This is part three of a series aimed at getting you going with Terraform in a vSphere environment. The series will assume you understand the concepts of IaC and Terraform, at a basic level. In part one, we setup Terraform and created a basic definition to create a virtual datacenter. In part two we initialised the Terraform folder to make sure we had the correct provider downloaded. We then produced a plan of the changes our definition will make. In this post we will apply the change, see our change take affect and then destroy the resource.
Now we have our plan file (newDC.plan) and our Terraform folder contains the required vSphere Provider file, let us go ahead and apply our definition. This will create our new datacenter object in our vSphere inventory. Open a command prompt and navigate into the \terraform\deploy_datacenter folder. To apply a definition we use the terraform apply command. There are multiple switches that can be used to control the behaviour, but since we have a plan already saved, we can omit many of these. We can apply our definition by executing the following command
terraform apply newDC.plan
As we can see, once the terraform apply command is called, we can see Terraform processing the plan. The vsphere_datacenter.dc object is created and we can see a message stating the apply command is complete. As you can see we have added one resource (our new datacenter) whilst changing and destroying nothing else. If our plan changed a setting or destroyed an infrastructure component, we would see this stated here as well. Checking the vSphere inventory we can see that our_new_datacenter, was indeed created.
Now that we have applied our plan, if you have a look in our \terraform\deploy_datacenter folder we can see there are two new files. These files were created by Terraform when we executed the plan. One of the files is the state file, the other is a backup of the state prior to the definition being applied.
Terraform cannot work without the state files. The state file allows Terraform to track the infrastructure it is affecting, recording the infrastructure components, their settings (configuration) and dependencies between each other. Without storing a state, Terraform would not know what to do or when to do it. It is not advisable to store state locally as we are here, but for testing and learning it is perfectly fine. In a future post I will discuss how to properly manage your state files.
Let’s assume that we no longer need our datacenter. Rather than destroy it outside of Terraform (which would result in an out of date state file) let’s use Terraform to do it for us. Execute the following command to destroy the resource
terraform destroy -var “datacenter=our_new_datacenter”
Terraform will print out to the console what resources will be affected by the command. When you are happy, type yes to confirm the destruction.
If you look in your vSphere inventory, you will now see that the datacenter resource has been destroyed.