I'm setting up CI with Gitlab and it's working good except I need to use a variable in a script command and I'm not sure how I can do that. I was thinking something like this
script:
- npm config set "//npm.fontawesome.com/:_authToken" $FONT_AWESOME_KEY
I've tried a few other routes but I can't seem to get the variable value to get populated in the command I want to run.
Can you share where your variable comes from?
You have a number of ways to get variables into your CI scripts:
variables section in your CI file.This allows you to create global variables, available to all jobs in the pipeline.
stages:
- build
variables:
GLOBAL_VARIABLE_1: some value
my job:
stage: build
script:
- echo $GLOBAL_VARIABLE_1
This can be used in scripts as an environment variable $GLOBAL_VARIABLE_1.
Similar to above but with the job as scope.
stages:
- build
my job:
stage: build
variables:
JOB_VARIABLE_1: some value
script:
- echo $JOB_VARIABLE_1
You can also create variables direct in the script section. This might be obvious to some, but worth mentioning:
stages:
- build
my job:
stage: build
script:
- export SCRIPT_VARIABLE_1="some value"
- echo $SCRIPT_VARIABLE_1
You can define variables in the project Settings > CI/CD section of the GitLab UI. Scroll down to Secret variables section and you will be able to define a "key" (variable name) and "value" (variable value). These variables will be available within the CI jobs.
If you check the protected box then the variable won't be defined in pipelines running on non-protected branches. Protected variables would commonly be used for things like API keys that are sensitive (you don't want them in your CI file visible to everyone), and you may need to change them occasionally
Included for completeness
This isn't natively supported, but can be achieved using artifacts. Note that since jobs within the same stage could run in parallel it only makes sense to pass variables from jobs in one stage to jobs in a downstream stage.
stages:
- build
- test
build job:
stage: build
script:
- export BUILD_JOB_VAR=123
- echo "$BUILD_JOB_VAR" > build_job_var.txt
artifacts:
paths:
- build_job_var.txt
expire_in: 2 days
test_job:
stage: test
script:
- export BUILD_JOB_VAR="$(cat build_job_var.txt)"
- echo $BUILD_JOB_VAR
When you use variables in scripts GitLab won't show the resolved commands as they run (you will only see the original command). To aide in debugging it can help to echo commands before they are run so that you can see the fully resolved command. In your example you could try echoing the npm command (note you may need to quote the command, and escape quotes to echo the exact command):
script:
- echo "npm config set \"//npm.fontawesome.com/:_authToken\" $FONT_AWESOME_KEY"
- npm config set "//npm.fontawesome.com/:_authToken" $FONT_AWESOME_KEY
You may find that the variable is being populated correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With