Terraform - Getting Azure Connection from Service Principal
  • 03 Jan 2020
  • 1 Minute to read
  • Contributors
  • Comment
  • Dark
    Light
  • PDF

Terraform - Getting Azure Connection from Service Principal

  • Comment
  • Dark
    Light
  • PDF

Article Summary

In a previous article (Click Here) I talked about how you need to set the following variables in your pipeline so that Terraform can access Azure:

  • ARM_CLIENT_ID = This is the application id from the service principal in Azure AD
  • ARM_CLIENT_SECRET = This is the secret for the service principal in Azure AD
  • ARM_SUBSCRIPTION_ID = The guid for the subscription id
  • ARM_TENANT_ID = This is the tenant id for your Azure AD instance

I previously talked about how you could set them as pipeline variables as a way to set the values. It would also be possible to import the variables from KeyVault but there is also another cool way you can do this can use the Service Principal you have already setup for connecting to Azure anyway. The service principal already contains the values for:

  • Client Id
  • Client Secret
  • Subscription Id

The idea is if I can copy these to the right environment variables so that Terraform will automatically pick them up then it means I dont need to keep these in another place from where they are already set anyway. To achieve this I can add the Azure CLI task to my DevOps pipeline. I will then need to set the advanced setting which will give my script access to the service principal details. See below pic.

image.png

In my powershell script I can use the below snippet to write the values from one variable to the correctly named values which can be used by Terraform to connect to Azure.

#This will write variables from the Service Principal to the variables needed by Terraform

Write-Host "##vso[task.setvariable variable=ARM_CLIENT_ID]$($env:servicePrincipalId)"

Write-Host "##vso[task.setvariable variable=ARM_CLIENT_SECRET]$($env:servicePrincipalKey)"

Write-Host "##vso[task.setvariable variable=ARM_TENANT_ID]$($env:tenantId)"

The full details for the task are in the exported yaml below. You need to remember to use the Preview v2.0 version of the task.

steps:
- task: AzureCLI@2
  displayName: 'Azure CLI - Promote SP for Terraform'
  inputs:
    azureSubscription: '[Subscription goes here]'
    scriptType: ps
    scriptLocation: inlineScript
    inlineScript: |
     #This will write variables from the Service Principal to the variables needed by Terraform
     
     Write-Host "##vso[task.setvariable variable=ARM_CLIENT_ID]$($env:servicePrincipalId)"
     
     Write-Host "##vso[task.setvariable variable=ARM_CLIENT_SECRET]$($env:servicePrincipalKey)"
     
     Write-Host "##vso[task.setvariable variable=ARM_TENANT_ID]$($env:tenantId)"
     
    addSpnToEnvironment: true
    workingDirectory: '$(Build.ArtifactStagingDirectory)'

Was this article helpful?