SBKDeveloper
SBKDeveloper

Reputation: 693

How do I set a computed local variable

I have a tf.json file that declares a bunch of local variables. One of the variables is a array of complex objects like so:

{
  "locals": [
    {
      "ordered_cache_behaviors": [
        {
          "path_pattern": "/poc-app-angular*",
          "s3_target": "dev-ui-static",
          "ingress": "external"
        }
      ]
    }
  ]
}

Here is what I want to do... instead of declaring the variable ordered_cache_behaviors statically in my file I want this to be a computed value. I will get this configuration from a S3 bucket and set the value here. So the value statically will only be an empty array [] that I will append to with a script after getting the data from S3.

This logic needs to execute each time before a terraform plan or terraform apply. What is the best way to do this? I am assuming I need to use a Provisioner to fire off a script? If so how do I then set the local variable here?

Upvotes: 1

Views: 808

Answers (1)

Adil B
Adil B

Reputation: 16778

If the cache configuration data can be JSON-formatted, you may be able to use the s3_bucket_object datasource plus the jsondecode function as an alternative approach:

Upload your cache configuration data to the poc-app-cache-config bucket as cache-config.json, and then use the following to have Terraform download that file from S3 and parse it into your local ordered_cache_behaviors variable:

data "aws_s3_bucket_object" "cache_configuration" {
  bucket = "poc-app-cache-config"
  key    = "cache-config.json" # JSON-formatted cache configuration map
}

...

locals {
  ordered_cache_behaviors = jsondecode(aws_s3_bucket_object.cache_configuration.body)
}

Upvotes: 2

Related Questions