28

I'm currently working on a deployment script to run as part of my GitLab CI setup. What I want is to copy a file from one location to another and rename it.

Now I want to be able to find what commit that file was generated with, so I'd like to add the hash of the commit to it.

For that to work I'd like to use something like this:

cp myLogFile.log /var/log/gitlab-runs/$COMMITHASH.log

The output should be a file named eg.

/var/log/gitlab-runs/9b43adf.log

How is this possible to achieve using GitLab CI?

ndequeker
  • 7,932
  • 7
  • 61
  • 93
Daniël van den Berg
  • 2,197
  • 1
  • 20
  • 45

3 Answers3

53

In your example you used the short git hash that you would get with the predefined variable CI_COMMIT_SHA by building a substring like this:

${CI_COMMIT_SHA:0:8}

or by using the short sha directly

$CI_COMMIT_SHORT_SHA
Yash Kumar Verma
  • 9,427
  • 2
  • 17
  • 28
VivaceVivo
  • 831
  • 7
  • 8
  • 8
    Gitlab 11.7 added `CI_COMMIT_SHORT_SHA` for this. See https://docs.gitlab.com/ee/ci/variables/predefined_variables.html – David Gardner Oct 11 '19 at 15:39
  • 2
    Look like `CI_COMMIT_SHORT_SHA` spit out an 8 character long hash. Whereas `git rev-parse --short` give an 7 character long one. – maclir Mar 02 '20 at 15:27
31

The variable you are looking for is CI_COMMIT_SHA (formerly CI_BUILD_REF in GitLab 8.x and earlier) which one of the predefined variables.

All predefined variables are listed here.

Zim
  • 410
  • 4
  • 13
Fairy
  • 3,592
  • 2
  • 27
  • 36
19

Since GitLab v11.7 you can use $CI_COMMIT_SHORT_SHA which returns the first eight characters of CI_COMMIT_SHA.

ndequeker
  • 7,932
  • 7
  • 61
  • 93