6

I'm using GitLab pipelines and have defined my build defintion in the .gitlab-ci.yml file.

I'm using this to build docker containers.

Simple question. Is there a way I can tag my docker containers with either a semver from gitlab or a timestamp.

The build-in variables don't seem to give me much to work with.

On Windows I've been able to use GitVersion before in powershell that gets the semver tag and puts it into a variable you can use in the rest of the build process.

If I can't do that, is it possible to get a timestamp from the OS and use that in the yml file?

Remotec
  • 10,304
  • 25
  • 105
  • 147

2 Answers2

14

You can use the timestamp in your .gitlab-ci.yml like this (taken from our own usage creating <year>.<month> tags and releases:

job-1:
 script:
   - export VERSION=$(date +%y.%m)
   - docker build -t myregistry/project/image:$VERSION

This results in a image tag like: myregistry/project/image:17.10

You can use date +%s instead of date +%y.%m for unixtimestamp.

Depending on your (git)flow you can also use branch-slugs provided by Gitlab CI env vars

Stefan van Gastel
  • 4,330
  • 23
  • 25
6

Regarding timestamp, another approach is to use existing variables associated to your current pipeline.

See GitLab 13.10 (March 2021)

Predefined CI/CD variables for job start and pipeline created timestamps

Previously, if you wanted to reference the exact date and time when a job started or a pipeline was created, you needed to retrieve these timestamps in your scripts. Now they are readily available as predefined CI/CD variables by using CI_JOB_STARTED_AT and CI_PIPELINE_CREATED_AT, provided in the ISO 8601 format and UTC time zone.

Thanks to @Winkies for this contribution!

See Documentation and Issue.

Unfortunately this variable can't be used directly as an image tag. As seen in the referenced implementation issue, the output of this variable is similar to 2021-03-18T04:45:29Z. Used directly, your image would look something like myimage:2021-03-18T04:45:29Z which is invalid.


smileek adds in the comments:

You can perform simple string operations on variables.
E.g., ${CI_PIPELINE_CREATED_AT:0:10} will give you the first ten symbols: 2021-03-18 out of 2021-03-18T04:45:29Z.

You can see more at "Extract substring in Bash".

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • You can perform simple string operations on variables. E.g., `${CI_PIPELINE_CREATED_AT:0:10}` will give you the first ten symbols: `2021-03-18` out of `2021-03-18T04:45:29Z` – Smileek Aug 07 '23 at 15:27
  • 1
    @Smileek Thank you for the feedback. This is indeed bash substring operations, and I have edited the answer to include your comment for more visibility, as well as added a link for documenting those bash variable operations. – VonC Aug 07 '23 at 19:49