Vittal Angadi
Vittal Angadi

Reputation: 101

How to use if else-if else condition in Terraform

I am trying to change the stack name based on the environment. I tried the following:

stack_name = "intl-${var.intl_region}-${var.intl_ctry}-${var.intl_env}-jk-${var.vanity_env == "-np" || var.vanity_env == "-dr"} ? "mstr" : "master"}"

but getting the following error:

Error: Error parsing /build_workspace/workspace/GCM/PIPE_JENKINS/main.tf: At 33:25: nested object expected: LBRACE got: ASSIGN

Can some please help me how can I change the stack name based on the environment?

It should be like:

if a == a || b ? "c ": "d"

so:

a==b==c else d

Upvotes: 1

Views: 4874

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56997

You've got the syntax for the ternary slightly wrong there:

stack_name = intl-${var.intl_region}-${var.intl_ctry}-${var.intl_env}-jk-${var.vanity_env == "-np" || var.vanity_env == "-dr" ? "mstr" : "master"}

Note that the whole ternary statement sits inside the ${} construct.

As a complete example:

variable "intl_region" {
  default = "foo"
}

variable "intl_ctry" {
  default = "bar"
}

variable "intl_env" {
  default = "baz"
}

variable "vanity_env" {}

output "foo" {
  value = "intl-${var.intl_region}-${var.intl_ctry}-${var.intl_env}-jk-${var.vanity_env == "-np" || var.vanity_env == "-dr" ? "mstr" : "master"}"
}

And running it:

$ TF_VAR_vanity_env=-np terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

foo = intl-foo-bar-baz-jk-mstr
$ TF_VAR_vanity_env=-dr terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

foo = intl-foo-bar-baz-jk-mstr
$ TF_VAR_vanity_env=quux terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

foo = intl-foo-bar-baz-jk-master

Upvotes: 2

Related Questions