How to use Gitlab Branches and Tags as Version inside Docker

By |2018-12-06T22:35:11+00:0011/2018|Categories: Entwicklungen|Tags: , , , , , |0 Comments

One charming way of versioning a software is to use the GitLab CI/CD and deploy with Tags. Feature Branches will be merged in Development and a version is then merged to Master. These versions may then be tagged with a version number.

If the App will be deployed with Docker, a nice feature would be to have the actual build version number or tag as a variable inside this container to show in the app (e.g. that a customer or partner can see which version is running).

There might be other solutions, but we found the following very handy.

Get version in GitLab CI

GitLab CI process has variables, which can be used within the continuous integration process. We use these variables and store a version number to a file, called .version

# we are inside the .gitlab-ci.yml in a stage
script:
     - echo "$CI_COMMIT_REF_NAME BUILD ${CI_COMMIT_SHA:0:8}" > .version

Now we can build our container and push it to the registry.

Deploy the Container to a Registry

We are using the Gitlab Registry, so the .gitlab-ci.yml looks like this:

stages:
    - build

variables:
    CONTAINER_IMAGE: registry.gitlab.com/mechlabengineering/cartox:$CI_COMMIT_REF_NAME

Build CartoX Docker:
    stage: build
    image: docker:git
    services:
        - docker:dind
    before_script:
        - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY
    script:
        - cd Docker
        
        # Save Version to file (will be read by api.py)
        - echo "$CI_COMMIT_REF_NAME BUILD ${CI_COMMIT_SHA:0:8}" > .version
        
        - docker build -t $CONTAINER_IMAGE .
        - docker push $CONTAINER_IMAGE

# Done

Use the version in an app inside the Docker

Inside the deployed container, we have a .version file, with the latest branch or tag name and the shortened commit SHA. To use it in an app (for example a python app), one can simply read the file like

# Get Version
with open('.version') as versionfile:
    version = versionfile.read().strip()

Now we can use this in our application, e.g.

# Instantiate the Flask App and API
app = Flask("CartoX API App")
api = Api(app,
          version=version,
          default='cartox',
          default_label='namespace',
          title='CartoX API',
          description='A RESTful API to predict vehicle connectivity',
          contact='BMVI Forschungsprojekt CartoX',
          contact_url='https://www.bmvi.de/SharedDocs/DE/Artikel/DG/mfund-projekte/serviceplattform-c2c-kommunikation-cartox2.html')
Python Application using versioning from GitLab CI

Python Application using versioning from GitLab CI

Leave A Comment