Azure DevOps Terraform Pipeline

I was recently working on a project that required me to create a Terraform pipeline in Azure DevOps. I had never done this before, so I had to do some research to figure out how to set it up. In this article, I will share the final pipeline that I created, as well as some of the resources that I found helpful along the way.

Preconditions

Terraform Pipeline

stages:
  - stage: Terraform
    jobs:
    - job: Terraform
      pool:
        vmImage: 'ubuntu-latest'
      steps:
      - task: CmdLine@2
        displayName: 'Terraform Install'
        inputs:
          script: |
# https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli#install-terraform
            sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
            wget -O- https://apt.releases.hashicorp.com/gpg | \
              gpg --dearmor | \
              sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg > /dev/null
            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 update
            sudo apt-get install terraform
            terraform --version

      - task: AzureCLI@2
        displayName: 'Terraform Plan'
        inputs:
          addSpnToEnvironment: true
          azureSubscription: MyServiceConnection
          scriptType: bash
          scriptLocation: inlineScript
          workingDirectory: '$(System.DefaultWorkingDirectory)/infrastructure'
          inlineScript: |
# https://devblogs.microsoft.com/devops/public-preview-of-workload-identity-federation-for-azure-pipelines/#azure-cli-task-support-for-inline-authentication
            export ARM_CLIENT_ID=$servicePrincipalId
            export ARM_OIDC_TOKEN=$idToken
            export ARM_TENANT_ID=$tenantId
            export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
            export ARM_USE_OIDC=true

            terraform init \
              -var-file="./env/dev/input.tfvars" \
              -backend-config="./env/dev/backend.tfvars"

            terraform plan \
              -var-file="./env/dev/input.tfvars" \
              -input=false

Comments

comments powered by Disqus