Home > Back-end >  How to implement semantic versioning of Docker images in GitHub Actions workflow?
How to implement semantic versioning of Docker images in GitHub Actions workflow?

Time:03-31

I would like to achieve the following CI pipeline with GitHub Actions workflow.

Pull Request is merged -> GitHub action is being triggered -> docker image is being built with semantic version incremented by one or the version is based on GitHub tag - if it is possible to somehow tag the pull request merge.

How to achieve that or is the better approach?

I have tried with secrets but no to avail. How to implement semantic versioning in GitHub Actions workflow?

CodePudding user response:

name: Docker Image CI

on:
  push:
    branches: [ master ]

jobs:

  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    - name: Build the Docker image
      run: docker build . --file Dockerfile --tag my-image-name:${{github.ref_name}}

${{github.ref_name}} pulls the tag for you or run git command like git describe --abbrev=0 in the previous step to get the latest tag and append it to image name and use it like:

- name: Get Tag
  id: vars
  run: echo ::set-output name=tag::${git describe --abbrev=0}
- name: Build the Docker image
  run: docker build . --file Dockerfile --tag my-image-name:${{ steps.vars.outputs.tag }}

CodePudding user response:

You can use a lot of semver actions on the market place. For example, I have tried using this - Semver action

This will bump your repo version, and you can use a git bash command to get that bumped version on the next job.

So combining with docker build, you can do something like:

jobs:
  update-semver:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: haya14busa/action-update-semver@v1
        id: version
        with:
          major_version_tag_only: true  # (optional, default is "false")
  Build:
    name: Build Image
    needs: [update-semver]
    runs-on: ubuntu-latest
    steps:
    - name: Check out code
      uses: actions/checkout@v2
    - name: Build image
      run: |
        tag_v=$(git describe --tags $(git rev-list --tags --max-count=1))
        tag=$(echo $tag_v | sed 's/v//')
        docker build -t my_image_${tag} .
        
  • Related