Environments and variables

The documentation for environments in the .gitlab-ci.yml specifically calls out the following:

CI/CD variables, including predefined, project, group, instance, or variables defined in the .gitlab-ci.yml file. You can’t use variables defined in a script section.

What does "You can’t use variables defined in a script section` precisely mean? For example, given the sample, edited for demonstration:

.deploy-scripts: &deploy-scripts |
    export prod="production"
    echo $prod

deploy:production:
  stage: deploy
  script:
    - *deploy-scripts
    - git push $prod HEAD:main
  environment: production

Is this not supported? Seems unlikely. I’ll play with it of course, but the documentation could be misleading to a reader. The example could be more explicit I think.

Hey Timothy,

The page you’re on describes YAML key specification. Hence, sentence

You can’t use variables defined in a script section.

refers to using variables as values in environment key in the YAML file. (not in the scripts) (later in docs about environment:name and environment:url as well, bcos environment is just shortcut for environment:name)

So, your example should work because it uses the variable in script section. But, e.g. this won’t:

deploy to prod:
  stage: deploy
  script:
    - export prod="production"
  environment: $prod

But, if you define a CI/CD variable, e.g. PROD_URL and do:

deploy to prod:
  stage: deploy
  script:
    - echo "deploying"
  environment:
    name: production
    url: $PROD_URL

will work :wink:

Hopes this makes it more clear :slight_smile:

1 Like

Thanks! I was pretty close to that understanding, but wanted the clarity of an example.

1 Like