You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitHub Actions无需needs传递IMAGE_SHA至部署作业的方法

解决GitHub Actions中build与deploy作业的SHA传递问题

核心思路

PR合并到master分支时,push事件对应的github.sha就是PR提交的完整哈希值,和build作业中使用的哈希完全一致。因此无需在两个作业间传递值,直接在deploy作业中重新生成短哈希即可,结果与build阶段完全匹配。

具体实现方案

方案1:在deploy作业中生成短哈希

添加与build作业一致的短哈希生成步骤,确保取值相同:

deploy:
    if: (github.event_name == 'push' && github.ref == 'refs/heads/master')
    name: 🚀 Deploy To Development 🚀
    runs-on: ubuntu-latest
    steps:
        - name: Checkout code
          uses: actions/checkout@v4
          with:
            fetch-depth: 1 # 仅拉取最新提交,提升执行速度
        - name: Generate Short GIT Commit HASH
          id: vars
          run: echo "sha_short=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
        # 后续部署步骤中,使用 ${{ steps.vars.outputs.sha_short }} 作为 IMAGE_SHA
        - name: Execute Deployment
          run: |
            IMAGE_SHA=${{ steps.vars.outputs.sha_short }}
            # 此处添加你的部署命令,比如拉取镜像、部署到开发环境等

方案2:直接通过GitHub上下文截取短哈希

无需额外步骤,利用GitHub内置的字符串处理功能直接生成短哈希:

deploy:
    if: (github.event_name == 'push' && github.ref == 'refs/heads/master')
    name: 🚀 Deploy To Development 🚀
    runs-on: ubuntu-latest
    steps:
        - name: Execute Deployment
          run: |
            IMAGE_SHA=${{ github.sha | substr(0,7) }}
            echo "Deploying image tagged with $IMAGE_SHA"
            # 此处添加你的部署命令

可行性说明

当PR合并到master时:

  • 若为快进合并,push事件的github.sha就是PR提交的哈希值;
  • 若为创建合并提交,build作业在合并队列阶段(gh-readonly-queue/master/**分支)已经使用该合并提交哈希构建了镜像。

两种场景下,deploy阶段生成的短哈希都能与build阶段的镜像标签完全匹配,确保部署的是PR审核通过的镜像版本。

内容的提问来源于stack exchange,提问作者Kermit the Frog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:28:17