Search code examples
gitdockergithub-actionsdocker-builddocker-tag

Need a way to build container image only if commit message contains specific text


I have made a github repo for a assignment. The basic requirement is that

  1. I have to create a new repo
  2. Build a Docker Image from it
  3. And push that Docker Image to the Docker Hub on my account in a public repo using Github Actions.
  4. I want to build the container image only if the commit message contains certain text like Ex: "build image"

I have been succesful in creating the image and also am able to push it to Docker Hub.

I want to set 4th condition to my repo. I found this guide but it is for Gitlab and I don't know anything about it

Post Link :Link to Post

This is the code of the file and it works fine.

name: Docker Image CI

on:
  push:
    branches: [ "master" ]
  pull_request:
    branches: [ "master" ]

jobs:

  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    - name: Docker Login
      env:
        DOCKER_USER: ${{secrets.DOCKER_USERNAME}}
        DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}}
      run:
        docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
    - name: Build the Docker image
      run: docker build . --file Dockerfile --tag ${{secrets.DOCKER_USERNAME}}/assignment:latest
    
    - name: Puch Image to Docker Hub
      run: docker push ${{secrets.DOCKER_USERNAME}}/assignment

I don't have advanced knowledge of Docker. So how can I achieve this?


Solution

  • Add following condition if: "contains(github.event.head_commit.message, 'build image')" to your .github/workflows, e.g.:

    name: Docker Image CI
    
    on:
      push:
        branches: [ "master" ]
      pull_request:
        branches: [ "master" ]
    
    jobs:
    
      build:
    
        runs-on: ubuntu-latest
        if: "contains(github.event.head_commit.message, 'build image')"
    
        steps:
        - uses: actions/checkout@v3
        - name: Docker Login
          env:
            DOCKER_USER: ${{secrets.DOCKER_USERNAME}}
            DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}}
          run:
            docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
        - name: Build the Docker image
          run: docker build . --file Dockerfile --tag ${{secrets.DOCKER_USERNAME}}/assignment:latest
        
        - name: Puch Image to Docker Hub
          run: docker push ${{secrets.DOCKER_USERNAME}}/assignment