microsoft / terraform-azure-devops-starter

A starter project for Azure DevOps Pipelines deploying resources on Terraform.
MIT License
164 stars 142 forks source link

Now it is possible to skip approval and deployment if there are no changes in the Terraform plan #4

Open HoussemDellai opened 4 years ago

HoussemDellai commented 4 years ago

It's not currently possible to skip approval and deployment if there are no changes in the Terraform plan, because of limitations in multi-stage pipelines (stages cannot be conditioned on the outputs of previous stages). You could cancel the pipeline (through the REST API) in that case, but that would prevent extending the pipeline to include activities beyond Terraform.

Actually this is now possible!

Here is a sample pipeline that can do that:

trigger:
- master
resources:
- repo: self
pool:
  vmImage: 'ubuntu-16.04'

variables:
  **MyVar**: 'MyVal'
 
stages:
- stage: Save_Variable
 
  jobs:
  - job: Save_Variable
    steps:
      - pwsh: Write-Host "##vso[task.setvariable variable=**MyVar**;isOutput=true]NewVal"
        name: MyOutputVar
 
- stage: Read_Variables
  dependsOn: Save_Variable
   
  jobs:
    - job: Read_Variable
      variables:
        **prevStageVar**: $[stageDependencies.Save_Variable.Save_Variable.outputs['MyOutputVar.**MyVar**']]
      steps:
      - powershell: 'Write-Host "Get Stage variable: **$(prevStageVar)**"'

And here is a video I made for that (skipping terraform apply, but not across stages here) : Video: Skip terraform apply in Azure DevOps pipelines

jikuja commented 3 years ago

The documentation for this is well-hidden: https://docs.microsoft.com/en-us/azure/devops/pipelines/process/expressions?view=azure-devops&branch=pr-en-us-1603#job-to-job-dependencies-across-stages

Other parts of ADO documentation only cover output sharing inside the job and stage only.

Edit: I did some experimentation and using script output variable as an input of stage condition is impossible. Therefore there will be a deployment stage that skips one or multiple (deployment) jobs.

vanmash commented 1 year ago

One can use changesPresent to see if apply is needed.

https://github.com/microsoft/azure-pipelines-terraform/tree/main/Tasks/TerraformTask/TerraformTaskV3#output-variables