Azure pipeline 配置根据条件执行脚本

  • 2019 年 10 月 14 日
  • 筆記

Azure pipeline 配置根据条件执行脚本

Intro

我的应用通过 azure pipeline 来做持续集成,之前已经介绍了根据不同分支去打包不同的package,具体的就不再这里详细介绍了,可以参考 持续集成之nuget进阶,nuget 包可以做到根据不同的分支来
发布不同的包,那么我的应用一定也可以做到不同的分支发布不同 tag 的 docker 镜像,最后通过 azure pipeline 内置的 Condition 来做判断,可以加一些条件脚本在满足特定条件下才执行的脚本再加上变量控制,就可以比较好的实现根据分支策略来发布不同 tag 的 docker 镜像了

Solution

来看一下修改之后的 azure-pipelines.yaml 示例配置吧:

steps:  # ...  - script: docker push $(latestImageName)    displayName: 'Push latest image'    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/dev'))    - script: docker push $(stableImageName)    displayName: 'Push stable image'    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/master'))    - task: SSH@0    displayName: 'Run shell inline on remote machine'    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/dev'))    inputs:      sshEndpoint: 'weihanli-vm'      runOptions: inline        inline: |        kubectl set image deployment/activityreservation activityreservation=$(imageName) --record=true

当前面的 step 运行成功并且是 master 分支的 build 时,发布 tag 为 stable 的 docker 镜像,如果是 dev 分支则发布 tag 为 latest 的 docker 镜像,并且仅当当前分支为 dev 时才执行部署操作。

完整配置可以在 Github
上获取

CI 执行过程

上图是一个 dev 分支的 build,从上面的截图可以看到,只有 master 分支才执行的 step,没有被执行,直接跳过了

Reference

  • < https://docs.microsoft.com/zh-cn/azure/devops/pipelines/process/conditions?view=azure-devops&tabs=yaml >