Peter Walker
Peter's SRE Notes

Peter's SRE Notes

Terraform State File in Azure

Peter Walker's photo
Peter Walker
·Jan 3, 2022·

1 min read

Terraform State File in Azure

This is sort of a chicken and egg situation where the egg has to come before the chicken. The state file is important and it maintains your current state of all your Azure resources created via Terraform. There are many ways to get started, but this is my approach.

Login to Azure, create a resource group, storage account and storage container via the Azure CLI (API):

az login
az group create --name my-resource-group --location westus
az storage account create --resource-group my-resource-group --name terraformstorageacct1
az storage container create --name tfstate-westus --acount-name terraformstorageacct1

Set your backend in your or whatever you named your file (Terraform doesn't care what a .tf file is named). The key below is what your state file will be stored as in your container:

terraform {
  backend "azurerm" {
    resource_group_name  = "my-resource-group"
    storage_account_name = "terraformstorageacct1"
    container_name       = "tfstate-westus"
    key                  = "myfirst.tfstate"

After creating the necessary Azure resources and declaring the backend, you can now initialize your backend and migrate a state file. If you have a state file in your local directory, you will be prompted to migrate it to your new Azure Storage container:

terraform init

Share this