Search code examples
gitgithubyamlgithub-actionsworkflow

Cannot force push to main branch using GitHub Actions


Error:

! [remote rejected]     main -> main (refusing to allow a GitHub App to create or update workflow `.github/workflows/docker.yml` without `workflows` permission)

After researching a bit, I learnt that I need to give it the necessary permissions. I have no idea from where and how can I grant it the permission. I don't have much experience either.

How should I fix this error? This is being caused because I'm forcing my changes to the repo since normal pushes are being rejected.

I'm very well aware that I should not be using --force in the first place. Since I need to push them, I'm obligated to do so. I pull from main before pushing, it causes conflicts that needs to be resolved manually which I don't want to.
If there's any work around, I'm happy to implement that as well.

Code:

name: Update Fork

on:
  workflow_dispatch:
  schedule:
    - cron: '0 10 * * *' # runs every everyday at 10:00

jobs:
  update_fork:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout Forked Repo
      uses: actions/checkout@v2
      with:
        repository: username/repo_name
        ref: main

    - name: Setup Git
      run: git config --global user.email ${{ secrets.EMAIL }} && git config --global user.name user_name

    - name: Check for Upstream Changes
      run: |
        git remote add upstream https://github.com/upstream_user_name/upstream_repo

        upstream_commit=$(git ls-remote --heads upstream | grep main | awk '{print $1}')
        # forked_commit=$(git rev-list --max-count=1 HEAD)
        forked_commit=$(git log -n 10 --pretty=%H)

        # if git rev-list $forked_commit..HEAD | grep -q $upstream_commit; then
        if echo "$forked_commits" | grep -q "$upstream_commit"; then
          echo "No commits to be synced!"
        else
          git fetch upstream
          git pull --rebase -X ours upstream main
          git push -f origin main

          echo "Rebase successful!"
        fi

After this code failed to push commits, I added below code:

      with:
        repository: username/repo_name
        ref: main
        repo-token: ${{ secrets.GITHUB_TOKEN }}

This didn't fix the issue either. And I'm pretty sure this was wrong..


Solution

  • Based on the error it looks like your git user does not have access to update workflows.

    There doesn't appear to be an explicitly defined workflows permission, but there is an OAuth scope for workflow.

    Try adding this permission to your workflow.

    permissions:
      actions: write
    

    If that doesn't work, try this, I have needed to add this before to a workflow that was committing back to the repo.

    permissions:
      contents: write