问题
I want to build a docker image using a GitHub action, migrating from TeamCity.
In the build script, I want to tag the image with a combination of branch and commit, e.g. master.ad959de
. Testing that locally, I get that information like this:
git_branch=`git symbolic-ref --short HEAD`
git_hash=`git rev-parse --short HEAD`
docker_version=${git_branch}.${git_hash}
This is the relevant part of the GitHub action:
name: CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Create docker image
run: ./docker-build.sh
Running that script in that GitHub action results in this error:
fatal: ref HEAD is not a symbolic ref
How can I generate a tag like that inside a GitHub action?
回答1:
from Using environment variables
github provides two variables that are useful here, you'll need to process them a bit to get the values you desire:
GITHUB_SHA
: The commit SHA that triggered the workflow. For example,ffac537e6cbbf934b08745a378932722df287a53
.
GITHUB_REF
: The branch or tag ref that triggered the workflow. For example,refs/heads/feature-branch-1
. If neither a branch or tag is available for the event type, the variable will not exist.
The short values can be extracted like this:
git_hash=$(git rev-parse --short "$GITHUB_SHA")
git_branch=${GITHUB_REF##*/}
回答2:
A handy way to get the currrent branch and commit sha on the workflow could be getting it and saving on a "variable".
- name: Declare some variables
id: vars
shell: bash
run: |
echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
echo "::set-output name=sha_short::$(git rev-parse --short HEAD)"
- name: Another step
run: |
echo "Branch: ${{ steps.vars.outputs.branch }}"
echo "Sha: ${{ steps.vars.outputs.sha_short }}"
Maybe your docker-build.sh
could receive the branch and she as parameter, os the full version as parameter.
- name: Create docker image
run: ./docker-build.sh "${{ steps.vars.outputs.branch }}.${{ steps.vars.outputs.sha_short }}"
OR JUST
- name: Create docker image
run: ./docker-build.sh "${GITHUB_REF#refs/heads/}.${GITHUB_SHA}"
On this action you can see many tests I done to see what works, what don't.
回答3:
You can get it this way in your sh file -
BRANCH_NAME=$(echo $GITHUB_REF | cut -d'/' -f 3)
GITHUB_SHA_SHORT=$(echo $GITHUB_SHA | cut -c1-8)
来源:https://stackoverflow.com/questions/58886293/getting-current-branch-and-commit-hash-in-github-action