Back to Tech Corner
DevOps

(Sept 23) DevOps - Terraform set-up for Azure

az ad sp create-for-rbac --role="Contributor" --scopes="<subscription id>"
  • Take note of client_id and client_secret
  • Set environment variables for Terraform:

Linux / MacOS:

export TF_VAR_client_id=<client_id retrieved above>
export TF_VAR_client_secret=<client_secret retrieved above>
export TF_VAR_tenant_id=<your Azure tenant ID>
export TF_VAR_subscription_id=<your Azure subscription ID>

Windows:

set TF_VAR_client_id=<client_id retrieved above>
set TF_VAR_client_secret=<client_secret retrieved above>
set TF_VAR_tenant_id=<your Azure tenant ID>
set TF_VAR_subscription_id=<your Azure subscription ID>

For persistency, these variables can be added to your .bashrc profile on Linux / MacOS, or to the user variables via 'Control Panel > System' in Windows

  • (Optional) Create a storage account to store the remote backend for your Terraform state:
# 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>
  • Set your Terraform remote backend, either by adding the following block to your main Terraform code:
terraform {
  backend "azurerm" {
    resource_group_name = "<resource group name"
    storage_account_name = "<storage account name>"
    container_name = "<container name"
    key = "<env name>.tfstate"
  }
}
  • Or by adding a separate backend file containing just the respective keys, without the backend stanza:
resource_group_name = "<resource group name"
storage_account_name = "<storage account name>"
container_name = "<container name"
key = "<env name>.tfstate"
  • Move to the directory where your Terraform code is stored and run the following command to initialize the remote backend:
terraform init -backend-config <name of backend file, if created>

(optionally, you might have to add the -reconfigure flag if a previous backend was already initialized)

  • If applicable, customize your parameters by adding them to a tfvars file, which can take the name of your environment, e.g. staging.tfvars
  • Run a Terraform plan / apply to plan and deploy the code, inputting 'yes' or 'no' when prompted:
terraform plan -var-file <env name>.tfvars
terraform apply -var-file <env name>.tfvars