I have a scripts repo, which have few scripts among which I have a build.sh file that I want to run when GitLab CI runs. Can I simply add that to my GitLab CI file under scripts section? Which I am assuming it will run the script file.
Is there a way I can add and pass variables from my GitLab CI file/environment to the hello.sh file?
My project:
rootdir
- folder1
- scripts
- hello.sh
hello.sh
:
#!/usr/bin/env bash
echo "Hello World!"
GitLab CI:
image: docker:latest
stages:
- build
build:
stage: build
script:
- ./scripts/hello.sh
3
Answers
Yes, both are possible. To use your
hello.sh
script in GitLab CI and pass variables directly from your.gitlab-ci.yml
, just define your variables under thevariables
section(below I included a GREETING variable as an example). Then, when you run your script, those variables will automatically be available to it.First make sure your
hello.sh
script is executable. You can achieve that by runningchmod +x ./scripts/hello.sh
locally, in the root of your repo. Or you can also have this as the first command to run under your Gitlab CI file’s script section, before running your script.Then modify your
.gitlab-ci.yml
to include the variables and run your script like this:For your question on whether you can access the variable in your
hello.sh
, you can access theGREETING
variable using$GREETING
:Try passing your variables (for ex: VARIABLE_AAA, VARIABLE_BBB) as arguments to the
Bash
script:.gitlab-ci.yml
hello.sh
Output
More details in: arguments in bash script
You can assign values to your variables in the CI/CD settings (see screenshot below). Then you can use those variables in your
.gitlab-ci.yml
like this:I prefer this approach because it means that the environment variable values are not hard-coded into a file and are easy changed via the GitLab UI.