Merge more than 2 tfvars file contents

.tfvars file processing happens before any configuration expressions are evaluated, so there is no way to do exactly what you asked about here: the rule for .tfvars files is always that the last definition of a particular variable “wins”, as you’ve seen.

The some options that are close to what you want here would be:

  • Define three different variables, perhaps named to indicate the three different sources that are providing these values, and then concatenate the three of them together in a local value:

    locals {
      all_api_stages = concat(
        var.a_api_stages,
        var.b_api_stages,
        var.c_api_stages,
      )
    }
    

    This approach would be appropriate only if there being exactly three sets of variables is a meaningful constraint for your system.

  • Declare the actual stage objects inside your configuration and make the variable instead be a list of keys for them:

    variable "api_stages" {
      type = set(string)
    }
    
    locals {
      api_stages = {
        x = {
          api_id = "xxxx"
          stage  = "play"
        }
        y = {
          api_id = "yyyy"
          stage  = "play"
        }
        z = {
          api_id = "zzzz"
          stage  = "play"
        }
      }
    }
    

    You can then use -var when running Terraform to choose the appropriate settings, instead of using -var-file:

    terraform apply -var='api_stages=["x", "y"]'
    

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top