Unlock terraform state that use Azure Backend with Bash
For various reasons, you may need to unlock your terraform state that is using the Azure Backend. It’s easier to use the Azure CLI to unlock the terraform state instead of the terraform force-unlock command.
Here’s a way to do using a bash script.
First you need to get the storage key for the azure storage account in which you store the terraform state.
AZURE_STORAGE_KEY=$(az storage account keys list \
--account-name "<your_account_name>" \
--resource-group "<your_resource_group>" \
--subscription "<your_subscription_id>" \
--query "[0].value" \
--output tsv
)
And then to unlock the terraform state, you have to break the lease on the object inside your blob container with this command below.
az storage blob lease break \
--blob-name "<state_filename>" \
--account-name "<your_storage_account_name>" \
--account-key "${AZURE_STORAGE_KEY}" \
--container-name "<blob_container_name>" \
--subscription "<your_subscription_id>" || true
The || true
part force the command to return true, otherwise if there’s no lease on the object, the command will return fail.
Now you have it, a way to unlock your terraform state file that is using the azure backend.