Override / set default variable value

I have a basic template to run .NET tests which I include in many other projects.

Till now I was able to define the image globally e.g.

image: mcr.microsoft.com/dotnet/core/sdk:latest

include:
  - project: tel/ci_templates
    file: dotNET-test.gitlab-ci.yml

But this is starting to get more challenging with complex multi-job pipelines.

What I would like to do is set a default in dotNET-test.gitlab-ci.yml but be able to override in the calling pipelines. e.g something like:

image: $DOTNET_IMAGE || mcr.microsoft.com/dotnet/core/sdk:latest

What might be the best way to achieve this?

It looks like I could use rules, something like:

test:
rules:
  - if: $DOTNET_IMAGE_OVERRIDE == ""
    variables:
      $DOTNET_IMAGE: mcr.microsoft.com/dotnet/core/sdk:latest
  - if $DOTNET_IMAGE_OVERRIDE != ""
    variables:
      $DOTNET_IMAGE: $DOTNET_IMAGE_OVERRIDE
image: $DOTNET_IMAGE
script...

But I suspect there’s a simpler solution? :slight_smile:

Thanks!

Hi @leetickett

Site note: using image on top level is deprecated and shouldn’t be used. There is a new default keyword for that.

dotNET-test.gitlab-ci.yml:

default:
  image: my_image1

job1:
....

.gitlab-ci.yml in project:

include:
  - project: tel/ci_templates
    file: dotNET-test.gitlab-ci.yml

default:
  image: my_image2

# override per job
job1:
  image: my_image3

Thanks for the headsup @balonik

For anyone interested, this is what we’ve ended up with for now:

test:
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"
      when: never
    - if: $DOTNET_IMAGE_OVERRIDE != null
      variables:
        DOTNET_IMAGE: $DOTNET_IMAGE_OVERRIDE
    - when: always
      variables:
        DOTNET_IMAGE: mcr.microsoft.com/dotnet/core/sdk:latest
  image: $DOTNET_IMAGE
  script:
    - dotnet test -v=normal Tests/Tests.csproj /p:CollectCoverage=true --logger:"junit;LogFilePath=test-result.xml" --collect:"XPlat Code Coverage"
  coverage: '/Average\s*\|.*\|\s(\d+\.?\d*)%\s*\|.*\|/'
  artifacts:
    when: always
    reports:
      junit: ./Tests/test-result.xml
      coverage_report:
        coverage_format: cobertura
        path: ./Tests/TestResults/**/coverage.cobertura.xml

This will:

  • Not run the test job for scheduled pipelines
  • Use the custom image if defined by $DOTNET_IMAGE_OVERRIDE
  • Fallback and use the Microsoft Artifact Registry image in any other scenario