Terraform conditionals - if variable does not exist

Viewed 85341

I have the following condition:

resource "aws_elastic_beanstalk_application" "service" {
  appversion_lifecycle {
    service_role          = "service-role"
    delete_source_from_s3 = "${var.env == "production" ?   false : true}"
  }
}

If var.env is set to production, I get the result I want.

However if var.env is not defined, terraform plan will fail because the variable was never defined.
How can I get this to work, without ever having to define that variable?

3 Answers

if you are using Terraform 0.12 or later, you can assign the special value null to an argument to mark it as "unset".

variable "env" {
    type = "string"
    default = null
}

You can't just leave it blank, not with the current versions.

You can have the default of the variable set to an empty string:

variable "env" {
  description = "Env where the module is deployed."
  type        = string
  default     = ""
}

Once that is done, your check var.env == "production" will produce false and the argument delete_source_from_s3 will be assigned to the value true.

Side note, there is no need for interpolation in the statement,

"${var.env == "production" ? false : true}"

just go with,

delete_source_from_s3 = var.env == "production" ? false : true

https://discuss.hashicorp.com/t/how-do-write-an-if-else-block/2563

Related