如何避免GitHub Actions workflow推送至main分支时递归触发
解决GitHub Actions Workflow递归触发自身的问题
问题根源
你当前的workflow递归触发的原因是:虽然你设置了GITHUB_TOKEN环境变量,但push操作实际使用的是checkout步骤中配置的自定义token(secrets.xxx),而非官方的GITHUB_TOKEN。只有GITHUB_TOKEN发起的推送才会被GitHub自动跳过workflow触发,自定义token没有这个特性。
解决方案
下面提供三种可靠的解决方式,任选其一即可:
方式一:全程使用GITHUB_TOKEN操作仓库
如果你的操作不需要自定义token的额外权限,直接替换checkout步骤的token为GITHUB_TOKEN:
name: Test preventing workflow recursion on: workflow_dispatch: push: branches: - main jobs: run: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3.5.2 with: token: ${{ secrets.GITHUB_TOKEN }} # 替换为官方token - name: Make changes and commit run: | echo a >> test.txt git config user.name 'github-actions[bot]' git config user.email 'github-actions[bot]@users.noreply.github.com' git add . git commit -m "Update explorationsContent.md" --no-verify git push
这样push时会自动使用GITHUB_TOKEN,GitHub会跳过后续的workflow触发,避免递归。
方式二:保留自定义token,但push时改用GITHUB_TOKEN
如果必须使用自定义token完成checkout,那么在push前修改远程仓库URL,强制使用GITHUB_TOKEN:
name: Test preventing workflow recursion on: workflow_dispatch: push: branches: - main jobs: run: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3.5.2 with: token: ${{ secrets.xxx }} - name: Make changes and commit run: | echo a >> test.txt git config user.name 'bot' git config user.email '...' git add . git commit -m "Update explorationsContent.md" --no-verify # 修改远程URL,使用GITHUB_TOKEN推送 git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git git push
方式三:通过触发条件过滤机器人推送
在workflow的触发规则中,排除由github-actions[bot]发起的推送(这是GITHUB_TOKEN对应的默认actor):
name: Test preventing workflow recursion on: workflow_dispatch: push: branches: - main if: github.actor != 'github-actions[bot]' # 过滤机器人推送 jobs: run: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3.5.2 with: token: ${{ secrets.xxx }} - name: Make changes and commit run: | echo a >> test.txt git config user.name 'github-actions[bot]' git config user.email 'github-actions[bot]@users.noreply.github.com' git add . git commit -m "Update explorationsContent.md" --no-verify git push https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git main
这种方式即使push用了自定义token,只要actor是机器人,就不会触发workflow。
内容的提问来源于stack exchange,提问作者Aaron Girard
相关产品推荐
相关产品推荐

