0

I have such Gitlab CI/CD pipeline:

.template: &template
  image: ubuntu
  stage: pre
  script:
    - echo "Startin process..."
    - echo $PROJECT_NAME
    - VAR1=$( ls )
    - echo "LIST_${PROJECT_NAME}=${VAR1}" >> pre.env
  artifacts:
    reports:
      dotenv: pre.env # Export variables to other stages

job1:
  variables:
    PROJECT_NAME: ProjectA
  <<: *template

job2:
  variables:
    PROJECT_NAME: ProjectB
  <<: *template

###########################################

.final-template: &final-template
  image: ubuntu
  stage: finish
  script:
    - echo "Run final jobs"
    - echo $LIST_ProjectA  # works
    - echo $LIST_ProjectB  # works 
    - echo $LIST_${PROJECT_NAME}  # doesn't work
    - VAR1=$LIST_${PROJECT_NAME}  # doesn't work
    - echo $VAR1  # contains just 'ProjectA' for final-job1 and 'ProjectB' for final-job2
    # code using VAR1 value
  tags: [ k8s,mn-bw-krun01 ]

final-job1:
  variables:
    PROJECT_NAME: ProjectA
  <<: *final-template
  needs: [ "job1" ]

final-job2:
  variables:
    PROJECT_NAME: ProjectB
  <<: *final-template
  needs: [ "job2" ]

So I saved env variables in job1 and job2. I can print them in next stages if use whole name:

- echo $LIST_ProjectB  # works

But I want to use them dynamically - using another variable $PROJECT_NAME:

echo $LIST_${PROJECT_NAME}  # doesn't work

I tried all possible (as I suppose) combinations of (),{} and $ and never can get the result - always empty value or just value of PROJECT_NAME.

How to correctly use variable in variable for such case?

Mikhail_Sam
  • 10,602
  • 11
  • 66
  • 102

1 Answers1

0

I found the answer (thanks to this answer)

Save variable:

stage: pre
  script:
    - echo "Startin process..."
    - echo $PROJECT_NAME
    - VAR1=$( ls )
    - echo "LIST_${PROJECT_NAME}=${VAR1}" >> pre.env
artifacts:
  reports:
    dotenv: pre.env # Export variables to other stages

Use variable:

stage: finish
  # remember - we define PROJECT_NAME here in variables! 
  # I skipped it in example because of using anchors
  script:
    - echo "Run final jobs"
    - VAR_TMP=LIST_${PROJECT_NAME} # create tmp var
    - echo $VAR_TMP # this prints correct the NAME of variable
    - echo ${!VAR_TMP} # this prints correct VALUE of that variable
Mikhail_Sam
  • 10,602
  • 11
  • 66
  • 102