Reminder of Objectives
- Deploy multiple virtual machines of varying RAM, CPU and Disk Sizes.
- Create 2 Virtual Machine Folders.
- Create a Virtual Distributed Switch.
- Attach the new virtual machines to the new VDS.
- Place the new Virtual Machines in the correct folder
In Part 1 I went through some folder structure and suggestions for organising the terraform files, now it’s time to start populating the files, i.e. terraform.tfvars, variables.tf and main.tf. I found when I started working on this mini-project that not many people have blogged about using the Terraform vSphere provider, the documentation provided by HashiCorp is quite detailed and they also provide a number of use case examples so it was a useful jumping off point, having said that… there was whole lot of trial and error involved to get the solution working. I’ve uploaded the finalised project to GitHub which can be found below.
The main challenge I had was creating multiple virtual machines of differing sizes, the solution was to define a ‘list’ variable for each virtual machine type, in the example on GitHub I’ve split them up in the ‘Web’ and ‘App’ virtual machine types, below is an example from the variables.tf files, here I declare the variable for machine types of ‘Web’ and ‘App’
Once the variables have been declared we then need to populate terraform.tfvars with the virtual machines specifications such as name, cpu, ram etc…
Main.tf code blocks
There are 3 code block types in the main.tf file, ‘provider’, ‘data’, and ‘resource’
- provider block – This denotes the type of terraform provider to be used for the project, in this case it’s vSphere.
- data blocks – represent infrastructure that you want to deploy on to, for example the VCSA, Datacenter, ESXi hosts etc…..
- resource blocks – represent new infrastructure, so what you intend to deploy e.g. VDS, virtual machines, folders etc..
The next step is to populate the main.tf file, we will add the virtual machine as a ‘resource’ block, as you can see Terraform will perform a ‘count’ operation on the list we populated in the terrafrom.tfvars file, it’s basically a ‘for’ loop, so for each indexed item in the list it will apply the values for CPU,RAM, etc…. to the indexed item, you can have as many virtual machines here as you want, for the purpose of demonstration I’ve included 2 virtual machines per virtual machine type. There’s lots of other stuff going on here such adding a static Mac-Address, adding the machine to the new port group on the VDS and adding multiple disks, I’ve made use of ‘lists’ in a number of places, if you look at the completed code on GitHub most of it should be quite self explanatory. If anything is unclear feel free to post a message and I’ll get back to you asap.