Authenticate Terraform to Azure

Terraform enables the definition, preview, and deployment of cloud infrastructure. Using Terraform, you create configuration files using HCL syntax. The HCL syntax allows you to specify the cloud provider - such as Azure - and the elements that make up your cloud infrastructure. After you create your configuration files, you create an execution plan that allows you to preview your infrastructure changes before they're deployed. Once you verify the changes, you apply the execution plan to deploy the infrastructure.

To use Terraform commands against your Azure subscription, you must first authenticate Terraform to that subscription. This article covers some common scenarios for authenticating to Azure.

In this article, you learn how to:

  • Understand common Terraform and Azure authentication scenarios
  • Authenticate via a Microsoft account from Cloud Shell (using Bash or PowerShell)
  • Authenticate via a Microsoft account from Windows (using Bash or PowerShell)
  • Create a service principal using the Azure CLI
  • Create a service principal using Azure PowerShell
  • Specify service principal credentials in environment variables
  • Specify service principal credentials in a Terraform provider block

1. Configure your environment

  • Azure subscription: If you don't have an Azure subscription, create a free account before you begin.

2. Authenticate Terraform to Azure

Terraform and Azure authentication scenarios

Terraform only supports authenticating to Azure via the Azure CLI. Authenticating using Azure PowerShell isn't supported. Therefore, while you can use the Azure PowerShell module when doing your Terraform work, you first need to authenticate to Azure using the Azure CLI.

This article explains how to authenticate Terraform to Azure for the following scenarios. For more information about options to authenticate Terraform to Azure, see Authenticating using the Azure CLI.

Authenticate to Azure via a Microsoft account

A Microsoft account is a username (associated with an email and its credentials) that is used to sign in to Microsoft services - such as Azure. A Microsoft account can be associated with one or more Azure subscriptions, with one of those subscriptions being the default.

The following steps show you how:

  • Sign in to Azure interactively using a Microsoft account
  • List the account's associated Azure subscriptions (including the default)
  • Set the current subscription.
  1. Open a command line that has access to the Azure CLI.

  2. Run az login without any parameters and follow the instructions to sign in to Azure.

    az login
    

    Key points:

    • Upon successful sign in, az login displays a list of the Azure subscriptions associated with the logged-in Microsoft account, including the default subscription.
  3. To confirm the current Azure subscription, run az account show.

    az account show
    
  4. To view all the Azure subscription names and IDs for a specific Microsoft account, run az account list.

    az account list --query "[?user.name=='<microsoft_account_email>'].{Name:name, ID:id, Default:isDefault}" --output Table
    

    Key points:

    • Replace the <microsoft_account_email> placeholder with the Microsoft account email address whose Azure subscriptions you want to list.
    • With a Live account - such as a Hotmail or Outlook - you might need to specify the fully qualified email address. For example, if your email address is admin@hotmail.com, you might need to replace the placeholder with live.com#admin@hotmail.com.
  5. To use a specific Azure subscription, run az account set.

    az account set --subscription "<subscription_id_or_subscription_name>"
    

    Key points:

    • Replace the <subscription_id_or_subscription_name> placeholder with the ID or name of the subscription you want to use.
    • Calling az account set doesn't display the results of switching to the specified Azure subscription. However, you can use az account show to confirm that the current Azure subscription has changed.
    • If you run the az account list command from the previous step, you see that the default Azure subscription has changed to the subscription you specified with az account set.

Create a service principal

Automated tools that deploy or use Azure services - such as Terraform - should always have restricted permissions. Instead of having applications sign in as a fully privileged user, Azure offers service principals.

The most common pattern is to interactively sign in to Azure, create a service principal, test the service principal, and then use that service principal for future authentication (either interactively or from your scripts).

  1. To create a service principal, sign in to Azure. After authenticating to Azure via a Microsoft account, return here.

  2. If you're creating a service principal from Git Bash, set the MSYS_NO_PATHCONV environment variable. (This step isn't necessary if you're using Cloud Shell.)

    export MSYS_NO_PATHCONV=1    
    

    Key points:

    • You can set the MSYS_NO_PATHCONV environment variable globally (for all terminal sessions) or locally (for just the current session). As creating a service principal isn't something you do often, the sample sets the value for the current session. To set this environment variable globally, add the setting to the ~/.bashrc file.
  3. To create a service principal, run az ad sp create-for-rbac.

    az ad sp create-for-rbac --name <service_principal_name> --role Contributor --scopes /subscriptions/<subscription_id>
    

    Key points:

    • You can replace the <service-principal-name> with a custom name for your environment or omit the parameter entirely. If you omit the parameter, the service principal name is generated based on the current date and time.
    • Upon successful completion, az ad sp create-for-rbac displays several values. The appId, password, and tenant values are used in the next step.
    • The password can't be retrieved if lost. As such, you should store your password in a safe place. If you forget your password, you can reset the service principal credentials.
    • For this article, a service principal with a Contributor role is being used. For more information about Role-Based Access Control (RBAC) roles, see RBAC: Built-in roles.
    • The output from creating the service principal includes sensitive credentials. Be sure that you don't include these credentials in your code or check the credentials into your source control.
    • For more information about options when creating a service principal with the Azure CLI, see the article Create an Azure service principal with the Azure CLI.

Specify service principal credentials in environment variables

Once you create a service principal, you can specify its credentials to Terraform via environment variables.

  1. Edit the ~/.bashrc file by adding the following environment variables.

    export ARM_SUBSCRIPTION_ID="<azure_subscription_id>"
    export ARM_TENANT_ID="<azure_subscription_tenant_id>"
    export ARM_CLIENT_ID="<service_principal_appid>"
    export ARM_CLIENT_SECRET="<service_principal_password>"
    
  2. To execute the ~/.bashrc script, run source ~/.bashrc (or its abbreviated equivalent . ~/.bashrc). You can also exit and reopen Cloud Shell for the script to run automatically.

    . ~/.bashrc
    
  3. Once the environment variables have been set, you can verify their values as follows:

    printenv | grep ^ARM*
    

Key points:

  • As with any environment variable, to access an Azure subscription value from within a Terraform script, use the following syntax: ${env.<environment_variable>}. For example, to access the ARM_SUBSCRIPTION_ID value, specify ${env.ARM_SUBSCRIPTION_ID}.
  • Creating and applying Terraform execution plans makes changes on the Azure subscription associated with the service principal. This fact can sometimes be confusing if you're logged into one Azure subscription and the environment variables point to a second Azure subscription. Let's look at the following example to explain. Let's say you have two Azure subscriptions: SubA and SubB. If the current Azure subscription is SubA (determined via az account show) while the environment variables point to SubB, any changes made by Terraform are on SubB. Therefore, you would need to log in to your SubB subscription to run Azure CLI commands or Azure PowerShell commands to view your changes.

Specify service principal credentials in a Terraform provider block

The Azure provider block defines syntax that allows you to specify your Azure subscription's authentication information.

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "~>2.0"
    }
  }
}

provider "azurerm" {
  features {}

  subscription_id   = "<azure_subscription_id>"
  tenant_id         = "<azure_subscription_tenant_id>"
  client_id         = "<service_principal_appid>"
  client_secret     = "<service_principal_password>"
}

# Your code goes here

Caution

The ability to specify your Azure subscription credentials in a Terraform configuration file can be convenient - especially when testing. However, it isn't advisable to store credentials in a clear-text file that can be viewed by non-trusted individuals.

3. Verify the results

Verify that you've authenticated to the Azure subscription by displaying the current subscription.

To confirm the current Azure subscription via the Azure CLI, run az account show.

az account show

Next steps