My goal is to schedule a Cron Job using GitHub Actions to destroy and reapply the same resource at specific times — for example, apply at 8 a.m. and destroy at 5 p.m.

Based on my research, I would run the command terraform destroy -target=xyz.resource_block_name.

Now, if I want to redeploy the exact same resource, would I run terraform apply -target=xyz.resource_block_name? Will this command apply only the Terraform code for that specific resource block (which configures the bastion host) and nothing else?

Also, will this create a new resource ID in Azure?

The Terraform code remains in the repository with the same resource block configuration — the only difference is that terraform destroy removed that resource from the state file.

Thank you.

3 Replies 3

The -target usage is actually as you expect it to work:

- terraform apply -target=xyz.resource_block_name will create ONLY the specified resource (and any dependencies).
- terraform destroy -target=xyz.resource_block_name will destroy ONLY the specified resource (and any dependencies) - as you commented.

Furthermore: YES, when you destroy a resource and then re-apply it, Azure will create a new resource with a new resource ID. Any manual configurations, connections, or data in the old resource will be lost.

Regarding the terraform state: After destruction, the resource is removed from the state file. Therefore, when you apply the IaC again, Terraform sees it as “missing” and creates a new one.

Note: I imagine you're aware, but it's worth a warning, relying on -target is not recommended as a long-term or complex workflow Terraform docs. It’s okay for simple and isolated resources, but it can cause state or dependency issues in larger setups.

Thank you GuiFalourd,

This is part of a large terraform infrastructure deployment, so the state file already has a lot of resource blocks to handle. So, for this isolated scheduled apply and destruction, in this case of an Azure Bastion Host, is there another method that won't cause state file issues?

I would suggest to move the Bastion resource into its own Terraform configuration and state file. This prevents state file conflicts and unintended side effects for the rest of your infra. This keeps your main state file clean, avoids race conditions or accidental resource deletions, and makes the automation safe and predictable (Here is a reference: Terraform: Recommended Practices - Separate State).

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.