Keep Terraform state in Azure Storage
In this task you'll keep Terraform state in Azure Storage with Entra ID sign-in.
The azurerm backend stores state as a blob, with locking (a lease) so two applies can't run at once. Turn on blob versioning to recover old copies.
With use_azuread_auth = true Terraform signs in as you or the pipeline's identity, which needs Storage Blob Data Contributor on the account: no account keys.
Example. Fernhill Cloud keeps every stack's state in one locked-down storage account, one container per environment, versioned, with shared keys turned off.
Before you start
You need: A storage account and a data role on it. Time: 20 minutes.
Where to look
- Storage account
- Containers
- tfstate
- Versions
Steps
- Create a private container tfstate and turn on versioning.
- Give yourself Storage Blob Data Contributor on the account and wait a minute.
- Add a backend "azurerm" block with the account, container, key and use_azuread_auth = true, then
terraform init. - To move existing local state,
terraform init -migrate-state.
Commands
az storage container-rm create --storage-account <sa> -g <group> -n tfstate --public-access off
az storage account blob-service-properties update --account-name <sa> -g <group> --enable-versioning true
az role assignment create --role "Storage Blob Data Contributor" --assignee $(az ad signed-in-user show --query id -o tsv) --scope $(az storage account show -n <sa> --query id -o tsv)
export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
terraform init
Watch out for
- Cost
- Pennies a month.
- Security
- Lock the account down: no public access, no shared keys, RBAC only.
- Common mistakes
- Waiting too little after the role assignment (403 errors), and different stacks sharing one key.
Clean up
Delete the storage account's resource group when no stack uses it.
Words to know
- Backend
- Where Terraform keeps state.
- State lock
- A blob lease that stops two runs changing state at once.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On