skip to Main Content

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


  1. 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 the variables 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 running chmod +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:

    image: docker:latest
    
    stages:
      - build
      
    variables:
      GREETING: "Welcome to GitLab CI/CD!"
    
    build:
      stage: build
      script:
        - ./scripts/hello.sh
    

    For your question on whether you can access the variable in your hello.sh, you can access the GREETING variable using $GREETING:

    #!/usr/bin/env bash
    echo "Hello World! $GREETING"
    
    Login or Signup to reply.
  2. Try passing your variables (for ex: VARIABLE_AAA, VARIABLE_BBB) as arguments to the Bash script:

    .gitlab-ci.yml

    image: docker:latest
    
    stages:
     - build
    
    build:
     stage: build
     script:
      - chmod +x ./scripts/hello.sh
      - ./scripts/hello.sh "VARIABLE_AAA" "VARIABLE_BBBB"
    

    hello.sh

    #!/usr/bin/env bash
    VAR_A=$1
    VAR_B=$2
    echo $VAR_A
    echo $VAR_B
    

    Output

    More details in: arguments in bash script

    Login or Signup to reply.
  3. 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:

    image: docker:latest
    
    stages:
      - build
      
    variables:
      SMTP_USERNAME: ${SMTP_USERNAME}
      SMTP_PASSWORD: ${SMTP_PASSWORD}
    
    build:
      stage: build
      script:
        - ./email.sh
    

    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.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search