Dave Berthiaume
Dave Berthiaume

Reputation: 3

Is there any way to reference to old plan in terraform?

I'm trying to setup a pipeline that creates a new alias in my cloudfront distribution automatically with terraform, but all I've been able to do is replace what's already there. I'd like to append a new value to what is there already. I tried something like this:

resource "aws_cloudfront_distribution" "web_distribution" {
    origin {
        domain_name = "${aws_s3_bucket.web.bucket_domain_name}"
        origin_id   = "S3-${aws_s3_bucket.web.id}"
    }
    enabled = true
    is_ipv6_enabled = true
    aliases = "${compact(concat(list("${var.url_prefix}.${var.zone}"), list("${aws_cloudfront_distribution.web_distribution.aliases}")))}"

Where "${var.url_prefix}.${var.zone}" is essentially a dynamically generated URL based on my gitlab branch name. But I get the following error:

Error: aws_cloudfront_distribution.web_distribution: aws_cloudfront_distribution.web_distribution: self reference not allowed: "aws_cloudfront_distribution.web_distribution.aliases"

Is there any workarounds to do this ?

Upvotes: 0

Views: 87

Answers (1)

Jordan
Jordan

Reputation: 4512

While there is technically a way to accomplish this using the Remote State data source (i.e. read the CloudFront distribution aliases from the existing state file, then append a new value to it, then use that expanded list as the input value for the CloudFront resource), it's almost certainly a very bad idea™. It would create a nasty loop and there would be no easy way to reset the list of aliases.

Terraform is "infrastructure-as-configuration" and is intended to have all of the configuration specified in the Terraform files; the configuration should not depend on previous output of the same Terraform source.

My point is, the full list of aliases should be defined somewhere; if you do it the way I described above, the list won't be defined anywhere but in the existing state file, which is where it's not intended to be. It can be defined in a file within the Terraform configuration (either in TF language or in an external file that's loaded by Terraform) or can be in a remote location (like an S3 file, an SSM parameter, etc.), but it needs to be somewhere that can easily be modified and doesn't get changed each time Terraform is run.

Upvotes: 1

Related Questions