Igor
Igor

Reputation: 319

Terraform use conditional for AWS SecurityGroups

Is it possible to use Terraform conditional with AWS Security groups like this:

securitygroup= ["${substr(terraform.workspace) == "PD" ? module1 : module2}"]

We want to create and attach Security group based of module1 only if terraform.workspace begins with "PD", and we don't want to create Security group defined in module2 if it's not required.

We have tried this and the problem is that Terraform doesn't assign security group built by module1 if security group of module2 is not already created. Once we create both resources, it recognize and attach module1 okay, but then we are duplicating number of Security groups.

Looks like Terraform requires both resources active and created in it's conditionals?

Thanks in advance!

Upvotes: 1

Views: 1049

Answers (1)

Erebus
Erebus

Reputation: 2038

There is a known bug with TF where with interpolation, it evaluates both branches of a conditional (which is why it only works if you have both security groups created):

https://github.com/hashicorp/terraform/issues/15605

I'm running into the same problem with a different implementation - currently trying to use the suggestion from the second comment in the link above as a workaround:

This is a known issue with Terraform. The main workaround so far seems to be to find something to put in each branch that will run without error.

For example in what you describe you may be able to do something like this:

"${truthtest ? file("${truthtest ? var.file_path : "/dev/null"}") : ""}

Or since file("/dev/null") should equal "" just:

file("${truthtest ? var.file_path : "/dev/null"}")

Upvotes: 2

Related Questions