Getting Started with Terraform on Azure DevOps

Introduction

As with most things, there are a number of ways to utilize Azure DevOps to orchestrate your management of Azure Resources through terraform. This post will walk through a way that I have found to be successful and relatively easy to maintain. It will not however describe the many benefits of using an Infrastructure as Code approach, as that is a much broader topic.

To follow along with the example below, please ensure you have the Multistage pipeline feature enabled, this is still in preview as of the publishing of this post.

Contents

Prior to using terraform to deploy infrastructure on Azure, there are a few setup steps. The first is to create an Azure Resource Manager service connection within Azure DevOps. From there, I recommend using a script to setup needed variables in KeyVault, but this can be accomplished through the portal, powershell, or through individual az cli commands.

The script I use for this creates a resource group, a keyvault, and a service principal. The service principal will be used by Terraform for it’s interactions with Azure Resource Manager.

The KeyVault you created can then be used in Azure DevOps by creating a variable group that is linked to it.

I recommend using a consistent folder structure for your pipeline and terraform configuration. This allows you to more easily maintain your code, but also significantly improves the usability for future developers. In my case, I like to have a pipelines folder that contains the main pipeline.yml for orchestrating the overall process and a templates folder that contains my pipeline templates.

The initial section of the pipeline are environment independent actions that should only need to be performed once. This is similar to build and unit test phase for an typical application deployment.

For simplicity, I am using template files for the individual steps. For the Setup phase, this includes formatting, init, and validation.

The fun part is the actual deployment. This can be separated into stages for each of the different environment you want to deploy resources. The first job in the deployment is plan, and as you might imagine runs terraform plan. The second job is apply, and this runs terraform apply.

Conclusion

There are many ways to deploy Azure Resources. Hopefully this post provides some ideas on how you can use an Infrastructure as Code approach to deploy using Azure DevOps and Terraform. This link shows a working example that utilizes this approach.

Authors