Reputation: 2358
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?
Upvotes: 66
Views: 195695
Reputation: 1412
Seems these days you can also use try
to check if something is set.
try(var.env, false)
After that your code will work since var.env
is now defined with the value false
even if var.env
was never defined somewhere.
https://www.terraform.io/docs/configuration/functions/try.html
Upvotes: 110
Reputation: 998
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.
Upvotes: 41
Reputation: 1642
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
Upvotes: 19