I am using Terraform to build my Infrastructure in Azure DevOps using the Task Group feature to keep it generalised. To do this I am using the Terraform Extension from Peter Groenewegen and remote state in Azure Blob Storage.
Thought I would share my setup in the hope that it would be useful for others.
My Task Group is comprised of 2 steps, the Plan & the Apply:
The first part of my Plan setup looks like the below:
In the Terraform template path I have used a mixture of built-in system variables and a custom parameter that can be defined in your pipeline
The system parameters can be found here
In the Terraform arguments section I have entered the path to my environment var file. Again I have used the system variable $(Release.EnvironmentName) and ensured that the folder within my Terraform Repo is named exactly the same, along with the tfvars file. This ensures you can keep the Task Group generalised throughout the pipeline.
I have ticked the Install Terraform box to ensure Terraform is installed on the Build Agent.
I have also ticked the Use Azure Service Principal Endpoint Box as per the Terraform best practice guidelines.
The last part of my Plan setup looks like the below:
In this section I declared that I went the state initialised in Blob storage and give the details of where I want this to be stored. Again keeping it generalised by using the system variables.
Within my Terraform code, the Main.tf file has this at the start so it knows to use the remote state:
The structure of my Terraform is as below, with the backend.tfvars sitting alongside my $environment.tfvars file. This means you could have completely different settings for each remote state if you wanted. I have it this way as devci1 & qa1 sit in a different subscription to uat1 & prod, so use different blob storage. I also seperate each state into different containers within the blob storage to keep it organised as you will see in the next screenshot.
The backend.tfvars file looks like the below. The main thing to note is that I change the container name to match the environment (I have changed this to be hard coded for this post but would usually just use the variable to pass the value in to avoid mistakes)
The Terraform Apply section is exactly the same apart from the Terraform arguments section. It has Apply rather than Plan and most importantly the -auto-approve means it doesn’t require any human intervention.
apply -var-file=”./environments/$(Release.EnvironmentName)/$(Release.EnvironmentName).tfvars” -auto-approve
Hope you find this post useful and it will help you to build your Infrastructure in Azure using Azure Devops & Terraform.
Any questions just get in touch via Twitter
Please follow and like us: