14

Actually I have a need to get a timestamp of my commit in GitLab CI. Alredy have tested the official documentation of GitLab CI Variables here: https://docs.gitlab.com/ee/ci/variables

But there are only commit variables for

  • CI_COMMIT_SHA The commit revision for which project is built
  • CI_COMMIT_TAG The commit tag name. Present only when building tags.

Is there a way to achieve this? Need to add these values to variables. My prefered way would be to add it to the variables section.

job:
  variables:
    COMMIT_TIME: $(git_timestamp)
  script: echo $COMMIT_TIME

I'm open to any helpful suggestions.

Jan Franta
  • 1,691
  • 2
  • 16
  • 25

3 Answers3

32

Yes you can get the commit time, like this:

job:
  script: 
    - export COMMIT_TIME=$(git show -s --format=%ct $CI_COMMIT_SHA)
    - echo $COMMIT_TIME

If you want to have your COMMIT_TIME variable in every job use the before_script option:

before_script:
  - export COMMIT_TIME=$(git show -s --format=%ct $CI_COMMIT_SHA)   

job:
  script: 
    - echo $COMMIT_TIME

The %ct format gives you unixtimestamp if you want something else, have a look at the PRETTY_FORMATS in this reference on git show.

Stefan van Gastel
  • 4,330
  • 23
  • 25
  • Thanks, will test it. – Jan Franta Mar 08 '18 at 13:40
  • Doesn't using the `before_script` method mean that each job calculates its own date/time? This could be an issue if the date is important and the pipeline spans midnight. Oh of course it doesn't because you're looking at the commit. Nice! – Paul D Smith Jun 18 '19 at 14:44
  • This saved me a lot of headache. For those that build a container from here and are looking to access the `COMMIT_TIME` variable from inside the container you'll want to use the `before_script:` option as mentioned above before the start of any stage. Then add `COMMIT_TIME: $COMMIT_TIME` to `variables:` (also before the start of any stage). You will now have access to this variable globally in your container. – Mix Master Mike Aug 17 '19 at 03:33
21

From GitLab 13.4 you can use a new predefined variable for this: CI_COMMIT_TIMESTAMP

Example of value: 2022-01-06T01:27:22+01:00

Ulf Lindback
  • 13,974
  • 3
  • 40
  • 31
SVL
  • 211
  • 2
  • 2
  • 5
    Here is an example of value for this variable (so that anyone looking for the date format does not need to run a pipeline to get it): `2022-01-06T01:27:22+01:00` – CDuv Jan 06 '22 at 00:55
0

For powershell use $Env:variable_name=value

job:
  script: 
    - $Env:COMMIT_TIME=$(git show -s --format=%ct $CI_COMMIT_SHA)
    - WRITE-HOST $Env:COMMIT_TIME

Reference: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_environment_variables?view=powershell-7.3

Huber Thomas
  • 1,577
  • 1
  • 5
  • 7