0

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

1 Answer 1

3

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:

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank you for response! While I'm trying to figure it out, maybe you can check my another question about gitlab?
@Mikhail_Sam I am updating my example; add example 2 for your GitLab question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.