GitHub动作,更新另一个动作的工作流文件



我在同一个repo中有两个GitHub Actions。我试图从另一个更新一个,但在尝试提交和推送更改时,我得到以下错误:

! [remote rejected] HEAD -> some-branch (refusing to allow a GitHub App to create or update workflow .github/workflows/the-other-action.yml without workflows permission)

这是我试图运行的GH动作的简化版本:

name: my-action
on:
workflow_dispatch:
schedule:
- cron: "0 9 * * *"
jobs:
components:
runs-on: ubuntu-latest
steps:
- name: Checkout the code
uses: actions/checkout@v2
- name: Update the other Action
run: |
# Do something to .github/workflows/the-other-action.yaml here
- name: Create Pull Request
uses: peter-evans/create-pull-request@v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
branch: some-branch
commit-message: Updated stuff

我想弄清楚如何给workflows许可给GITHUB_TOKEN,但不确定如何?

(对于上下文:我每天运行此操作一次,以检查其他操作中使用的工具的新版本是否已发布。)如果是,它将创建一个PR来更新其他操作以使用新版本)

您需要在这里使用具有工作流权限的个人访问令牌,而不是具有定义范围的GITHUB_TOKEN

实际上,这只是在2022年9月8日改变了:

GitHub Actions:使用GITHUB_TOKENworkflow_dispatchrepository_dispatch

客户现在将能够使用GITHUB_TOKENworkflow_dispatchrepository_dispatch事件来触发工作流。

在此更改之前,由GITHUB_TOKEN触发的事件不会创建新的工作流运行。这样做是为了防止意外触发无休止的工作流。

此更新对workflow_dispatchrepository_dispatch事件例外,因为它们是由客户进行的显式调用,不太可能以循环结束。

name: Create Workflow Dispatch
on:   workflow_dispatch:
jobs:   build:
runs-on: ubuntu-latest
steps:
- name: Trigger Workflow
uses: actions/github-script@v6
with:
script: |
github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'test.yml',
ref: 'main',
})

详细信息请参见
从工作流中触发工作流.

所以GITHUB_TOKEN现在可以工作了。


在OP问题的上下文中:这里的主要任务是从另一个工作流中修改工作流文件。

我上面提到的最近的GitHub更改允许使用GITHUB_TOKEN触发工作流,但它没有明确提到是否可以使用令牌直接将更改推送到工作流文件。这个能力可以解决原来的问题。

您仍然需要修改您的工作流以提交并将更改推送到工作流文件。尝试更新工作流文件的操作步骤如下所示:

- name: Update the other Action
run: |
# Do something to .github/workflows/the-other-action.yaml here
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add .github/workflows/the-other-action.yaml
git commit -m "Update the other Action"
git push

您需要使用一个具有必要权限的令牌来推动更改,并且您可以使用GITHUB_TOKEN的更新功能来测试它:

对于peter-evans/create-pull-request@v3动作,这将是:

- name: Create Pull Request
uses: peter-evans/create-pull-request@v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
branch: some-branch
commit-message: Updated stuff

您需要使用具有工作流权限的个人访问令牌这里,而不是GITHUB_TOKEN,它有一个定义的范围。

此外,如果此${{ secrets.GITHUB_TOKEN }}是您的PAT,则可能存在问题,因为您不能使用GITHUB_前缀添加秘密。因此,您必须按照此语法重命名secret。

最新更新