Terraform, an open-source infrastructure as code software tool developed by HashiCorp, is built with the goal of simplifying the deployment and management of cloud services. Now, it supports almost all the cloud providers, including Azure. The objective of this guide is to give a detailed perspective of Terraform on Azure that brings together the capabilities of declarative infrastructure management with the wide range of Microsoft Azure services.
What is Terraform and Why Use It?
Terraform is an infrastructure-as-code tool. Using this tool, you can define configuration files that allow you to deploy and configure infrastructure-based resources. So let’s get an example: a company needs to host an application on a set of infrastructure-based resources. If you’re familiar with the Azure cloud, you already know how to host applications on Azure virtual machines, host data within Azure Storage accounts and Azure SQL databases.
Sometimes you may provision these resources manually via the cloud web console and then deploy the application. But let’s assume there is an application that also has a test environment in place. As part of this environment, you have the same set of resources that need to be deployed. There are:
- Two VMs
- One Azure Storage account
- One Azure SQL database.
Now whenever the testing phase starts, you need to create these resources and deploy your application. As soon as the testing is complete, you need to go ahead and delete the infrastructure because, you know, keeping this infrastructure in place increases costs. When the testing phase is complete, you delete the resources. Whenever testing is required to be conducted again, you recreate the resources and deploy the application. The newer version of the application test is complete. Then we need to go ahead and delete the environment again. So all of this is a headache.
Azure Code Configuration File
As a DevOps/Cloud engineer, you may need to recreate the environment repeatedly with the same environment, the same set of virtual machines, the same Azure SQL database, and the same storage account. It’s a manual task, and you need to recreate the environment every time. Secondly, the repeated task of recreating resources is also prone to errors.
You need to have an infrastructure that always has the same configuration. But when you’re manually creating resources, you are prone to making errors. You might put in the wrong configuration for one of the infrastructure-based resources. So we can avoid all of this. We can define the infrastructure that we want to have at hand by using or declaring it within a code configuration file. This code configuration file would declare all of our infrastructure base resources, and then we can use Terraform to deploy the resources on demand using that configuration file.
How to Set Up Terraform on Azure
- First, you need to get Terraform on your local machine. Go to the terraform documentation page and when it comes onto the various downloads available for Terraform. You have it available for Mac OS, Windows, Linux, etc. Since I’m on a Windows-based device and this demo, you can see how to set up terraform on Windows.
- Under the Operating System heading, select the Windows tab. The latest version is preselected.
- Select 386 for 32-bit systems or AMD64 for 64-bit systems.
- Unzip the downloaded file. (use the C:\terraform path) Remember this location so you can add the path to the environment variables.
You don’t need to run the file; add Terraform to the Windows environment variables so that the system recognizes it. - To add the Terraform executable to the system’s global path: Open the start menu, start typing environment , and click Edit system environment variables. The System Properties window opens.
- Click the Environment Variables button.
- Select the Path variable in the System variables section to add terraform for all accounts. Alternatively, select Path in the User variables section to add terraform for the currently logged-in user only. Click Edit once you select a Path.
- Click New in the edit window and enter the location of the Terraform folder.
Select the “Path” variable and click “Edit.” Append the path to the Terraform executable to the end of the variable value (e.g., C:\terraform\terraform.exe). Finally, click OK on all windows to apply the changes.
How to Verify Installation
Open a new command-prompt window and enter the command to check the Terraform version:
terraform -version
Everything is set. We have Terraform now running on our local machine.
Now you need to configure Azure CLI to authenticate Terraform with the Azure cloud. Go to the Microsoft official website and download and install Azure CLI on your operating system.
Setting Up the Terraform Azure Provider
When you come on to building your terraform files you need to provision Terraform Azure provider block on your Terraform code. Azure provider will allow you to work with the Azure Cloud Platform. Basically, the Azure terraform provider has many versions because Azure itself keeps on updating its services and it keeps adding new features.
When you add new features, the provider needs to make use of these features. Anything that Azure changes, the provider has to change as well. In the end, what the provider is doing is calling the APIs, the application programming interfaces that are made available by Azure. Those APIs interact with the Azure-based services. So, the provider also needs to be up to date.
Terraform Azure Provider:
1 2 3 4 5 6 7 8 9 10 11 12 |
terraform { required_providers { azurerm = { source = "hashicorp/azurerm" version = "4.21.1" } } } provider "azurerm" { # Configuration options } |
Terraform Azure Features and Benefits
- Declarative Infrastructure Management
One of the fundamental core principles behind Terraform is its declarative approach to handling infrastructure. You don’t have to write instructions on how to create, modify, or delete infrastructure. Just describe what you want the state of the infrastructure to be, and Terraform figures out how to get there no matter where it begins. This approach eliminates many common errors caused by manual operations or scripts. - State Management
Terraform state files store the states of the managed resources. State files should be stored in a secure, shared place like Azure Blob Storage for teams. Proper state management is necessary for safe and correct operations. - Version Control
Manage infrastructure using version-controlled files stored in Git repositories. - Conflict Handling
Terraform has some strong conflict detection and handling features in addition to its effective cloud tool automation capabilities. One of these features is the Terraform plan function, which identifies any perceived or possible conflicts of infrastructure orchestration and makes it simple to resolve them before deployment. - Code Reusability
We can use Terraform Azure codes for another same services deployment in the same or different projects and Terraform’s developer documentation page provides a large selection of code templates for simple reuse.
What is the Basic Terraform Workflow in Azure?
The core Terraform workflow has three steps:
- Write – Author infrastructure as code.
- Plan – Preview changes before applying.
- Apply – Provision reproducible infrastructure.
- Create a Terraform Configuration on Azure
Define an Azure resource using terraform block. In this example, we will create an Azure resource group, an Azure virtual network, and a VM.
- Initialize Terraform
Initializing your workspace is used to initialize a working directory containing Terraform configuration files. Run the following command to initialize Terraform and download the Azure provider.terraform init
-
- Plan the Infrastructure
Terraform has a dry run mode where you can preview what Terraform will change without making any actual changes to your infrastructure. This dry run is performed by running a terraform plan. In your terminal, you can run a plan as shown below to see the changes required for Terraform to reach the desired state you defined in your code. This is equivalent to running Terraform in a “dry mode”.terraform plan
- Plan the Infrastructure
Once completed, you will see that Terraform has successfully built your resource based on what was in your plan file.
- Applying terraform Plan
Run the command below to build the resources within your plan file.terraform apply
- Now, resources are deployed. You can check those resources in the Azure console.
- Terraform Destroy
The terraform destroy command is a convenient way to destroy all remote objects managed by a particular Terraform configuration. It does not delete your configuration file(s), main.tf, etc. It destroys the resources built from your Terraform code. Run the command as shown below to run a planned destroy.terraform destroy
Terraform Best Practices for Azure
- Use Modules for Reusability
Modules are specifically authored within the Terraform framework and serve as reusable components which enable you to organize cloud services with ease. You can also store vital information regarding cloud services in a module and then make it special by customizing it using module variables.
1234module "network" {source = "Azure/network/azurerm"version = "3.0.0"} - State Management
Store the Terraform state remotely in Azure Storage to enable team collaboration.
12345678terraform {backend "azurerm" {resource_group_name = "tf-backend"storage_account_name = "tfstate"container_name = "state"key = "terraform.tfstate"}} - Security Best Practices
Avoid storing secrets in Terraform files: Keep sensitive information in Azure Key Vault.
Final Thoughts
Terraform for Azure is a powerful tool for managing cloud infrastructure. As you apply Terraform, your organizations are able to utilize scalability, efficiency, and predictability of infrastructure as code. Continue learning, experimenting, and practicing best practices as you undertake your Terraform journey so that you can harness the full potential of deploying infrastructure on Azure using Terraform.
For further details and advanced topics, the Terraform Azure Provider documentation has extensive resources and tutorials to enhance your knowledge and expertise in handling Azure resources with Terraform.
FAQ
- Q: What is Terraform used for in Azure?
A: Terraform automates the provisioning and management of Azure resources using Infrastructure as Code (IaC). - Q: How does Terraform store infrastructure state?
A: Terraform uses a state file (terraform.tfstate) to track deployed resources. It is recommended that it be stored remotely in Azure Storage for collaboration. - Q: Can Terraform be used with Azure DevOps?
A: Yes, Terraform integrates with Azure DevOps to enable CI/CD pipelines for infrastructure automation. - Q: How can I manage secrets securely in Terraform?
A: Use Azure Key Vault to store sensitive credentials instead of hardcoding them in Terraform files. - Q: What is the benefit of using Terraform over ARM templates?
A: Terraform provides multi-cloud support, built-in state management, and a modular approach, making it more flexible than Azure Resource Manager (ARM) templates. - Q: How does Terraform handle infrastructure drift in Azure?
A: Terraform detects configuration drift by comparing the current infrastructure state with the desired state defined in the code. Running terraform plan helps identify any discrepancies, and terraform apply can be used to bring the infrastructure back to the desired state.