One of the amazing features of Terraform is, it tracks the infrastructure that you provision. It does this through the means of state. By default, Terraform stores state information locally in a file named terraform.tfstate
. This does not work well in a team environment where if any developer wants to make a change he needs to make sure nobody else is updating terraform in the same time. You need to use remote storage to store state file.
With remote state, Terraform writes the state data to a remote data store, which can then be shared between all members of a team. Terraform supports storing state in many ways including the below:
- Terraform Cloud
- HashiCorp Consul
- Amazon S3
- Azure Blob Storage
- Google Cloud Storage
- Alibaba Cloud OSS
- Artifactory or Nexus
We will learn how to store state file in Azure Blob storage. We will be creating Azure storage account and container.
Watch the steps in YouTube channel:
Pre-requisites:
- Install Azure CLI
- Make sure Terraform is setup on your local machine
- Azure subscription
- Authenticate Terraform with Azure using Azure CLI.
Steps:
Logging into the Azure Cloud
Login into the Azure Cloud using Azure CLI using:
az login
Create main.tf
Step # 1 - Configure Azure storage account
Before you use Azure Storage as a backend, you must create a storage account. We will create using shell script:
RESOURCE_GROUP_NAME=tfstate
STORAGE_ACCOUNT_NAME=tfstate$RANDOM
CONTAINER_NAME=tfstate
# Create resource group
az group create --name $RESOURCE_GROUP_NAME --location eastus
# Create storage account
az storage account create --resource-group $RESOURCE_GROUP_NAME --name $STORAGE_ACCOUNT_NAME --sku Standard_LRS --encryption-services blob
# Create blob container
az storage container create --name $CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME
This should have created resource group, storage account and container in Azure portal.
Step # 2 - Configure terraform backend state
To configure the backend state, you need the following Azure storage information which we created above:
- resource_group_name: name of the resource group under which all resources will be created.
- storage_account_name: The name of the Azure Storage account.
- container_name: The name of the blob container.
- key: The name of the state store file to be created.
terraform init --reconfigure
This should have created backend file called terraform.tfstate in a container inside azure storage.
This is how you can store terraform state information remotely in Azure storage.
No comments:
Post a Comment