1
votes

I have a bunch of terraform scripts to build one or more virtual machines along with relevant resources (nic, nfg, rg, data disks, extensions, roles, etc). I have variables defined in the variables.tf file for both Ubuntu and CentOS; however, I have to uncomment the ones I plan to use. Here is the code:

Variable definitions for Ubuntu image

variable os_publisher { default = "Canonical"}
variable os_offer { default = "UbuntuServer" }
variable os_sku { default = "18.04-LTS" }
variable os_version { default = "latest" }

Variable definitions for CentOS image

variable OS_publisher { default = "OpenLogic" }
variable OS_offer { default = "CentOS" }
variable OS_sku { default = "7.4" }
variable OS_version  { default = "latest" }

I'd like to modify my setup such that when the value of a single variable (say os_image) is set to ubuntu, TF automatically fills up the right values for the following block under the azurerm_virtual_machine resource in vm.tf:

storage_image_reference {
  publisher = "${var.os_publisher}"
  offer     = "${var.os_offer}"
  sku       = "${var.os_sku}"
  version   = "${var.os_version}"
}

And if the value for os_image is set to centos, it installs CentOS.

I looked at the if-else conditional and also at the lookup function plus the map/list options, but I am unsure on which one to use and how. I am open to other solutions as well.

I'd appreciate a response.

Thank you Asghar

1

1 Answers

1
votes

use map()

Use the first variable os_publisher as sample.

variable "os" {}

variable "os_publisher" {
  type = "map"

  default = {
    ubuntu = "Canonical"
    centos = "OpenLogic"
  }
}

So you can easily reference the value depend on which os is.

storage_image_reference {
  publisher = "${var.os_publisher[var.os]}"
  ...
}