Part 2 - Provisioning vSphere VMs with Terraform

In the first part of this blog series we looked at what Infrastructure as Code is, and some of the kinds of software we can use to orchestrate and manage our datacentres. In this part we’re going to run through the basics of creating virtual machines in vSphere with Terraform.

There’s two main files we’re predominently interested at this point to allow us to interact with vSphere. First we have our variables file:

In here you would typically set the values that could be re-used across different Terraform builds, for example in the above example we’re defining a default VM template, a default network, and our vSphere credentials, etc.

It’s important to notice that we’ve obfuscated things like credentials into a secondary file called terraform.tfvars, these can then be excluded from your source control platform in .gitignore (assuming you’re using Git).

Now that we’ve defined our variables we can get into the meat of the configuration.

Here’s the core terraform config file

The first code block here is where we tell Terraform what Provider we’re using, in our case vSphere, and the appropriate options for the Provider. In this example we’re also telling Terraform to accept unverified SSL certs to get around any self-signed certificate errors in vSphere.

After we define our Provider we can get into the business of defining resources. In our example we’re defining two seperate VMs, but they’re pretty much the same at this point. In the resource block we define characteristics such as hostname, number of vCPUs, memory, etc, and then define network and disk information.

In my lab the VMs all pick up a DHCP address automatically, but you can easily define further network settings like so:

Network settings

So now we have the basics of two VMs ready to be automagically built within your vSphere environment by Terraform, how do we run this?

First it’s important to remember that Terraform will parse all the files in the working directory, so you should break out your apps or configurations into specific folders. This being a test Terraform config for a 2-tier web app, mine looks like this:


First we have to run terraform init to install the vSphere Provider (this only has to be done once), and then we can run terraform plan to dry-run the proposed build steps. In our case we should see a result that looks like this: Plan: 2 to add, 0 to change, 0 to destroy.

All being well we can now run terraform apply. At this point you can sit back and wait, and watch the magic happen in vSphere:


If we check back to our CLI, Terraform will also confirm that it has finished, and our VMs are provisioned with the settings we specified and ready to go:


There we go, and if we look in vSphere we’ll see them up and online, huzzah!


In part 3 we will now look at how to use an additional Provisioner to install and manage the software configuration of these VMs.