Search code examples
dockergitlabdockerfilegitlab-ci

Docker, Gitlab: How can I print ${CI_COMMIT_SHA} on my website?


I want to display the value of Gitlab's variable CI_COMMIT_SHA on my website to know which website version is displayed at the moment.

To do this, I have this HTML snippet on my website:

<p>Hashcode2: current_hash_code2</p>

In my Dockerfile I want to replace current_hash_code2 with the value of CI_COMMIT_SHA with

RUN sed -i "s/current_hash_code2/${CI_COMMIT_SHA}/g" ./src/components/WelcomeMessage.vue

However, this is not working; I can only see this:

enter image description here

To get some more information I ran some tests.

Website:

<p>Hashcode1: current_hash_code1</p>
<p>Hashcode2: current_hash_code2</p>
<p>original text</p>

Dockerfile:

RUN sed -i "s/original text/new text/g" ./src/components/WelcomeMessage.vue

ARG myvalue=15.8
RUN echo $myvalue
RUN sed -i "s/current_hash_code1/${myvalue}/g" ./src/components/WelcomeMessage.vue

RUN echo $CI_COMMIT_SHA
RUN sed -i "s/current_hash_code2/${CI_COMMIT_SHA}/g" ./src/components/WelcomeMessage.vue

Logging of Gitlab:

#11 [ 7/12] RUN sed -i "s/original text/new text/g" ./src/components/WelcomeMessage.vue
#11 DONE 0.4s
#12 [ 8/12] RUN echo 15.8
#12 0.496 15.8
#12 DONE 0.5s
#13 [ 9/12] RUN sed -i "s/current_hash_code1/15.8/g" ./src/components/WelcomeMessage.vue
#13 DONE 0.5s
#14 [10/12] RUN echo $CI_COMMIT_SHA
#14 0.396 
#14 DONE 0.5s
#15 [11/12] RUN sed -i "s/current_hash_code2/${CI_COMMIT_SHA}/g" ./src/components/WelcomeMessage.vue
#15 DONE 0.4s

Website output:

enter image description here

As you can see, I am able to replace data via the Dockerfile, even when using variables. However, I cannot get the value of $CI_COMMIT_SHA to the website.

Do you know why?


Solution

  • Then variable CI_COMMIT_SHA is empty inside your Dockerfile, which means it might not have been valued during the docker build

    You would need:

    docker build --build-arg CI_COMMIT_SHA=${CI_COMMIT_SHA}
    

    And your Dockerfile should start with (after the FROM)

    ARG CI_COMMIT_SHA
    ENV CI_COMMIT_SHA $CI_COMMIT_SHA