Option to make terraform variable to be ignored if missing

1.3k Views Asked by At

I have a .tftpl file which has the following code:

echo "running terraform on ${VAR_A} folder: ${VAR_B}"

in my main.tf I have the following, which call the above code to put variables:

terraform {
  required_version = ">= 0.13.1"
}

resource "local_file" "plan" {
  content  = templatefile("plan-pipeline-template.tftpl", var.generatedvars)
  filename = "${path.module}/plan-generated"
}

my variables.tf is as follows:

variable "generatedvars" {
  type = map
  default = {
  }
}

I exported as env variable only 1 variable:

export TF_VAR_generatedvars='{VAR_A="somestring"}'

so VAR_B is missing when the main.tf run the templatefile function.

when i run terraform plan, i get the following error:

Invalid value for "vars" parameter: vars map does not contain key "VAR_B"

I was expecting to see the following result

echo "running terraform on somestring folder: ${VAR_B}"

is there any way to tell templatefile function to ignore varuables that looks like this ${..} if they are not present?

1

There are 1 best solutions below

0
On

I don't think that's possible inside the template. Would it help you to build the actual command outside the template first and then pass it in as an argument?

locals {
  generatedvars = {
    VAR_A = "somestring"
  }
  command = "echo 'running terraform on ${lookup(local.generatedvars, "VAR_A", "")} folder: ${lookup(local.generatedvars, "VAR_B", "")}'"
}