Destroy specific resource using terraform cloud

we can destroy azure VM using terraform CLI. Is there any way we can integrate this feature in terraform cloud and dynamically delete resources based on the variables defined in the workspace?

Hi @mondalsukanta,

The typical way to delete an object in Terraform CLI is to remove the resource block that defined it and then run terraform apply, so Terraform will see that it’s no longer needed and destroy it. That same workflow is available in Terraform Cloud too.

Is that what you’re asking about, or do you have a different operation in mind?

Hi,
Thanks for the reply.

destroy infrastructure feature destroy all the resources associated with the plan. But i am looking for a Terraform Cloud solution that can take custom resource name to destroy. My requirement is to create two workspaces - 1) build a VM 2) destroy the same VM or some resource associated with the VM

Hi @mondalsukanta,

Removing the VM’s resource block from your configuration and then sending that modification to Terraform Cloud to be applied is the standard answer to this, as I was saying in my previous comment. If you can say a little more about why that answer doesn’t work for you then I might be able to offer an alternative, but it’s not clear from what you’ve said so far what constraints you have which make that answer not appropriate.

Hi @mondalsukanta :blush:
The thing is that dynamic deletion of real-life objects (i.e. VM) without appropriate change in the Terraform code conflicts with the principle of IaC – the code is the single source of truth. It is illogical to have VM described in the code and do not have it as real-life object in your infrastructure. Therefore, you need to define the state of real-life objects in the code first, then apply this.

However, if I got your initial idea clear, the usage of count meta argument may help.

Quick example:

resource "aws_instance" "this" {
  count    = var.instance_num
  argument = value
  ...
  ...
}

If instance_num == 0, you will have 0 resources of aws_instance type.

Another example:

resource "aws_eip" "this" {
  count    = var.has_eip ? 1 : 0
  instance = aws_instance.this.id
}

This is conditional resource creation. If has_eip == true, then 1 resource of aws_eip type will be created, otherwise 0.

I didn’t try this yet, but i will do a proof of concept :ok_hand:
Thanks so much.

Thanks a lot for the tips and example.

1 Like