>

Terraform Azure 01

Connecting Terraform to Azure

  • Deploying infrastructure

Prerequisites

  • Azure Cli
  • Terraform

Verify you have az cli and terraform

➜  ~ which terraform 
/usr/bin/terraform
➜  ~ which az
/usr/bin/az

Login to Azure

az login

Set the subscription you’re working with

az account set --subscription "xxx-xxxx-xxxx"

Create Service Principal

az ad sp create-for-rbac --role="Contributor" \
--scopes="/subscriptions/xxx-xxxx-xxxx"

Use the output of the SP create to configure these:

It is recommended to set these are Environmental variables.

export ARM_CLIENT_ID="<appId>"
export ARM_CLIENT_SECRET="<password>"
export ARM_SUBSCRIPTION_ID="<subscription>"
export ARM_TENANT_ID="<tenant>"

Create main.tf - populate it with the following

## Configure the Azure provider
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0.2"
    }
  }

  required_version = ">= 1.1.0"
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "rg" {
  name     = "TerraformRG"
  location = "westus2"
}

Run the following verify each steps completes successfully

terraform init
terraform fmt
terraform validate
terraform apply

Sources and further reading

Terraform Azurerm Provider Information

Azure Service Principal Documentation

Joshua Cooper

DevOps engineer with an emphasis on cybersecurity


2024-06-19