Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Terraform with if, else, elsif statement?

I'm setting up a terraform module to create an aurora cluster.
I need to have an option for cross region replication so i need to decide the region of the replica in relation to the source region.
Is there any way to do a multiple option conditional in terraform?

like image 861
ConscriptMR Avatar asked Apr 07 '19 05:04

ConscriptMR


People also ask

How do you do an if statement with 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.

Can we use if else in Terraform?

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

What is map type in Terraform?

Terraform variable Map Type Explained!!! Maps are a collection of string keys and string values. These can be useful for selecting values based on predefined parameters such as the server configuration by the monthly price.

What is local in Terraform?

Terraform Locals are named values which can be assigned and used in your code. It mainly serves the purpose of reducing duplication within the Terraform code. When you use Locals in the code, since you are reducing duplication of the same value, you also increase the readability of the code.


2 Answers

This is one way using the coalesce() function:

locals{
  prod = "${var.environment == "PROD" ? "east" : ""}"
  prod2 = "${var.environment == "PROD2" ? "west2" : ""}"
  nonprod = "${var.environment != "PROD" && var.environment != "PROD2" ? "west" : ""}"
  region = "${coalesce(local.prod,local.prod2, local.nonprod)}"
}
like image 189
victor m Avatar answered Sep 19 '22 13:09

victor m


locals {
  test = "${ condition ? value : (elif-condition ? elif-value : else-value)}"
}

For a more literal "if-elif-else" approach you can embed the if short hand with other ones to produce a similar effect. If you're use case is also inside a for loop, you can do that as well:

locals {
  test = {
    for i in list : 
      key => "${ condition ? value : (elif-condition ? elif-value : else-value)}"
  }
}

Will work in any situation where you would use the "${}" syntax

like image 33
MrJ1m0thy Avatar answered Sep 17 '22 13:09

MrJ1m0thy