Using Azure Resource Manager with Terraform

05 Dec 2016 in TIL

The Terraform documentation contains a list of steps that you can follow to create access credentials to use Terraform with Azure. No matter how many times I tried I couldn't get them to work.

I finally managed to piece together all of the required information using the azure CLI tool. You'll need jq installed to copy/paste these commands. Here are the steps I followed:

(If you prefer, there's a script that performs all of these steps on GitHub)

Install the azure CLI tool

bash
sudo npm install -g azure-cli

Login to the CLI tool

bash
azure login

Fetch your subscription ID and tenant ID

bash
azure account show --json | jq ".[] | {subscription_id: .id, tenant_id: .tenantId}"

Create an Active Directory application The -i option is the URL for your application. You can set both this and the home page URL to anything as Terraform is a desktop application. The password that you specify here will be your client_secret, so make it nice and long. This will return a value, which will be your client_id

bash
azure ad app create --json -n michael-terraform -i <url> --home-page <homepage> -p <password> | jq .appId

Create a service principal As well as creating an active directory application, we need to create a service principal to use under that application

bash
azure ad sp create -a <client_id>

Add the correct permissions Finally, we need to give your new application the permissions it needs to manage resources. For this post I've given the application access to everything, but you can find a list of all available roles here. The "Role name" is what you need to pass to the -o flag.

To add permissions to our application, we need to provide both our application's URL and our subscription_id

bash
azure role assignment create --spn <url> -o "Owner" -c /subscriptions/<subscription_id>

At this point, you should be able to create a terraform definition and try and execute it. Here's my test definition:

hcl
provider "azurerm" {
subscription_id = "<subscription_id>"
client_id = "<client_id>"
client_secret = "<client_secret>"
tenant_id = "<tenant_id>"
}
resource "azurerm_resource_group" "tf-test-michael" {
name = "production"
location = "West US"
}

Save that to test.tf then run terraform plan to make sure that all of your credentials work