In the previous post of the Microsoft Azure with Terraform series we have described how to setup Terraform Microsoft Azure provider. In this post, we explore how to setup Terraform Azure backend for managing remote states.
To be able to function Terraform needs to keep track of its Infrastructure and configuration status. When the “terraform apply” is issued the terraform.tfstate is created locally in the terraform folder and Terraform state information are saved in it.
If we are using Terraform as single user this approach should work reasonably. If instead we are working in a team and we need to share the Terraform state then this approach is not suggested. Luckily Terraform provides a remote state mechanism for saving its state remotely
To be able to handle different state both locally and remotely, Terraform provides the backends. Among the different backends types there is the Microsoft Azure backend. We provide now the steps to be able to setup the Terraform Azure backend for managing the Terraform remote state.
For setting up the Terraform backend some information shall be treated according to the Terraform documentation
The above-mentioned information are required for setting up the Terraform Azure backend.
The Terraform Azure backend is saved in the Microsoft Azure Storage. Therefore, we need to create an Azure storage blob for the Terraform state file. These are the steps for creating the Azure storage blob:
1. Click on the “Storage accounts” in the Azure panel
2. Click “Add” and create the new storage account
3. Create the Blob container
Now we have all the information to be able to create the Terraform Azure backend. We save its configuration in the backend.tf file
The key = the name of the Terraform state file that is created when “terraform apply” is performed.
The access_key = key from the storage account
Now we have the terraform backend file ready
Before performing any Terraform command, is good practice to run the “terraform init” command for initializing the Terraform backend before use
Now we run the “terraform plan” and “terraform apply” for creating the Microsoft Azure resources
and we can see that the terraform state is now saved in the Azure backend
Terraform keeps track of its state in a file that can be managed locally or remotely. When working in a team Hashicorp Terraform team suggest using Terraform backend for Terraform remote state handling. One of the Terraform backend type is Azure backend and this post showed how to set it up.