Pass Environment variables from post_get_sources_script to build_script or pre_build_script

Greetings,

I have the following usecase:

  1. Fetch a secret from vault in post_get_sources_script
  2. export that secret to an env variable
  3. pass that env variable to the build_script and use it

In my case i dynamically generate tokens for artifactory and read the secret from vault.

context:

  • post_get_sources_script is executed in the helper image
  • the build_script itself is executed in the container image you define in your CI/CD job

example:

post_get_sources_script (Happens in helper image) :

if [[ "${GENERATE_ARTIFACTORY_TOKEN}" == "true" ]];
then
  echo "Generating Artifactory token."
  # Install some dependencies
  apk add --no-cache curl jq vault libcap
  setcap cap_ipc_lock= /usr/sbin/vault

  export VAULT_ADDR=https://vault.example.com
  export VAULT_AUTH_ROLE=artifactory-test

  login_response=$(curl  --request POST  --data "{\"jwt\": \"${JWT_TOKEN}\", \"role\": \"${VAULT_AUTH_ROLE}\"}" "${VAULT_ADDR}/v1/auth/jwt/login")
  token=$(echo $login_response | jq -r '.auth."client_token"')

  vault login -no-print $token

  vault write artifactory/roles/${GITLAB_USER_LOGIN} scope="applied-permissions/user" default_ttl=1h max_ttl=1h
  token_response=$(vault read -format json artifactory/token/${GITLAB_USER_LOGIN})
  export ARTIFACTORY_TOKEN=$(echo $token_response | jq -r '.data.access_token')
fi

CI JOB:

fetch-file:
  stage: build
  variables:
    GENERATE_ARTIFACTORY_TOKEN: "true"
  id_tokens:
    JWT_TOKEN:
      aud: "https://vault.example.com"
  script: |
    curl -H "Authorization: Bearer  $ARTIFACTORY_TOKEN" https://artifactory.example.com/artifactory/myrepo/thefile.json -o thefile.json
    cat thefile.json

I now want to use the exported variable ARTIFACTORY_TOKEN in the build script, but i can't.

Current Workaround

The only workaround was to do something like this in post_get_sources_script:

echo "export ARTIFACTORY_TOKEN=$(echo $token_response | jq -r '.data.access_token')" >> $CI_PROJECT_DIR/my.build.env

and in pre_build_script

if [[ "${GENERATE_ARTIFACTORY_TOKEN}" == "true" ]];
then
  source $CI_PROJECT_DIR/my.build.env
  rm $CI_PROJECT_DIR/my.build.env
fi

However, I don't like this workaround as it requires a shell and does not work for images that are built from scratch with an entrypoint pointing to a binary.

Is there any way to pass the variables generated in post_get_sources_script to the actual build container?

Edited by Julian Wachter