Azure DevOps中如何规划CI流水线实现目录变更触发对应Docker镜像构建推送
Azure DevOps 多应用目录按需构建Docker镜像流水线实现方案
核心逻辑是通过识别代码变更的路径,仅触发对应目录的镜像构建推送任务,两种实现方案如下:
方案1:内置路径触发器(适合应用数量少、变更不频繁的场景)
直接在流水线YAML中为每个应用配置独立的构建Job,通过路径过滤规则控制Job是否执行:
- 流水线触发分支按需配置,每个Job添加路径匹配条件,仅当对应应用目录下的文件发生变更时才执行
- 示例配置如下:
trigger: branches: include: - main # 替换为你需要触发的分支名 paths: include: - app1/* - app2/* - app3/* stages: - stage: BuildImages jobs: - job: BuildApp1 condition: contains(variables['Build.ChangedFiles'], 'app1/') steps: - task: Docker@2 inputs: containerRegistry: '你的ACR服务连接名称' repository: 'app1' command: 'buildAndPush' Dockerfile: 'app1/dockerfile' buildContext: 'app1' tags: '$(Build.BuildId)' - job: BuildApp2 condition: contains(variables['Build.ChangedFiles'], 'app2/') steps: - task: Docker@2 inputs: containerRegistry: '你的ACR服务连接名称' repository: 'app2' command: 'buildAndPush' Dockerfile: 'app2/dockerfile' buildContext: 'app2' tags: '$(Build.BuildId)' - job: BuildApp3 condition: contains(variables['Build.ChangedFiles'], 'app3/') steps: - task: Docker@2 inputs: containerRegistry: '你的ACR服务连接名称' repository: 'app3' command: 'buildAndPush' Dockerfile: 'app3/dockerfile' buildContext: 'app3' tags: '$(Build.BuildId)'
方案2:动态识别变更目录(适合应用数量多、后续会新增应用的场景)
通过前置脚本自动识别变更的应用目录,动态生成构建任务,新增应用时无需修改流水线配置:
- 第一步添加变更识别Job,执行git命令提取本次变更的应用目录,输出为流水线变量
示例脚本如下:# 拉取足够的提交历史(若检出时配置了fetchDepth=0可跳过) git fetch origin main --depth=2 # 提取变更的app开头的根目录,去重后输出为流水线变量 CHANGED_APPS=$(git diff --name-only origin/main HEAD | awk -F/ '{print $1}' | grep '^app' | sort | uniq | tr '\n' ' ') echo "##vso[task.setvariable variable=changedApps;isOutput=true]$CHANGED_APPS" - 第二步通过each表达式遍历变更的应用列表,为每个变更的应用执行镜像构建推送
示例配置如下:- job: BuildChangedApps dependsOn: GetChangedApps variables: changedApps: $[ dependencies.GetChangedApps.outputs['getChangedStep.changedApps'] ] steps: - ${{ each app in split(variables.changedApps, ' ') }}: - task: Docker@2 inputs: containerRegistry: '你的ACR服务连接名称' repository: '${{ app }}' command: 'buildAndPush' Dockerfile: '${{ app }}/dockerfile' buildContext: '${{ app }}' tags: '$(Build.BuildId)'
注意事项
- 流水线检出代码时建议设置
fetchDepth: 0拉取全量提交历史,避免git diff无法识别变更 - ACR服务连接需提前在Azure DevOps项目的「服务连接」中创建,确保有镜像推送权限
内容的提问来源于stack exchange,提问作者notageek27
相关产品推荐
相关产品推荐

