Terraform in Azure Devops without additional tasks
I don’t know how you and your team look at custom Azure Devops tasks developed outside of your company. I have mixed feelings about that. Moreover sometimes I need more flexibility than given by someone’s tasks. Third thing is that I want to use Powershell for whatever reason.
Basing on that I ended with scripts based on AzureCLI@2 task. First I get all the needed credentials in one task like this:
- task: AzureCLI@2
name: tfCredentials
displayName: Terraform credentials
inputs:
azureSubscription: <SERVICE_CONNECTION_NAME>
scriptType: ps
scriptLocation: inlineScript
inlineScript: |
$subscriptionId=$(az account show --query id -o tsv)
echo "##vso[task.setvariable variable=ARM_CLIENT_ID]$env:serviceprincipalid"
echo "##vso[task.setvariable variable=ARM_CLIENT_SECRET]$env:serviceprincipalkey"
echo "##vso[task.setvariable variable=ARM_SUBSCRIPTION_ID]${subscriptionId}"
echo "##vso[task.setvariable variable=ARM_TENANT_ID]$env:tenantid"
addSpnToEnvironment: true
After that I use those variables in any other task.
- task: AzureCLI@2
displayName: "terraform init plan"
inputs:
azureSubscription: <SERVICE_CONNECTION_NAME>
scriptType: ps
scriptLocation: inlineScript
inlineScript: | terraform init -backend-config=subscription_id="$env:ARM_SUBSCRIPTION_ID" -backend-config=tenant_id="$env:ARM_TENANT_ID" -backend-config=client_id="$env:ARM_CLIENT_ID" -backend-config=client_secret="$env:ARM_CLIENT_SECRET" terraform plan -out tfplan.out -input=false
terraform apply -input=false -auto-approve tfplan.out
Of course this is only an excerpt from actual solution. You probably don’t want to auto-approve plan like that. I just wanted to show the general idea of connecting from AzureCLI@2 task with terraform (1.0.7 if you’re interested).
This approach is based on idea presented here for bash: https://cloudarchitected.com/2021/02/using-terraform-in-azure-pipelines-without-extensions/.
I got to this solution because charleszipp.azure-pipelines-tasks-terraform.azure-pipelines-tasks-terraform-cli.TerraformCLI@0 task wasn’t flexible enough for my case. I want to find to go to terraform directories dynamically and in a loop (for instance looping through changed subdirectories basing on git diff).