Create an Azure SPN for Terraform

An Azure Service Principal (SPN) is a security identity used by applications and services to access Azure resources.

You need to create a service principal name (SPN) account in Azure AD and assign contributor rights to the area in Azure where it will manage resources. This could be the management group, subscription, or resource group. An SPN, also known as an Azure AD app registration, is the account Terraform will use when interacting with Azure. Terraform should not use your standard login account.

When you create the SPN, the generated authentication tokens are output to the CLI. These tokens produced in the CLI are appid, password and tenant. You also need the subscription_id, which must be retrieved from Azure directly.

Create the SPN

Open a terminal and run the following command, when prompted in the browser session logon to Azure.

az login

Now select your working subscription.

az account set --subscription "<SUBSCRIPTION_ID>"

Create the SPN (app registration) in Azure AD by creating the new SPN with a <NAME> that describes the landing zone, for example, terraform-spn-<SUBSCRIPTION-NAME>.

Update the <SUBSCRIPTION_ID> with the subscription ID you specified in the previous step.

When the command completes, ensure you preserve the output data used to create environment variables Terraform requires.

az ad sp create-for-rbac --name="<NAME>" --role="contributor" --scopes="/subscriptions/<SUBSCRIPTION_ID>"

This is an example of what data will be output to the CLI

  "appId": "xxxxxx-xxx-xxxx-xxxx-xxxxxxxxxx",
  "displayName": "<NAME>",
  "password": "xxxxxx~xxxxxx~xxxxx",
  "tenant": "xxxxx-xxxx-xxxxx-xxxx-xxxxx"
Last modified July 21, 2024: update (e2ae86c)