Search code examples
githubgithub-actions

How to get the current branch within GitHub Actions?


I'm building Docker images with GitHub Actions and want to tag images with the branch name.

I found the GITHUB_REF variable, but it results in refs/heads/feature-branch-1 and I need only feature-branch-1.


Solution

  • I added a separate step for extracting branch name from $GITHUB_HEAD_REF/$GITHUB_REF¹ (pr and push) and set it to the step output:

    - name: Extract branch name
      shell: bash
      run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_OUTPUT
      id: extract_branch
    

    after that, I can use it in the next steps with steps.<step_id>.outputs.branch:

    - name: Push to ECR
      id: ecr
      uses: jwalton/gh-ecr-push@master
      with:
        access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        region: us-west-2
        image: eng:${{ steps.extract_branch.outputs.branch }}
    

     


    ¹ $GITHUB_HEAD_REF on pull_request (pr) and $GITHUB_REF on push. Description:

    Variable Description
    GITHUB_HEAD_REF The head ref or source branch of the pull request in a workflow run. This property is only set when the event that triggers a workflow run is either pull_request or pull_request_target. For example, feature-branch-1. (source)
    GITHUB_REF The fully-formed ref of the branch or tag that triggered the workflow run. For workflows triggered by push, this is the branch or tag ref that was pushed. For workflows triggered by pull_request, this is the pull request merge branch. For workflows triggered by release, this is the release tag created. For other triggers, this is the branch or tag ref that triggered the workflow run. This is only set if a branch or tag is available for the event type. The ref given is fully-formed, meaning that for branches the format is refs/heads/<branch_name>, for pull requests it is refs/pull/<pr_number>/merge, and for tags it is refs/tags/<tag_name>. For example, refs/heads/feature-branch-1. (source)

    Full description of these and all other Default environment variables - Learn Gihtub Actions (archived copy).

    Looking for the Microsoft Github Action Context named github? See the answer by ysfaran and/or the answer by Dusan Plavak.