Jir
Jir

Reputation: 3145

How do I correctly expand variables in .gitlab-ci.yml?

In my .gitlab-ci.yml file I try and set a variable containing a timestamp in the before_script section. I would then like to expand that variable and append it to the archive I'm creating for my build. The file goes roughly like this:

#.gitlab-ci.yml

image: node:14.4.0-buster

before_script:
  - export DATETIME=$(date "+%Y%m%d%H%M%S")

stages:
  #- test  # not relevant for this question
  - build
  - deploy

build:
  stage: build
  script:
    - npm install
    - npm run build
    - ls -la build
    - tar cvfJ build_${DATETIME}.tar.xz build/
    - sha1sum build_${DATETIME}.tar.xz
  artifacts:
    paths:
    - build_${DATETIME}.tar.xz

deploy:
  image: node:14.4.0-buster
  stage: deploy
  script:
    - sha1sum build_${DATETIME}.tar.xz
    - tar xvfJ build_${DATETIME}.tar.xz
    # do the actual deploy
  only:
  - master

The deploy stage fails at sha1sum. The output is:

$ sha1sum build_${DATETIME}.tar.xz
sha1sum: build_20200702165854.tar.xz: No such file or directory

This shows that the expansion is done correctly, yet something is wrong.

What am I missing?

Upvotes: 1

Views: 3202

Answers (1)

Rekovni
Rekovni

Reputation: 7374

The before_script is run at the start of each job, and so the export DATETIME=$(date "+%Y%m%d%H%M%S") would be different for both stages.

It would probably be better to use ${CI_COMMIT_SHORT_SHA} instead for example.

Upvotes: 2

Related Questions