Search code examples
terraform

Using a variable as map key in Terraform


environment_variables = {
    "S3_BUCKET" = var.s3_bucket, 
    var.env_name = true,
}

Is there a way to pass in a variable as a key for a map in terraform?

I am looking to pass in these environment variables and all custom ones will be prefixed with TAG_ which will be consumed within the lambda function. However, it doesn't seem like a variable can be used as map key?


Solution

  • What you have written here is what Terraform calls an "object constructor" expression, documented in Types and Values: Maps/Objects.

    The last paragraph of that section currently says:

    The keys in a map must be strings; they can be left unquoted if they are a valid identifier, but must be quoted otherwise. You can use a non-literal string expression as a key by wrapping it in parentheses, like (var.business_unit_tag_name) = "SRE".

    In your specific case, that would be:

    environment_variables = {
        "S3_BUCKET"    = var.s3_bucket, 
        (var.env_name) = true,
    }
    

    I suggest considering this design choice carefully. Allowing arbitrary environment variables to be defined has been the cause of some security vulnerabililties in the past since some software unfortunately assumes that environment variables are being set only by a trusted operator. A historical example is the "Shellshock" problem that affected older versions of Bash.

    You mentioned that all of the custom ones will start with TAG_, and so one way to reduce the risk of such problems would be to include a validation rule on your input variable, so at least then the potential vulnerabilities would be limited only to software that interprets environment variable names starting with TAG_:

    variable "env_name" {
      type = string
    
      validation {
        condition     = startswith(var.env_name, "TAG_")
        error_message = "The variable name must have the prefix 'TAG_'."
      }
    }
    

    (This would not actually have helped with Shellshock in particular since that problem applied to any environment variable name where the value started with certain characters -- it was the value rather than the name that triggered those problems -- so I still recommend caution.)