I am trying to create a simple rollback workflow that will get the previous SHA of 'main' branch and deploy a docker image with that tag. In my local machine this command works -
git rev-parse HEAD~1
And returns previous SHA. So I created a workflow around it to set output of a variable but now I am getting this error-
Run echo "prev_sha=$(git rev-parse HEAD~1)" >> "$GITHUB_OUTPUT"
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
This is the workflow -
on: workflow_dispatch
jobs:
get_prev_sha:
name: get previous sha of main
runs-on: ubuntu-latest
outputs:
prev_sha: ${{ steps.prev_sha.outputs.prev_sha }}
steps:
- name: Checkout
uses: actions/checkout@v3
with:
ref: 'main'
- name: Get last commit SHA
id: prev_sha
run: |
echo "prev_sha=$(git rev-parse HEAD~1)" >> "$GITHUB_OUTPUT"
My only question is, how do I get the previous (2nd last) hash of a branch using GitHub Actions and set is as output? Any help is appreciated.
According to the description of actions/checkout@v4:
Only a single commit is fetched by default, for the ref/SHA that triggered the workflow. Set
fetch-depth: 0
to fetch all history for all branches and tags.
and, here's the usage of fetch-depth
:
# Number of commits to fetch. 0 indicates all history for all branches and tags.
# Default: 1
fetch-depth: ''
So, you can use fetch-depth
to fetch the last two commits only i.e. fetch-depth: 2
and git rev-parse HEAD~1
should return the correct commit hash.