Terraform environment specific variables

Viewed 12138

Anyone know if there's a way to populate variables in Terraform based on what the environment/workspace is? Preferably one that

  • populates the var namespace (ie not an external data source),
  • doesn't require a wrapper
    • like tf(){ terraform --var-file=$(get_tf_env).tfvars
  • takes effect by changing a terraform env/workspace, without any additional manual steps (ie steps that aren't triggered by running terraform env )?
6 Answers

Handling environmental variables in Terraform Workspaces -Taking Advantage of Workspaces, by Miles Collier 2019 explains clearly how this works. This is just a summary.

In parameters.tf:

locals {
   env = {
      default = {
         instance_type  = "t2.micro"
         ami            = "ami-0ff8a91507f77f867"
         instance_count = 1
      }
      dev = {
         instance_type  = "m5.2xlarge"
         ami            = "ami-0130c3a072f3832ff"
      }
      qa = {
         instance_type  = "m5.2xlarge"
         ami            = "ami-00f0abdef923519b0"
         instance_count = 3
      }
      prod = {
         instance_type  = "c5.4xlarge"
         ami            = "ami-0422d936d535c63b1"
         instance_count = 6
      }
   }
environmentvars = "${contains(keys(local.env), terraform.workspace)}" ? terraform.workspace : "default"
   workspace       = "${merge(local.env["default"], local.env[local.environmentvars])}"
}

To reference a variable, add to locals or pass this to a module:

instance_type = "${local.workspace["instance_type"]}"

This will use the value from the selected workspace, or the default value if either the variable is not defined for that workspace, or no workspace is selected. If not default is defined, it fails gracefully.

Use terraform workspace select dev to select the dev workspace.

I use terraform workspace and created a bash script to echo the --var-file argument.

#!/bin/bash

echo --var-file=variables/$(terraform workspace show).tfvars

To run terraform with tfvars applied by workspace

terraform plan $(./var.sh)
terraform apply $(./var.sh)
Related