Home > Enterprise >  Gitlab CI: can I use variable in another variable name?
Gitlab CI: can I use variable in another variable name?

Time:07-25

I know I can use variables in variables, for example:

script:
  - SOME_VAR=text_${VAR1}

but how can I use variable IN the name of a new variable?

script:
  - VAR1=TEXT1
  - SOME_NEW_VAR_${VAR1}=some_text

It doesn't work this way:

SOME_NEW_VAR_TEXT1=some_text: command not found

Looks like Gitlab create text correctly, but can't get I want to create it as new variable.

Is it possible in some way? I use template to create specific variables in different jobs and want to recognise which variable from which job.


Full example:

.template: &template
  image: $common/specificImage:latest
  stage: build
  script: 
    - echo "Startin process..."
    - SOME_VAR_${PROJECT_NAME}=$( ls )

first-job:
  variables:
    PROJECT_NAME: ProjectA
  <<: *template

second-job:
  variables:
    PROJECT_NAME: ProjectB
  <<: *template

ERROR:

/scripts-123-456/step_script: line 192: SOME_VAR_ProjectA=sometext: command not found

CodePudding user response:

You can use indirect/reference variables, for example1:

first-job:
  image: ubuntu:22.04
  script:
    - VAR1="TEXT1"
    - declare SOME_NEW_VAR_${VAR1}="some_text"
    - varname=SOME_NEW_VAR_${VAR1}
    - echo $varname
    - echo "${!varname}"

output:

$ echo $varname
SOME_NEW_VAR_TEXT1
$ echo "${!varname}"
some_text

example 2:

.template: &template
  image: ubuntu:22.04
  script:
    - VAR1=$PROJECT_NAME
    - VAR2=`ls`
    - declare "SOME_NEW_VAR_${VAR1}=$VAR2"
    - varname=SOME_NEW_VAR_${VAR1}
    - echo $varname
    - echo "${!varname}"

first-job:
  variables:
    PROJECT_NAME: ProjectA
  <<: *template

second-job:
  variables:
    PROJECT_NAME: ProjectB
  <<: *template

reference:

  • Related