is there an option to destroy a resource by giving it some attribute in the tf file? for example, I have a security group and I want to delete it and after some days I may want the security group back at that time I just want to toggle the attribute. essentially the attribute should indicate if the resource is required or should be deleted.
we already have terraform destroy and terraform state rm but neither of them are git commitable.
While there may be some more features in the future to add the ability to “forget” resources from the configuration, since you want to be able to add and remove the resource, I don’t think that is what you are looking for.
If you actually want to destroy the resource and add it back later, you would want to modify the configuration in some way specifically so that it can be tracked by Terraform.
This is usually done by using count or for_each on the resource, reducing the number of of instances to 0 when you want to destroy the resource, and increasing the instance count to 1 or more when you want that resource back.
You can even go so far as to comment out or remove the resource from the config, which also would be recorded in version control, but doesn’t really offer any benefit for integrating with the rest of the configuration and may require other changes to keep the configuration valid.
I use logical conditions for creation / deletion of Route 53 entries, maybe you can use the same.
Example (inside a module that creates EC2 instances):
If var.register_dns_private is true, the DNS record is created for the EC2 instance, if it its false and exists in AWS, then it will be deleted by Terraform.
resource "aws_route53_record" "private" {
count = var.register_dns_private ? 1 : 0
zone_id = var.route53_private_zone_id
name = var.tag_private_name
type = "A"
ttl = "300"
records = [aws_instance.default.private_ip]
}
Since var.register_dns_private is defined/derived in a terraform.tfvars or in a tf file, its value is tracked by git.