Get Started: Configure Terraform in Azure Cloud Shell with Bash

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.

This article presents you with the options to authenticate to Azure for use with Terraform.

In this article, you learn how to:

  • Configure Cloud Shell
  • Display current Azure account
  • 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. Open Cloud Shell

  1. If you already have a Cloud Shell session open, you can skip to the next section.

  2. Browse to the Azure portal

  3. If necessary, log in to your Azure subscription and change the Azure directory.

  4. Open Cloud Shell.

    Open Cloud Shell from the top menu in the Azure portal.

  5. If you haven't previously used Cloud Shell, configure the environment and storage settings.

  6. Select the command-line environment.

    Select the CLI you want to use in Cloud Shell.

3. Install latest version of Terraform in Azure Cloud Shell

Cloud Shell automatically updates to the latest version of Terraform within a couple of weeks of its release. However, if you need the most recent version sooner, the following steps show you how to download and install the current version of Terraform.

  1. Determine the version of Terraform being used in Cloud Shell.

    terraform version
    
  2. If the Terraform version installed in Cloud Shell isn't the latest version, you see a message indicating that the version of Terraform is out of date.

  3. If you're fine working with the indicated version, skip to the next section. Otherwise, continue with the following steps.

  4. Browse to the Terraform downloads page.

  5. Scroll down to the Linux download links.

  6. Move your mouse over the 64-bit link. This is the link for the latest 64-bit Linux AMD version, which is appropriate for Cloud Shell.

  7. Copy the URL.

  8. Run curl, replacing the placeholder with the URL from the previous step.

    curl -O <terraform_download_url>
    
  9. Unzip the file.

    unzip <zip_file_downloaded_in_previous_step>
    
  10. If the directory doesn't exist, create a directory named bin.

    mkdir bin
    
  11. Move the terraform file into the bin directory.

    mv terraform bin/    
    
  12. Verify that the downloaded version of Terraform is first in the path.

    terraform version
    

4. Verify the default Azure subscription

When you log in to the Azure portal with a Microsoft account, the default Azure subscription for that account is used.

Terraform automatically authenticates using information from the default Azure subscription.

Run az account show to verify the current Microsoft account and Azure subscription.

az account show

Any changes you make via Terraform will be against the displayed Azure subscription. If that's what you want, skip the rest of this article.

5. Authenticate Terraform to Azure

Terraform and Azure authentication scenarios

Terraform only supports authenticating to Azure via the Azure CLI. Authenticating using Azure PowerShell is not 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 log 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 to log in to Azure interactively using a Microsoft account, list the account's associated Azure subscriptions (including the default), and 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 log in to Azure.

    az login
    

    Key points:

    • Upon successful login, 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 log in as a fully privileged user, Azure offers service principals.

The most common pattern is to interactively log 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, log 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 is not 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 is not 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
    

    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) and 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 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 is not advisable to store credentials in a clear-text file that can be viewed by non-trusted individuals.

Troubleshoot Terraform on Azure

Troubleshoot common problems when using Terraform on Azure

Next steps