While preparing a Kubernetes course, I had to put in place a cloud infrastructure for future students so as they can perform the tasks of the course.
Basically, I had to provision a couple of Vitual Machnines and a virtual network. Which is no big deal if you have to do it once. But Since we’re planning on having multiple classes on different periods of time, it could be a good idea to automate the provisioning and deletion of classes.
To achieve this we’ll be using Terraform s Azure Provider to create our cloud resources for the course.
Only prerequirement is to generate an Azure Service Principal Account Credentials for your Azure Cloud Subscription.
Then setup your terraform folder where the *.tf files will be.
terraform.tfvars
We declare variable values here, they’ll be used afterwards in our terraform scripts.
variables.tf
We declare our variables here, subscription credentials, a map and a list of strings.
main.tf
The main.tf file is where we specify which terraform version we’ll be using and which provider as well. Here, it’s the azurerm provider.
We need to precise the providers variables so it can authenticate to our Azure Subscription. These variables are fetched from the terraform.tfvar file.
Also the Azure resource group, virtual network and subnet blocks as they are central resources, but you can also just put them in a separate file.
vms.tf
This is the bloc that will allow us to create a Virtual machine per Student, give it a static IP within the subnet and create credentials of the student for that VM. to do so, it will loop through the map and list of strings we wrote in the variables.tf file, creates and configures each student’s VM.
Per example, student1 will get internal-vm1 with the private IP 192.168.1.11, he can access it with the student1:student1 username:password pair.
** Change the xxxx-xx….xxxx characters with your Azure subscription ID.
Provision the Infrastructure
Okey now we’re all set. We can init, plan, apply and destroy our resources with the provided terraform scripts. Make sure they’re in the same directory.
So the day we have a planned class, we can mount the cloud infrastructure for it with the right number of students, all we have to do is to append the list of strings in the variables.tf file.
Provision the class resources
Destroy the class resources
That’s it, we now have a Cloud Virtual class Infrastructure with a dynamic number of students. Using terraform gives us the flexibility to switch to other Cloud providers easily.