Alexander Knyazev
Alexander Knyazev

Reputation: 2892

How to set up env variables in gitlab-ci.yaml?

My gitlab ci-cd config file uses many env variables. To set them, I use gitlab ci-cd secret variables.

For example, dev deploy-part:

- echo "====== Deploy to dev server ======"
# Add target server`s secret key
- apk add git openssh bash
- mkdir ~/.ssh
- echo $DEV_SERVER_SECRET_KEY_BASE_64 | base64 -d > ~/.ssh/id_rsa
- chmod 700 ~/.ssh && chmod 600 ~/.ssh/*
- echo "Test ssh connection for"
- echo "$DEV_SERVER_USER@$DEV_SERVER_HOST"
- ssh -o StrictHostKeyChecking=no -T "$DEV_SERVER_USER@$DEV_SERVER_HOST"
# Delploy
- echo "Setup target server directories"
- TARGET_SERVER_HOST=$DEV_SERVER_HOST TARGET_SERVER_USER=$DEV_SERVER_USER TARGET_SERVER_APP_FOLDER=$DEV_SERVER_APP_FOLDER pm2 deploy pm2.config.js dev setup 2>&1 || true
- echo "make deploy"
- TARGET_SERVER_HOST=$DEV_SERVER_HOST TARGET_SERVER_USER=$DEV_SERVER_USER TARGET_SERVER_APP_FOLDER=$DEV_SERVER_APP_FOLDER pm2 deploy pm2.config.js dev

I have 5 repositories in project and 3 servers (dev, preprod, prod). So I must manage many variables. Manage all them using gitlab ci-cd secret variables it's very hurt. I can't see it, change it - only delete and create. I agree to use it for secret ssh keys, but it's not suitable for specifying the names of folders, hosts, etc.

Is there some other way to provide variables to ci-cd script?

Upvotes: 5

Views: 5358

Answers (1)

Stephen L.
Stephen L.

Reputation: 21

You can define custom variables in quite a few ways:

I. using GUI:

II. using .gitlab-ci.yml file:

You can use the variables keyword in a job or at the top level of the .gitlab-ci.yml file. If the variable is at the top level, it’s globally available and all jobs can use it. If it’s defined in a job, only that job can use it.

variables:
  TEST_VAR: "All jobs can use this variable's value"

job1:
  variables:
    TEST_VAR_JOB: "Only job1 can use this variable's value"
  script:
    - echo "$TEST_VAR" and "$TEST_VAR_JOB"

Make sure to store only non-sensitive variables in your .gitlab-ci.yaml file

Check the official documentation for more information and examples.

Upvotes: 2

Related Questions