Skip to main content

Command Palette

Search for a command to run...

How to Save Terraform State in an Azure Storage Account

Updated
2 min read
How to Save Terraform State in an Azure Storage Account
R

I'm technologist in love with almost all things tech from my daily job in the Cloud to my Master's in Cybersecurity and the journey all along.

I personally prefer not to do this but some teams do and it's a good way to collaborate and a cheap(est) alternative to using the Terraform Cloud with the intention of allowing a team to build cloud services.

I've only used one storage account per resource group assigned to a Terraform project, I haven't tested storing more than one Terraform project state on the same storage account but different container. I'd presume it's doable.

Terraform Backend

It starts with the terraform block:

terraform {

}

This blocks allows the configuration of Terraform's backend among many others not covered here:

backend. Specifically refers to the Terraform State. The state is the persistent data keeping track the resources Terraform manages. Note: The default backend is always local.

Some of the Cloud supported backends:

  • AWS S3

  • Azure Storage Account (blob storage)

  • Google Cloud Storage

I didn't change anything on the main.tf where the logic for the password generator is. I added the backend.tf file:

terraform {
  backend "azurerm" {
    resource_group_name  = "RGTFSTAUPWD"       # Resource group of the storage account
    storage_account_name = "saauetfpwd"      # Name of the storage account
    container_name       = "terraform-state"       # Name of the container
    key                  = "terraform.tfstate"     # Name of the state file
  }
}

As a good practice enable versioning on the the blob as this will allow to roll back in case required or review the previews states (passwords):

Running the password generator:

On the command line:

terraform apply -auto-approve -var length=10; terraform output espasswordWill generate a 10 character password: $CZ0QFn3bc
terraform apply -auto-approve -var length=255; terraform output espasswordWill generate a 255 character password (why not): 7MM2Z1m#jlfzw{Oj1lq1VQJjE&XkXD?F6wUH-O)&YXyZTHTq<=l{ZkRT?-W}Zpea9Sq({b#9_U=k62{aUfeBfdXR-V&r9N)g+3-dvoLG&B3*AE+U(V8Xt1Jj)cw-MS=!KMB_c?#]ME!(zGZt8xo0j{A<usUYrHHvNZ0vSJOW!>k=csrtseWoXng>IV%_MrAZBv[#}ag-LG:tBpB)6pZ[%BV_5+(zofSmCr>MutoV4XEKB[2OL[b(rXm9bH]gC

Looking at the versions on the Azure portal

The 10 character password:

The 255 password:

Pre-requisites:

  • As a very minimum you'd require an Azure account (obviously)

  • Being logged into the Azure subscription when running this code

More from this blog

U

Understand. Build. Conquer the Cloud

70 posts

No time for a novel? Here are my my Cloud Architect field notes: Distilling my complex cloud adventures into digestible TL;DRs.