I have setup a whole bunch of files for deploying a simple VM, but trying to use the ADO Service Connection setup in the projec, avoiding to hardcode secrets, however after multiple tries still failing
Error: Error building ARM Config: obtain subscription() from Azure CLI: parsing json result from the Azure CLI: waiting for the Azure CLI: exit status 1: ERROR: Please run ‘az login’ to setup account
I was hoping to pass values from the ADO Service Connection into variables extracted from the pipe yaml file to the main.tf terraform file for authentication
main.tf extract
provider "azurerm" {
features {}
client_id = ARM_CLIENT_ID
client_secret = ARM_CLIENT_SECRET
tenant_id = ARM_TENANT_ID
subscription_id = ARM_CLIENT_SUBSCRIPTION_ID
}
terraform-pipelines.yml extract
trigger:
- main
pool:
vmImage: 'ubuntu-latest'
variables:
KeyVault: "test-kv"
StorageAccount: "testtfstatedemostg"
ContainerName: "tfstate"
ResourceGroup: "test-rg"
AzureRegion: "uksouth"
vmCount: 1
vmNames: "vm01"
os_publisher: "Canonical"
os_offer: "UbuntuServer"
os_sku: "18.04-LTS"
os_version: "latest"
jobs:
- job: TerraformDeployment
displayName: 'Terraform Deployment'
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: '3.x'
addToPath: true
azureSubscription: "<AzureDevops_Service_Connection_Name>"
scriptType: bash
addSpnToEnvironment: true # this will add the required credentials to env vars
useGlobalConfig: true
scriptLocation: inlineScript
inlineScript: |
echo "##vso[task.setvariable variable=ARM_TENANT_ID;]$tenantId"
echo "##vso[task.setvariable variable=ARM_CLIENT_ID;]$servicePrincipalId"
echo "##vso[task.setvariable variable=ARM_CLIENT_SECRET;]$servicePrincipalKey"
echo "##vso[task.setvariable variable=ARM_CLIENT_SUBSCRIPTION_ID;]$subscriptionId"
- script: |
#Install Terraform
curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt-get update && sudo apt-get install terraform
#Initialize Terraform
cd $(Build.SourcesDirectory)
terraform init
2
Answers
You don’t need to set the authentication directly in your provider configuration:
After fetching the credentials from the service connection, you can set the corresponding environment variables used to authenticated to the provider at the task level, for all tasks that run terraform commands such as
init
,plan
andapply
– example:You are using the wrong task to get the credentials. The UsePythonVersion@0 task does not have the options to receive ARM service connection and run script.
The correct task you should use is AzureCLI@2. See below sample as refence.
Note:
This feature does not return the Azure Subscription Id.