0

I have variable name URL_DEV in Gitlab Variables (Settings > CI/CD > Variables). I want to get the value using ${CI_ENVIRONMENT_NAME}. Example : echo URL_${CI_ENVIRONMENT_NAME} should provide the value from Gitlab Variables, but it is giving output as URL_DEV but not printing the value.

#Tried below commands
$ echo $URL_${CI_ENVIRONMENT_NAME}
output: DEV

$APP="URL_${CI_ENVIRONMENT_NAME}"
echo $APP
output: URL_DEV

$APP="URL_${CI_ENVIRONMENT_NAME}"
echo $(echo $APP)
output: URL_DEV

Expected Output should be value from the variables

echo $URL_${CI_ENVIRONMENT_NAME}
expected output: https://www.example.com
Sahit
  • 470
  • 6
  • 15

2 Answers2

0

You need to use bash indirect expension. This snippet works :

URL_DEV="https://google.com"
ENV="DEV"
SITE="URL_"$ENV
echo $SITE
URL_DEV

curl -k ${!SITE}

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.com/">here</A>.
</BODY></HTML>
Nicolas Pepinster
  • 5,413
  • 2
  • 30
  • 48
0

For anyone who is still looking for the answer to this question.

If there is a secret gitlab variable called something like the following COMPUTE_VAR_dev and within that variable is the contents of a secret .yml file (for instance) - (see image)

enter image description here

That variable can then be accessed within another variable, such as the following

variables:
   ENV: dev
   COMPUTE_VAR: '${COMPUTE_VAR_${ENV}}'
script:
   - echo $COMPUTE_VAR > vars.yml

The content of the variable will now be created as file named vars.yml file on the runner

One can then do something nice like the following

workflow:
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      variables:
        ENV: "prod"
    - if: $CI_COMMIT_BRANCH == "staging"
      variables:
        ENV: "stage"
    - if: $CI_COMMIT_BRANCH == "develop"
      variables:
        ENV: "dev"
    - when: always
deploy:
  variables:
    COMPUTE_VAR: '${COMPUTE_VAR_${ENV}}'
  script:
   - echo $COMPUTE_VAR > vars.yml
   - echo 'deploy something here - with the new file'

Hope it helps