How to build a Docker image using github action for the last commit on a pull request

Hi all,

  • I was trying to build a Docker Image from a Dockerfile file in my repository using/inside the GitHub action.
  • The image should be created for the last commit on a pull request.
  • I was running the Github Actions on issue_comment basis which also involves pull request comments and I tried to use docker build command inside this like:
name: Litmus-CI
on:
  issue_comment:
    types: [created, edited]
jobs:
  tests:
    if: contains(github.event.comment.html_url, '/pull/') && contains(github.event.comment.body, '/run-e2e')
    runs-on: ubuntu-latest
    steps:

      - name: Running git checkout
        uses: actions/checkout@v2

      - name: Build docker image
        run: |
          sudo docker build . -f build/ansible-runner/Dockerfile -t uditgaurav/demo-litmus-e2e:v1
          sudo docker images

So will the image build using the above code will be on the last commit on pull request basis or it will be a general image build of the repository?
secondly, Are there any actions around this - for building the image of the last commit in PR?
Thanks!

The GITHUB_SHA of issue_comment event is the Last commit on default branch. So it could not get the last commit on pull_request.
As a work around , please follow next steps to get the last commit in PR

  1. You could get the PR number from the payload of issue comment event : github.event.issue.number .
  2. Use the PR number to get its commits through this API . You could use octokit/request-action to send request to GitHub API. This action will output the response body to an output variable data.
  3. Use jq to get the commit id from the response data. Then set the value to an output variable
  4. When execute checkout action, you could add ref parameter with the commit id as value.
    There is my sample workflow :
on:
  issue_comment:
    types: [created, edited]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: octokit/request-action@v2.x
        id: get_PR_commits
        with:
          route: GET /repos/:repo/pulls/:pull_number/commits
          repo: ${{ github.repository }}
          pull_number: ${{ github.event.issue.number }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: set commit to output
        id: getcommit
        run: | 
           prsha=$(echo $response | jq '.[-1].sha'  | tr -d '"')
           echo "::set-output name=sha::$prsha" 
        env: 
          response:  ${{ steps.get_PR_commits.outputs.data }}
          
      - uses: actions/checkout@v2
        with:
          ref: ${{steps.getcommit.outputs.sha}}  
1 Like

This works fine
Awesome Thanks!