Search code examples
gitazure-pipelinesazure-reposazure-pipelines-yaml

Run Azure Pipelines job only when certain files are changed


I have a repository that contains both a Dockerfile and other code. We want to run certain steps regardless of what changed, but only want to run the docker build job when **/Dockerfile is changed.

I've reviewed the Conditions documentation and the Expressions documentation but it's unclear to me how (if it's possible at all) how to combine these or otherwise achieve the desired outcome.

I realize it's possible in bash (e.g. git rev-list... and git diff --name-only <previous_commit>..HEAD | grep <pattern>) but this is a bit cumbersome and it still shows in Azure Pipelines that the job ran, it just short-circuited. Ideally it would show (appropriately) that the job was skipped all together.

I also realize that that the Docker portion and the code portion could be in separate repositories with separate build triggers, but would like to keep them together in the same repo if possible.


Solution

  • Sorry but there's no trigger per job. Trigger is for pipeline scope.

    According to your requirements, you may take this structure as a workaround:

    jobs: 
      - job: OtherSteps
        steps:
        Your other steps in this job.
        - task: PowerShell@2
          inputs:
            targetType: 'inline'
            script: |
              $changedfiles = git diff ... (Choose right git command depending on your needs.)
              Write-Host $changedfiles
              If ($changedfiles.Contains("Dockerfile"))  {
                echo "##vso[task.setvariable variable=IfRunDockerBuild;isOutput=true]run"
              }
          name: 'DetermineIfRunNextJob'
    
      - job: DockerBuild
        dependsOn: OtherSteps
        condition: eq(dependencies.OtherSteps.outputs['DetermineIfRunNextJob.IfRunDockerBuild'],'run')
        steps:
        - script: echo Only run this job when IfRunDockerBuild=run instead of Null!
    

    1.Assuming your have job1 and job2(docker build), you just need to add one PS task like above in the end of the job1. Then it outputs one variable which determines if we need to run job2 or skip it.

    2.The Powershell task can run on Linux, macOS, or Windows.

    2.The core of this workaround comes from this feature: Use the output variable from a job in a condition in a subsequent job.