Terraform import only when destroy

Hello!

After that I run terraform apply, ec2 instance creates some of the resources(AWS Cloudformation stacks), and I want when I run terraform destroy to destroy them. I have their names, id and etc.
How can I automate this process.

Hi @zeeman.a,

Terraform will only propose to destroy objects that it is directly managing, although providers are free to decide what exactly it means for an object to be “managed” by a particular resource instance, and some providers do treat secondary objects created as a side-effect of creating the main object as being managed by that resource instance, and will automatically delete the whole set of objects as part of deleting the Terraform resource instance.

For example, aws_cloudformation_stack in the hashicorp/aws provider handles delete by calling cloudformation:DeleteStack, which is documented to delete all of the objects being indirectly managed by the CloudFormation Stack. That means that you should not need to do anything special to have the objects you’re managing through that stack get destroy when the stack is destroyed.

If you want Terraform to delete something that isn’t automatically deleted as part of destroying some other object then you’ll need to change your approach to make Terraform be the one to create the object. A particular object should be destroyed by the same subsystem that created it.

If I’m understanding correctly that you are using Terraform to declare an EC2 instance which contains some software that then creates a CloudFormation stack using the CloudFormation API then your two options would be:

  • Change your design so that Terraform declares the CloudFormation Stack and then passes information from it into the EC2 instance, for example using user_data, so that the EC2 instance only uses the Cloudformation Stack, rather than managing it.
  • Include additional software in your EC2 instance which sends a cloudformation:DeleteStack request as part of the shutdown process, so that the EC2 instance is responsible for destroying the objects it created.

Terraform does not support an asymmetrical model where an object gets created by some other system but destroyed by Terraform. You must choose either to have Terraform manage the full lifecycle of the object, or to have your EC2 instance manage the full lifecycle of the object.