Search code examples
terraform

Terraform - if variable is set


I want to set instance prefixes depending on wheter I have set an variable or not. When I set the variable instance_prefix I want to use the local variable called instance_prefix_new. When it's not set, I want to use the local variable called instance_prefix. Here are my variables and locals defined inside the module:

variable "project_name" {
  type        = string
  default     = null
}

locals {
  instance_prefix = "${data.openstack_identity_auth_scope_v3.project.project_name}.${data.openstack_compute_availability_zones_v2.zones.names[0]}"
  instance_prefix_new = "${var.project_name}.${data.openstack_compute_availability_zones_v2.zones.names[0]}"
}

I want to use it on the following line, if var.project_name is set, use local.instance_prefix_new, otherwise use local.instance_prefix_new

name            = "${local.instance_prefix}.${var.instance_name}${format("%02d", count.index + 1)}"

Solution

  • You are looking for the ternary operator. You would need to do something like the following:

    name = var.project_name == null ? "${local.instance_prefix}.${var.instance_name}${format("%02d", count.index + 1)}" : "${local.instance_prefix_new}.${var.instance_name}${format("%02d", count.index + 1)}"