How to set up Terraform remote state for a project in Azure

2023/09/10

Introduction

When you use Terraform locally you can potentially store sensitive information in the state. This information is not encrypted which means that passwords and such are fully retrievable by anyone with the state files.

To circumvent this you use something called remote state. Remote state is something that can be used with Terraform to make sure that state isn’t stored locally on your machine or code repository.

All major cloud providers make it possible to use their blob storage functionality for remote state. For this tutorial we will use Azure.

Setting up your Azure subscription

  1. Create a storage account to hold all Terraform states for your directory. Call it something like “tfstates{RANDOM NUMBER}”. The name must be unique across Azure, which is why there is a random number in my suggested naming.
  2. Create a container in the storage account for your application.

Setting up remote state with Terraform and testing

  1. Install the latest Azure CLI:
  2. Log into your Azure subscription using az login.
  3. Create a service principal in Azure you will use for all Terraform stuff:

    _10
    az ad sp create-for-rbac --name terraform --role Contributor

  4. Install Terraform and set it up so it is availible to use in console.
  5. Change your main.tf file and add the following code:

    _21
    terraform {
    _21
    required_providers {
    _21
    azurerm = {
    _21
    source = "hashicorp/azurerm"
    _21
    version = "2.99.0"
    _21
    }
    _21
    }
    _21
    _21
    backend "azurerm" {
    _21
    resource_group_name = "YOUR_RESOURCE_GROUP_NAME"
    _21
    storage_account_name = "STORAGE_ACCOUNT_NAME"
    _21
    container_name = "CONTAINER_NAME"
    _21
    key = "terraform.tfstate"
    _21
    }
    _21
    }
    _21
    _21
    provider "azurerm" {
    _21
    subscription_id = "SUBSCRIPTION_ID"
    _21
    tenant_id = "TENANT_ID"
    _21
    features {}
    _21
    }

    This code is enough to have your main.tf file set up to connect to your Azure directory and state. As long as you are logged in with az login it will figure out the storage connection key by itself.
  6. Test if things work with a terraform plan with the following code added to your main.tf file:

    _10
    resource "azurerm_resource_group" "example" {
    _10
    name = "example-resources"
    _10
    location = "West Europe"
    _10
    }

Extras

You can find your tenant ID on this page.

You can find your subscription ID on this page.