GitLab CI: Export variable in before_script build job
Asked Answered
E

3

11

I try to implement a conditional versioning depending on if the CI script runs for a tagged branch or not. However the version var is not resolved. Instead it is printed as a string.

The relevant jobs of the GitLab CI script:

# build template
.build_base_template: &build_base_template
  image: registry.gitlab.com/xxxxxxx/npm:latest
  tags:
    - docker
  stage: LintBuildTest
  script:
    - export CUR_VERSION='$(cat ./version.txt)$BUILD_VERSION_SUFFIX'
    - npm ci
    - npm run build
  artifacts:
    expire_in: 1 week
    paths:
      - dist/

# default build job
build:
  before_script:
    - export BUILD_VERSION_SUFFIX='-$CI_COMMIT_REF_SLUG-SNAPSHOT-$CI_COMMIT_SHORT_SHA'
  <<: *build_base_template
  except:
    refs:
      - tags
  only:
    variables:
      - $FEATURE_NAME == null

# specific build job for tagged versions
build_tag:
  before_script:
    - export BUILD_VERSION_SUFFIX=''
  <<: *build_base_template
  only:
    refs:
      - tags
Eberle answered 8/7, 2019 at 8:41 Comment(1)
My colleague was able to resolve the problem. I would like to provide the solution to everybody: Calling the build_base_template needs to be called first (above the line of before_scriptEberle
T
5

in general you can't export variables from child to parent processes.

As workaround you can use text file to write/read variable value. Also maybe it's possible to pass variable via yaml template.

Tague answered 8/7, 2019 at 12:8 Comment(0)
C
16

Variables which are exported within before_script are visible within script.

before:
  before_script:
    - export HELLOWELT="hi martin"
  script:
    - echo $HELLOWELT  # prints "hi martin"
Commodore answered 13/5, 2021 at 10:1 Comment(2)
But not in after_scriptMallina
You actually don't need an export in this example because „Scripts you specify in before_script are concatenated with any scripts you specify in the main script. The combined scripts execute together in a single shell.Welcher
T
5

in general you can't export variables from child to parent processes.

As workaround you can use text file to write/read variable value. Also maybe it's possible to pass variable via yaml template.

Tague answered 8/7, 2019 at 12:8 Comment(0)
M
0

GitLab Runner internal variable expansion mechanism

Not supported: variables defined inside of custom scripts (for example, export MY_VARIABLE="test").

So, you have 3 (three) options:

  1. project/group variables
  2. .gitlab-ci.yml variables
  3. config.toml variables
Maintopmast answered 29/3, 2023 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.