如何在 GitHub Action 中推送到受保护的主分支?

Wad*_*ade 27 github github-actions

这是我的 github 操作工作流程。

\n
name: Release\n\non:\n  push:\n    branches:\n      - main\n\njobs:\n  release:\n    name: Release\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v2\n        with:\n          persist-credentials: false\n      - name: Setup java\n        uses: actions/setup-java@v1\n        with:\n          java-version: 11\n      - name: Setup node\n        uses: actions/setup-node@v1\n        with:\n          node-version: "14.x"\n          cache: npm\n      - name: Install dependencies\n        run: npm ci\n      - name: Build package\n        run: npm run build --if-present\n      - name: Semantic release\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}\n          HUSKY: 0\n        run: chmod +x script/prepare-release.sh && npx semantic-release\n
Run Code Online (Sandbox Code Playgroud)\n

但是,我的工作流程失败并出现以下错误日志。

\n
[semantic-release] \xe2\x80\xba \xe2\x9c\x96  An error occurred while running semantic-release: Error: Command failed with exit code 1: git push --tags https://x-access-token:[secure]@github.com/didrlgus/convention-template.git HEAD:main\nremote: error: GH006: Protected branch update failed for refs/heads/main.        \nremote: error: At least 1 approving review is required by reviewers with write access.      \n
Run Code Online (Sandbox Code Playgroud)\n

也许是因为我的主分支是受保护的分支。
\n如何在 github 操作上使用受保护的分支进行推送?

\n

小智 27

有一个解决方法。步骤如下:

  1. 创建新的 Github 用户,例如。my-org-bot

  2. 在https://github.com/settings/tokens上为此用户生成个人访问令牌并将其保存在某处(选择令牌的存储库范围)

  3. 转到您的存储库并添加my-org-bot到贡献者

  4. 打开您的分支保护规则并添加my-org-bot到以下规则: 在此输入图像描述

  5. 转到存储库机密并为带有 key =BOT_ACCESS_TOKEN和 value =之前生成的个人访问令牌的操作添加新机密

  6. 修改您的 GH 工作流程结账步骤如下: 在此输入图像描述

现在您的工作流程应该能够代表my-org-bot用户直接推送到受保护的分支。


Yaa*_*aaZ 11

刚刚发现你可以使用GitHub 部署密钥

  1. 生成 SSH 密钥对:ssh-keygen -t ed25519. 不需要密码等。

  2. 添加公钥(.pub一)作为部署密钥Your repo -> Settings -> Security -> Deploy keys,选中“允许写入访问”。

  3. 添加私钥作为秘密Your repo -> Settings -> Security -> Secrets and variables -> Actions

  4. 查看存储库时指定您的密钥:

    - name: Checkout
      uses: actions/checkout@v3.5.2
      with:
        ssh-key: ${{secrets.YOUR_SECRET_KEY}}
    
    Run Code Online (Sandbox Code Playgroud)

此类部署密钥不与任何帐户绑定,但提供完全写入访问权限,包括绕过分支保护规则:

具有写入访问权限的部署密钥可以与具有管理员访问权限的组织成员或个人存储库上的协作者执行相同的操作。