Search code examples
bashgitlabcontinuous-integrationgitlab-cipipeline

Gitlab CI: save command in variable


I need to run big command in several jobs and save results in dynamically created variables. My idea - save such command as variable and evaluate it in script sections of all jobs. For example:

.grep_command: &grep_command
  GREP_COMMAND: dotnet ef migrations list | grep "VERY_LONG_PATTERN_HERE"

job1:
  variables:
    <<: *grep_command
  script:
    # some job specific code
    - echo $GREP_COMMAND
    - VAR=$(${GREP_COMMAND}) # doesn't work


job2:
  variables:
    <<: *grep_command
  script:
    # some job specific code
    - echo $GREP_COMMAND
    - echo "VAR=$(${GREP_COMMAND})" > build.env # also doesn't work

Solution

  • I found the right way: define command as script command and use it in script section, not variables:

    .grep-command: &grep-command
      - dotnet ef migrations list | grep "VERY_LONG_PATTERN_HERE"
    
    job1:
      script:
        # some job specific code
        - *grep-command
    

    (By the way saving command as variable also works, just use it carefully, but I suppose it is not so clear - variables must stay variables, and commands - as commands. I find it bad practice to mix them)