Bhanu
Bhanu

Reputation: 253

Conditional Statements for terraform modules

We have two projects lets say A & B and three modules X,Y,Z (modules/X,Y,Z) for these two projects separately and do changes regularly & changes will be deployed to those A & B projects. Every time for a change we need to add in both project modules respective folders and its hard for us to track those changes.

Project A -> (modules/X,Y,Z)

Project B -> (modules/X,Y,Z)

We have decided to move identical modules to common folder and for different modules need to write conditional statements to work for respective projects.

Project A -> (modules/Z)

Project B -> (modules/Z)

(common/X,Y)

X & Y modules we have moved to common folder as both are identical and works for both projects whereas Z module has different changes which will not work in this case. Is there any option to write conditional statements to pick specific lines of code to get deployed for A & B projects.

Upvotes: 0

Views: 2020

Answers (1)

Tapan Hegde
Tapan Hegde

Reputation: 1328

As per my knowledge, terraform does not support direct if-else statements. Instead using 'count' we can achieve similar results.

If we set count = 1 for a particular resource , we will get one copy of that resource

If we set count = 0, No resources will get created.

In terraform, conditional expression can be written in below format.

condition ? true_val : false_val

Terraform just checks boolean condition in CONDITION and if value is true it will return 'TRUE_VAL' else it will return 'FALSE_VAL'

I guess when you are creating resources using module Z , you can use count + boolean condition expression to get expected results.

References:

https://medium.com/swlh/terraform-how-to-use-conditionals-for-dynamic-resources-creation-6a191e041857

https://www.terraform.io/language/expressions/conditionals

Upvotes: 1

Related Questions