Azure  

How to Set Up Infrastructure as Code Using Terraform for Azure?

Infrastructure as Code (IaC) is a modern DevOps practice that allows teams to provision, configure, and manage cloud infrastructure using declarative configuration files instead of manual portal-based operations. When working with Microsoft Azure, Terraform is one of the most widely adopted tools for implementing Infrastructure as Code because of its multi-cloud capability, strong state management, and modular design.

This article provides a complete, practical, and enterprise-level guide on how to set up Infrastructure as Code using Terraform for Azure, including architecture concepts, step-by-step configuration, real-world use cases, best practices, comparison with native Azure tools, and production considerations.

What Is Infrastructure as Code (IaC)?

Infrastructure as Code is the process of defining cloud resources such as virtual machines, storage accounts, networks, databases, and Kubernetes clusters using code files. Instead of clicking through the Azure Portal, you describe infrastructure in configuration files, and a tool like Terraform provisions it automatically.

In simple terms, IaC treats infrastructure like application code.

Why IaC Is Important in Cloud Environments

Manual infrastructure management causes:

  • Configuration drift

  • Human errors

  • Inconsistent environments

  • Difficult rollbacks

  • Slow provisioning

With IaC:

  • Infrastructure becomes repeatable

  • Environments are consistent (Dev, QA, Production)

  • Changes are version controlled

  • CI/CD pipelines can provision resources automatically

  • Disaster recovery becomes easier

Real-World Analogy

Think of IaC like using a blueprint to build houses. Instead of manually constructing each house differently, you use a standardized design to create identical structures every time.

Terraform acts as the construction manager that reads the blueprint and builds the house automatically.

What Is Terraform?

Terraform is an open-source Infrastructure as Code tool developed by HashiCorp. It uses a declarative configuration language called HCL (HashiCorp Configuration Language) to define infrastructure.

Terraform supports:

  • Azure

  • AWS

  • Google Cloud

  • Kubernetes

  • Many third-party services

It is cloud-agnostic and widely used in enterprise DevOps workflows.

How Terraform Works Internally

Terraform follows a three-step workflow:

  1. Write configuration files.

  2. Run terraform plan to preview changes.

  3. Run terraform apply to provision infrastructure.

Internally, Terraform:

  • Reads configuration files

  • Compares desired state with current state

  • Calculates execution plan

  • Applies required changes

  • Stores state in a state file

The state file is critical because it tracks resource metadata.

Step 1: Install Terraform

Download Terraform from the official website and verify installation:

terraform --version

Step 2: Authenticate with Azure

Login using Azure CLI:

az login

Terraform uses Azure credentials from CLI session.

Step 3: Create Terraform Configuration File

Create a folder named terraform-azure and inside create main.tf:

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example" {
  name     = "my-terraform-rg"
  location = "East US"
}

resource "azurerm_storage_account" "example" {
  name                     = "myterraformstorage123"
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

This configuration creates:

  • Resource Group

  • Storage Account

Step 4: Initialize Terraform

terraform init

This downloads required provider plugins.

Step 5: Preview Execution Plan

terraform plan

Terraform shows what will be created or modified.

Step 6: Apply Configuration

terraform apply

After confirmation, Azure resources are provisioned.

Step 7: Destroy Resources (If Needed)

terraform destroy

This removes infrastructure safely.

Real Business Scenario: Multi-Environment SaaS Platform

Consider a SaaS company with:

  • Development environment

  • Staging environment

  • Production environment

Using Terraform:

  • Each environment has separate configuration variables.

  • CI/CD pipeline provisions infrastructure automatically.

  • Infrastructure changes are reviewed via pull requests.

  • Rollbacks are controlled via version history.

This eliminates manual configuration and ensures consistency.

Using Variables for Environment Configuration

Create variables.tf:

variable "location" {
  default = "East US"
}

Reference in main.tf:

location = var.location

This makes configuration reusable.

Using Remote State (Production Best Practice)

Instead of storing state locally, use Azure Storage:

terraform {
  backend "azurerm" {
    resource_group_name  = "tfstate-rg"
    storage_account_name = "tfstatestorage123"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
  }
}

Remote state enables:

  • Team collaboration

  • State locking

  • Secure storage

Difference: Terraform vs ARM Templates vs Bicep

FeatureTerraformARM TemplatesBicep
LanguageHCLJSONDomain-specific (simplified)
Multi-Cloud SupportYesNoNo
State ManagementYesNo persistent stateNo persistent state
Learning CurveModerateComplex JSONEasier than ARM
Community ModulesLarge ecosystemLimitedGrowing
Cloud PortabilityHighAzure-onlyAzure-only
CI/CD IntegrationStrongStrongStrong
Enterprise AdoptionVery HighHighGrowing
ReadabilityHighLow (verbose JSON)High

Terraform is preferred when multi-cloud or advanced state management is required.

Advantages of Using Terraform for Azure

  • Declarative infrastructure

  • Version-controlled environments

  • Multi-cloud flexibility

  • Strong modularization support

  • Large provider ecosystem

  • Infrastructure reproducibility

Disadvantages

  • State file management complexity

  • Additional tool to maintain

  • Requires understanding of provider configuration

  • Drift detection must be managed carefully

Common Mistakes Developers Make

  • Storing state file in local system for production

  • Hardcoding secrets in configuration files

  • Not using modules for reusable components

  • Not reviewing terraform plan before apply

  • Mixing manual Azure changes with Terraform-managed resources

Best Practices for Enterprise Use

  • Store state in Azure Storage backend

  • Use separate state files per environment

  • Use modules for reusable infrastructure

  • Integrate Terraform in CI/CD pipeline

  • Use Azure Key Vault for secrets

  • Enable state locking

  • Follow naming conventions consistently

Enterprise Architecture Flow Example

Developer → Git Repository → CI/CD Pipeline → Terraform Plan → Terraform Apply → Azure Infrastructure Provisioned → Monitoring and Logging Enabled

Infrastructure changes become part of software delivery lifecycle.

When NOT to Use Terraform

  • Extremely small projects

  • One-time manual resource creation

  • Teams without DevOps maturity

However, even small teams benefit from adopting IaC early.

FAQ

Is Terraform free to use?

Yes, the open-source version is free.

Can Terraform manage existing Azure resources?

Yes, using terraform import.

Is Terraform suitable for production?

Yes, it is widely used in enterprise production systems.

Conclusion

Setting up Infrastructure as Code using Terraform for Azure enables organizations to provision and manage cloud resources in a consistent, automated, and scalable manner. By defining infrastructure declaratively, maintaining state securely, and integrating Terraform into CI/CD pipelines, teams can eliminate configuration drift, reduce manual errors, and accelerate cloud adoption. While it introduces additional tooling and state management responsibilities, Terraform’s modularity, multi-cloud support, and enterprise-grade capabilities make it a powerful solution for managing modern Azure environments efficiently and reliably.