简体   繁体   中英

How to conditionally update a resource in Terraform

Seems it's common practice to make use of count on a resource to conditionally create it in Terraform using a ternary statement.

I'd like to conditionally update an AWS Route 53 entry based on a push_to_prod variable. Meaning I don't want to delete the resource if I'm not pushing to production, I only want to update it, or leave the CNAME value as it is.

Has anyone done something like this before in Terraform?

Currently as it stands interpolation syntax isn't supported in lifecycle tags. You can read more here . Which will make this harder because you could use the "Prevent Destroy". However, without more specifics I am going to take my best guess on how to get your there.

I would use the allow_overwrite property on the Route53 record and set that based on your flag. That way if you are pushing to prod you can set it it false. Which should trigger creating a new one. I haven't tested that.

Also note that if you don't make any changes to the Route53 resource it should trigger any changes in Terraform to be applied. So updating any part of the record will trigger the deployment.

You may want to combine this with some lifecycle events, but I don't have enough time to dig into that specific resource and how it happens.

Two examples I can think of are:

type = "${var.push_to_prod == "true" ? "CNAME" : var.other_value}" - this will have a fixed other_value , there is no way to have terraform "ignore" the resource once it's being managed by terraform.

or

type = "${var.aws_route53_record_type}" and you can have dev.tfvars and prod.tfvars , with aws_route53_record_type defined as whatever you want for dev and CNAME for prod.

The thing is with what you're trying to do, "I only want to update it, or leave the CNAME value as it is.", that's not how terraform works. Terraform either manages the resource for you or it doesn't. If it's managing it, it'll update the resource based on the config you've defined in your .tf file. If it's not managing the resource it won't modify it. It sounds like what you're really after is the second solution where you pass in two different configs from your .tfvars file into your .tf file and based off the different configs, different resources are created. You can couple this with count to determine if a resource should be created or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM