Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform conditionals - if variable does not exist

Tags:

terraform

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?

like image 364
sebastian Avatar asked Nov 08 '18 02:11

sebastian


People also ask

How do you write if condition in Terraform?

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.

How do you conditionally create resources in Terraform?

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."

How do you use a loop in Terraform?

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.

Can we use if else in Terraform?

As you (probably) know, Terraform doesn't support if statements.


2 Answers

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

like image 89
Erik-Jan Riemers Avatar answered Sep 19 '22 07:09

Erik-Jan Riemers


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.

like image 28
Shiv Rajawat Avatar answered Sep 19 '22 07:09

Shiv Rajawat