Terraform 25: Remote state with the azurerm backend
easy⏱ 5 mincourseterraform
backend.tf points at a storage container
The backend "azurerm" block names four things: the resource group and storage account that hold the state, the container inside it, and the key (the blob's file name). The state blob is created on terraform init. Give each service/environment a unique key so their states never collide.
# backend.tf (environment: dev)
terraform {
backend "azurerm" {
resource_group_name = "myorg-tfstate-dev-rg"
storage_account_name = "myorgtfstatedev"
container_name = "tfstate"
key = "dev/orders.tfstate"
}
}
Backend config cannot use variables
Terraform initializes the backend before it evaluates variables, so you cannot write key = var.env. Two standard patterns: keep a tiny per-environment backend.tf (as above), or leave the block partial and supply the differing values at init time with -backend-config. Both keep secrets and env names out of a single shared file.
# Partial backend — values supplied at init time
terraform {
backend "azurerm" {
container_name = "tfstate"
}
}
# terraform init \
# -backend-config="resource_group_name=myorg-tfstate-dev-rg" \
# -backend-config="storage_account_name=myorgtfstatedev" \
# -backend-config="key=dev/orders.tfstate"
The backend needs no access key in the file
Don't hard-code a storage access_key. The azurerm backend authenticates with your Azure CLI login, a managed identity, or an OIDC federated token in CI — the same credential chain the provider uses. That keeps the state's own secret out of the repo.
Build the state key
Implement stateKey(env, service) to return "{env}/{service}.tfstate". For example stateKey("dev", "orders") must return "dev/orders.tfstate". The starter logs that call.