Monday 31 August 2020

Authorizing Terraform to Apply Changes to Azure Using SPN

We have discussed setting up a Windows 10 environment to develop terraform scripts in previous post. Let’s understand how to authenticate terraform to deploy infrastructure on Azure platform using a service principle with this post.

As the first step we need to have an SPN created in Azure. If you have more than one Azure subscription, make sure to set the required subscription in cloud shell using below CLI command.

Az account set --subscription azure subscriptionid

Service Principle (SPN) can be created in Azure allowing subscription level contribution permissions by executing below command in Azure cloud shell.

az ad sp create-for-rbac -n "infradeployapp" --role contributor --scopes /subscriptions/azuresubscriptionid

An app registration in Azure active directory will be created with contributor access to the subscription specified in the above command. The output of the SPN create will provide app id, password and the tenant information which you have to copy to a secure location, as the password will not be viewable again.

In terraform file you can add below code segment to allow authentication of terraform and authorize it to add resources to Azure subscription via the created SPN.

provider "azurerm" {

# The "feature" block is required for AzureRM provider 2.x.

# If you're using version 1.x, the "features" block isn't allowed.

version = "~>2.0"

subscription_id = var.AzureSubscriptionId

client_id = var.AzureSPNAppId

client_secret = var.AzureSPNPwd

tenant_id = var.AzureTenantId

features {}


The variables for the above setting can be defined in the

These variables can be supplied with command line so that the terraform is authorized to apply or execute plan on the given Azure subscription.

To supply each variable you can use syntax as below.


No comments:

Popular Posts