Skip to main content

Command Palette

Search for a command to run...

3.2 Automating Azure Infrastructure Deployment Using Terraform

Updated
5 min readView as Markdown
3.2 Automating Azure Infrastructure Deployment Using Terraform

Level Up Your Azure Kubernetes Game: Automating Infrastructure with Terraform

Alright, Kubernetes enthusiasts! Ready to ditch the tedious clicking in the Azure portal and embrace the power of automation? In this post, we'll explore how to use Terraform to deploy your Azure infrastructure for Kubernetes. Think of it as having a blueprint for your entire Azure setup – replicable, version-controlled, and ready to deploy with a single command.

Why Automate Azure Infrastructure with Terraform?

Imagine you're building a Lego castle. You could painstakingly place each brick by hand, referencing instructions repeatedly. Or, you could use a pre-designed template that lays out exactly where each piece goes, allowing you to build the castle faster and with fewer mistakes.

Terraform is like that pre-designed template for your Azure infrastructure. Instead of clicking around the Azure portal, you define your resources (like virtual machines, networks, load balancers) in a declarative configuration file. Terraform then reads this file and creates (or updates) the infrastructure in Azure.

Benefits of Terraform:

  • Infrastructure as Code (IaC): Your infrastructure lives as code, enabling version control, collaboration, and repeatability.

  • Consistency: Ensure your environments (development, staging, production) are identical.

  • Efficiency: Deploy complex infrastructure with a single command, saving time and effort.

  • Idempotency: Terraform only makes changes necessary to achieve the desired state defined in your configuration. Run it multiple times, and it will only act if the configuration differs from the current infrastructure.

A Simple Azure Kubernetes Example

Let's say you want to create a basic Azure Kubernetes Service (AKS) cluster with a virtual network. Here's a simplified snippet of Terraform code that would achieve this:

# Configure the Azure Provider
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0"
    }
  }
  required_version = ">= 0.14.9"
}

provider "azurerm" {
  features {}
}

# Create a resource group
resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = "eastus"
}

# Create a virtual network
resource "azurerm_virtual_network" "example" {
  name                = "example-network"
  address_space       = ["10.0.0.0/16"]
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
}

# Create a subnet
resource "azurerm_subnet" "example" {
  name                 = "example-subnet"
  resource_group_name  = azurerm_resource_group.example.name
  virtual_network_name = azurerm_virtual_network.example.name
  address_prefixes     = ["10.0.1.0/24"]
}

# Create an AKS cluster
resource "azurerm_kubernetes_cluster" "example" {
  name                = "example-aks"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  dns_prefix          = "exampleaks"

  default_node_pool {
    name           = "default"
    node_count     = 1
    vm_size        = "Standard_D2_v2"
    vnet_subnet_id = azurerm_subnet.example.id
  }

  identity {
    type = "SystemAssigned"
  }
}

Explanation:

  • terraform block: Specifies the required providers (Azure) and Terraform version.

  • provider "azurerm" block: Configures the Azure provider.

  • resource "azurerm_resource_group" block: Creates an Azure resource group to hold all our resources.

  • resource "azurerm_virtual_network" block: Creates a virtual network.

  • resource "azurerm_subnet" block: Creates a subnet within the virtual network.

  • resource "azurerm_kubernetes_cluster" block: Creates the AKS cluster itself, specifying its location, name, DNS prefix, and node pool configuration. Crucially, it uses the subnet we just created.

To deploy this:

  1. Save the code as a .tf file (e.g., main.tf).

  2. Initialize Terraform: terraform init

  3. Plan the changes: terraform plan (This shows you what Terraform will do).

  4. Apply the changes: terraform apply (This creates the resources in Azure).

Real-World Scenario: Building a Scalable E-commerce Platform

Imagine you're building an e-commerce platform. You'll need:

  • An AKS cluster to run your application's containers.

  • A database (e.g., Azure Database for PostgreSQL) to store product information and user data.

  • A load balancer to distribute traffic to your application.

  • Azure Container Registry (ACR) to store your container images.

Using Terraform, you can define all these resources in code, ensuring that your development, staging, and production environments are identical. You can easily scale your infrastructure by simply changing the node count in your AKS cluster configuration and re-applying the Terraform configuration.

Challenge: Secret Management

One common challenge is managing secrets, such as database passwords and API keys. Hardcoding them in your Terraform files is a huge security risk.

Solution: Azure Key Vault and Terraform

The best practice is to store secrets securely in Azure Key Vault. Terraform can then access these secrets during deployment. Here's a simplified example:

  1. Create a Key Vault in Azure: (You can do this through the Azure portal or using Terraform as well).

  2. Store your secrets in Key Vault.

  3. Grant your Terraform service principal access to read secrets from the Key Vault.

  4. Use the data source in Terraform to retrieve secrets from Key Vault:

data "azurerm_key_vault_secret" "db_password" {
  name         = "db-password"
  key_vault_id = "/subscriptions/YOUR_SUBSCRIPTION_ID/resourceGroups/YOUR_RESOURCE_GROUP/providers/Microsoft.KeyVault/vaults/YOUR_KEYVAULT_NAME"
}

resource "azurerm_postgresql_server" "example" {
  name                = "example-db"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  administrator_login         = "dbadmin"
  administrator_login_password = data.azurerm_key_vault_secret.db_password.value

  sku_name   = "B_Gen5_1"
  storage_mb = 5120
  version    = "12"

  ssl_enforcement_enabled = true
}

In this example, we're retrieving the database password from Azure Key Vault and using it to configure the PostgreSQL server. This keeps your secrets safe and allows you to rotate them without modifying your Terraform code directly.

Visualizing the Architecture

Here's a simplified diagram of what we're building with Terraform:

+-----------------------+      +----------------------+      +---------------------+
|     Azure Portal      |  --> |     Terraform CLI    |  --> |     Azure Cloud     |
+-----------------------+      +----------------------+      +---------------------+
       (Optional)           (terraform init, plan, apply)      (Resource Group, AKS, VNet, KeyVault...)

Key Takeaways

Terraform empowers you to automate your Azure infrastructure deployments for Kubernetes, bringing consistency, efficiency, and security to your workflow. Start small, experiment with simple examples, and gradually incorporate more complex scenarios. Remember to use Azure Key Vault for managing secrets! Happy automating!

Mastering Terraform: From Infrastructure as Code to Automation

Part 12 of 36

Learn Terraform from scratch! This series covers everything from basic Infrastructure as Code concepts to advanced automation, modules, state management, and best practices for building, deploying, and managing cloud infrastructure efficiently.

Up next

3.3 Creating a Google Cloud Environment with Terraform

Kubernetes in the Cloud: Building Your Google Cloud Playground with Terraform So, you're diving into the world of Kubernetes? Awesome! But before you can deploy containers and orchestrate your applications, you need a place to do it. That's where clo...

More from this blog

TechZen

136 posts