Rules for includes behave differently if defined in .gitlab-ci.yml directly vs. in a included template

Rules for includes behave differently if defined in .gitlab-ci.yml directly vs. in a included template

I am applying rules to select which ci-templates to include. I see a different behavior if I define the rules in the .gitlab-ci.yml directly vs. in an included template.

For example in a project named ci-import-example, available at https://gitlab.com/cadami-public/ci-import-example/ I use the following .gitlab-ci.yml

include:
  - remote: 'https://gitlab.com/cadami-public/ci-import-example/-/raw/main/job_A.yml'
    rules:
    - if: $CI_PROJECT_NAME == "ci-import-example"
      when: always
  - remote: 'https://gitlab.com/cadami-public/ci-import-example/-/raw/main/job_B.yml'
    rules:
    - if: $CI_PROJECT_NAME != "ci-import-example"
      when: always

direct_job_A:
  stage: build
  script:
    - env | sort
  rules:
    - if: $CI_PROJECT_NAME == "ci-import-example"
      when: always

direct_job_B:
  stage: build
  script:
    - env | sort
  rules:
    - if: $CI_PROJECT_NAME != "ci-import-example"
      when: always

with job_A.yml as

imported_job_A:
  stage: .post
  script:
    - env | sort

and job_B.yml as

imported_job_B:
  stage: .post
  script:
    - env | sort

As expected, direct_job_A and imported_job_A are scheduled.

If I move the .gitlab-ci.yml to template-gitlab-ci.yml and include the template, such that .gitlab-ci.yml now is

include:
  - remote: 'https://gitlab.com/cadami-public/ci-import-example/-/raw/import-ci-file/template-gitlab-ci.yml'

then direct_job_A and imported_job_B are scheduled. I did expect that again direct_job_A and imported_job_A would be scheduled.

I have verified that the variable I am using can be used with include Use CI/CD configuration from other files | GitLab

I am running this on gitlab.com and the example I provided is a public repository. The initial configuration is on the main branch with this pipeline.

The configuration with the template on the import-ci-file branch with this pipeline.

Hi @andreasdotzler

this is actually expected behavior and documented here in “Additional details” section All nested includes are executed without context as a public user, so you can only include public projects or templates. No variables are available in the include section of nested includes.

@balonik thank you so much for pointing me to the correct documentation. This also gives me a solution. In my case, I can use a local or project include to get the desired behavior.