如何列出指定分支所有Commit并选择特定Commit运行GitHub Workflow?
实现选择特定Commit部署的方案
可以通过扩展workflow_dispatch的自定义输入参数,结合actions/checkout的分支/Commit指定功能来实现需求,具体步骤如下:
1. 修改Workflow配置,添加自定义输入项
在原配置的on.workflow_dispatch部分添加输入参数,让用户可以指定目标分支(用于参考Commit列表)和要部署的Commit SHA:
name: myWorkflow on: workflow_dispatch: inputs: target_branch: description: '目标分支(用于查看Commit列表)' required: true default: 'main' target_commit: description: '要部署的Commit完整SHA或短SHA' required: true permissions: id-token: write contents: write packages: write env: LOG_LEVEL: ${{ vars.LOG_LEVEL }} ACCOUNT_DOMAIN: ${{vars.ACCOUNT_DOMAIN}} DATO_INTEGRATION_LAMBDA: ${{ vars.SOMETHING }} APPSYNC_API_KEY: ${{ secrets.SOMETHING2}} defaults: run: shell: bash jobs: production: name: Deploy to Production runs-on: ubuntu-latest needs: package environment: prod steps: - name: Checkout指定Commit uses: actions/checkout@v3 with: ref: ${{ github.event.inputs.target_commit }} fetch-depth: 0 # 拉取完整历史,方便后续校验 - name: 校验Commit是否属于目标分支(可选) run: | git fetch origin ${{ github.event.inputs.target_branch }} if ! git branch -r --contains ${{ github.event.inputs.target_commit }} | grep -q "origin/${{ github.event.inputs.target_branch }}"; then echo "ERROR: 指定的Commit不属于目标分支${{ github.event.inputs.target_branch }}" exit 1 fi - name: Deploy uses: ./.github/actions/deploy with: stage: prod aws-region: eu-north-1 deploy-role-arn: ${{ secrets.DEPLOY_ROLE_ARN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} environment: staging
2. 使用方式
当你点击"运行Workflow"时,会出现两个输入框:
- 先填写目标分支(默认是main),可以先在GitHub仓库的该分支页面查看所有Commit列表,复制需要的Commit SHA
- 粘贴Commit SHA到
target_commit输入框,然后触发Workflow即可
关键说明
actions/checkout的ref参数支持分支名、Tag名或Commit SHA,直接指定Commit SHA就能拉取对应版本的代码- 添加的校验步骤是可选的,用于防止用户输入不属于目标分支的Commit,避免误部署
fetch-depth: 0确保拉取完整的仓库历史,这样才能执行Commit归属校验
内容的提问来源于stack exchange,提问作者CodingLittle
相关产品推荐
相关产品推荐

