Automating vSphere VM Deployment with Terraform and Variable Maps

Using Terraform Variable Maps to Simplify VM Deployment with vSphere Templates

Over the past few weeks, I have been working on a project that has allowed me to improve my Terraform skills. One of the key challenges I faced was deploying VMs based on specific vSphere templates. Rather than having one set of Terraform declarations per template, resulting in code duplication, or tying declaration variables to specific operating systems and changing depending on what is being deployed, I looked for a way to make it even more “singularly declarative.”

The solution I found was using Terraform variable maps. By groupings like variables in one block declaration, these map values are then fed through to the rest of the Terraform code. This approach allowed me to logically separate what was being configured and made it easier to manage and maintain the code.

Here’s an example of a maps.tf file that I have separate from the variables.tf file:

“`

variable “vsphere_linux_distro” {

default = “Ubuntu”

}

map “ubuntu” {

template_password = “my_secret_password”

remote_exec_call = “sudo firewall-cmd –permanent –add-rule ipv4 input ssh”

}

map “centos” {

template_password = “my_other_secret_password”

remote_exec_call = “sudo firewall-cmd –permanent –add-rule ipv4 input ssh”

}

“`

In the above maps, we have a standard variable that is the only variable that changes and needs to be set: vsphere_linux_distro. Depending on the value of this variable, Terraform will lookup the linux_template variable and map it with the various mapped values. The data source that dictates what template is used builds the name from the lookup function of the base variable and the map value.

The values we set in the maps are being used to execute the right command depending if it is Ubuntu or Centos, and also use the correct password depending on the linux_distro set. The declared variable can either be set in the terraform.tfvars file or passed through at the time of plan execution.

The result is a more controlled and easily managed way to use Terraform to deploy VMs from different pre-existing VM templates. The variable mappings can be built up over time and used as a complete library or different operating systems with different options. It’s another awesome feature of Terraform!

References:

* https://www.terraform.io/docs/configuration-0-11/variables.html#maps

Copyright © 2024 VIRTUALIZATION IS LIFE!. Powered by WordPress & Infinite Theme