Youssef CH
Youssef CH

Reputation: 741

terraform dynamic input argument value based on condition

i 've this main.tf file :

resource "google_compute_instance" "prod" {
  count = var.is_test == false ? 1 : 0 #condition : if the is_test = false , create 1 instance of vm
  name         = "vm-prod"
  machine_type = "e2-medium"
  zone         = "us-central1-c"
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }
    network_interface {
        network = "default"
    access_config {
    }
  }
}

resource "google_compute_instance" "dev" {
  count = var.is_test == true ? 3 : 0 #condition : if the is_test = true, create 3 instance of vm
  name         = "vm-dev"
  machine_type = "e2-small"
  zone         = "us-central1-b"
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }
   network_interface {
        network = "default"
    access_config {
    }
  }
}

and variables.tf file :

variable "is_test" {
  type = bool
  description = "env"
  default = true
}

i use is_test variable to choose the env, to privsion the vm

now , i want to delete the value of inputs arguments from main.tf and make them in terraform.tfvars .

How i can do that ? How i can make the value of input arguments dynamically based on condition ?

i mean : if the env is dev , the size of vm is small , the region is in us-central1-b ..

if the env is prod , the size of vm is medium , ... Thanks

Upvotes: 0

Views: 1056

Answers (2)

tomarv2
tomarv2

Reputation: 833

I would do it this way, so you dont have to repeat the code and tfvars file:

resource "google_compute_instance" "instance" {
  name         = var.is_test == false ? "vm-prod" : "vm-dev"
  machine_type = var.is_test == false ? "e2-medium" : "e2-small"
  zone         = var.is_test == false ? "us-central1-c" : "us-central1-b"
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }
    network_interface {
        network = "default"
    access_config {
    }
  }
}

Upvotes: 2

main.tf

resource "google_compute_instance" "my_instance" {
  count = var.instances
  name         = var.name
  machine_type = var.machine_type
  zone         = var.zone
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }
    network_interface {
        network = "default"
    access_config {
    }
  }
}

dev.tfvars

instances = 1
name = "vm-dev"
machine_type="e2-small"
zone="us-central1-b"

prod.tfvars

instances = 3
name = "vm-prod"
machine_type="e2-medium"
zone="us-central1-c"

run the command

terraform apply -var-file="dev.tfvars"
terraform apply -var-file="prod.tfvars"

Documentation: Terraform Input Variables

Upvotes: 2

Related Questions