Terraform AzureDevOps – Pipeline

deploy terraform using pipelines

The biggest challenge to automate the deployment of Azure resource creation more than once, we need to create Azure DevOps Pipeline. The Azure DevOps pipeline will use your terraform template and deploy to Azure to create resources.

Requirements:

First we need to create azure storage account and container to store the Terraform State file that will be used during deployments.

Please check below pipeline yaml file content that will be used to deploy your terraform .

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

variables:
  subscription: "your subscription"
  resourceGroup: "storage resource group"
  storageAccount: "storage accoutn name"
  container: "container name"
  tfstateFile: "terraform tfstate file name"
  anyTfChanges: false

steps:

- task: TerraformInstaller@0
  displayName: install Terraform v1.0.4
  inputs:
    terraformVersion: '1.0.4'

- task: TerraformTaskV2@2
  displayName: init
  inputs:
    provider: 'azurerm'
    command: 'init'
    workingDirectory: '$(System.DefaultWorkingDirectory)'
    backendServiceArm: '$(subscription)'
    backendAzureRmResourceGroupName: '$(resourceGroup)'
    backendAzureRmStorageAccountName: '$(storageAccount)'
    backendAzureRmContainerName: '$(container)'
    backendAzureRmKey: '$(tfstateFile)'

- task: TerraformTaskV1@0
  displayName: terraform plan -out=tfplan
  inputs:
    provider: 'azurerm'
    command: 'plan'
    workingDirectory: '$(System.DefaultWorkingDirectory)'
    commandOptions: '-out=tfplan'
    # commandOptions: '-detailed-exitcode -out=tfplan'
    environmentServiceNameAzureRM: '$(subscription)'

- task: PowerShell@2
  displayName: detect any terraform change
  inputs:
    workingDirectory: '$(System.DefaultWorkingDirectory)'
    targetType: 'inline'
    script: |
      # Write-Host "LASTEXITCODE : $LASTEXITCODE"
      $plan = $(terraform show -json tfplan | ConvertFrom-Json)
      $actions = $plan.resource_changes.change.actions
      Write-Host "Terraform actions : $actions"
      if (($actions -contains 'create') -or ($actions -contains 'delete') -or ($actions -contains 'update'))
      {
        Write-Host "Terraform will perform the following actions : $actions"
        Write-Host "##vso[task.setvariable variable=anyTfChanges;]true"
      }
      else
      {
        Write-Host "There is no change detected in Terraform tfplan file"
      }

- task: TerraformTaskV1@0
  displayName: terraform apply tfplan
  condition: eq(variables.anyTfChanges, true)
  inputs:
    provider: 'azurerm'
    command: 'apply'
    workingDirectory: '$(System.DefaultWorkingDirectory)'
    commandOptions: 'tfplan'
    environmentServiceNameAzureRM: '$(subscription)'

 

 

Exit mobile version