Terraform: Branching (if/else/while/ etc) in terraform

Created on 5 Oct 2015  ยท  5Comments  ยท  Source: hashicorp/terraform

Hi all,

Is it a way to use if statements and while/for loops in terraform?

If yes, can someone show how and an example please?

PS :ย  Can anyone contribute to hashicorp projects source code, just by commiting here in github?

Thanks.

core question

Most helpful comment

here's how I'm faking out an if to select the right provider. It's terrible, but if you absolutely positively need a workaround, it'll do.

variable "dns_provider" { default = "none" }
# supporting multiple dns providers requires non-obvious code. It works
# by generating the count attribute from var.dns_provider. If the provider is
# supposed to be used, it will just pass count = 1 through. Otherwise, it
# defaults to count = 0.
# also note: because re2 doesn't support negative lookahead, we can't
# ensure that unexpected values are properly defaulting to count = 0. 
resource "aws_route53_record" "record" {
    count  = "${replace(replace(var.dns_provider, \"route53\", 1), \"/\A(ultradns)|(none)\z/\", 0)}"
# other attrs here...
}

resource "ultradns_record" "record" {
    count  = "${replace(replace(var.dns_provider, \"ultradns\", 1), \"/\A(route53)|(none)\z/\", 0)}"
# other attrs here...
}

All 5 comments

This is not yet supported. There is a discussion of use-cases for this in #1604, which you are welcome to add to.

...and yes, pull requests are welcome! For more details, see CONTRIBUTING.md.

Thank you @apparentlymart

here's how I'm faking out an if to select the right provider. It's terrible, but if you absolutely positively need a workaround, it'll do.

variable "dns_provider" { default = "none" }
# supporting multiple dns providers requires non-obvious code. It works
# by generating the count attribute from var.dns_provider. If the provider is
# supposed to be used, it will just pass count = 1 through. Otherwise, it
# defaults to count = 0.
# also note: because re2 doesn't support negative lookahead, we can't
# ensure that unexpected values are properly defaulting to count = 0. 
resource "aws_route53_record" "record" {
    count  = "${replace(replace(var.dns_provider, \"route53\", 1), \"/\A(ultradns)|(none)\z/\", 0)}"
# other attrs here...
}

resource "ultradns_record" "record" {
    count  = "${replace(replace(var.dns_provider, \"ultradns\", 1), \"/\A(route53)|(none)\z/\", 0)}"
# other attrs here...
}

Looks like @papiveron's question got answered - closing so we can keep conversation about conditionals consolidated in #1604 :+1:

I'm going to lock this issue because it has been closed for _30 days_ โณ. This helps our maintainers find and focus on the active issues.

If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.

Was this page helpful?
0 / 5 - 0 ratings