Home > Enterprise >  Terraform command line arguments doesn't work with conditional expression
Terraform command line arguments doesn't work with conditional expression

Time:05-23

I am trying to deploy a resource block either into dev or prod depending on the variable using conditional expression , for this i am trying to use command line argument. This work with terraform.tfvars but doesn't work with CMD arguments which means when i am trying to run terraform plan it doesn't not have any other changes.

ideally it should add 1 instance.

here is my resource block

main.tf file

resource "aws_instance" "dev" {

  ami           = "ami-0ca285d4c2cda3300"
  instance_type = var.instanceType
  count         = var.istest == true ? 1 : 0
}

resource "aws_instance" "prod" {

  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.micro"
  count         = var.istest == false ? 1 : 0
}

variables.tf

variable "istest" {
  default = true
}

terraform .tf vars is empty, command to run terraform

terraform plan -var="istest=false"

CodePudding user response:

I would recommend to use the following syntax instead of checking for the literal true or false value

resource "aws_instance" "dev" {

  ami           = "ami-0ca285d4c2cda3300"
  instance_type = var.instanceType
  count         = var.istest ? 1 : 0
}

resource "aws_instance" "prod" {

  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.micro"
  count         = var.istest ? 0 : 1
}

This way if the istest var is true it will deploy the dev instance.

And if it is false it will create the prod instance

Try

terraform plan -var="istest=false"

UPDATE

The core issue seems to be that terraform performs type conversions

Quoting from: https://www.terraform.io/language/expressions/type-constraints#conversion-of-primitive-types

The Terraform language will automatically convert number and bool values to string values when needed, and vice-versa as long as the string contains a valid representation of a number or boolean value.

true converts to "true", and vice-versa false converts to "false"

As a result you should explicitly set the type of the variable

In your variables.tf file

variable "istest" {
  default = true
  type    = bool
}

Then it should work as expected

terraform plan -var="istest=false"
  • Related