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?
Terraform doesn't support if-statements, so this code won't work. However, you can accomplish the same thing by using the count parameter and taking advantage of two properties: If you set count to 1 on a resource, you get one copy of that resource; if you set count to 0, that resource is not created at all.
You can use count block with Conditional Expressions (condition ? true_val : false_val) to create a resource based on variable value. description = "default condition value is true."
Using the count meta-argument The count meta-argument is the simplest of the looping constructs within Terraform. By either directly assigning a whole number or using the length function on a list or map variable, Terraform creates this number of resources based on the resource block it is assigned to.
As you (probably) know, Terraform doesn't support if statements.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With