Search code examples
gitlabyamlpipelinecicd

YML syntax: How do I get the same commands to run before each stage without repeating myself in the YML file?


I've set up a .gitlab-ci.yml file as follows for my self-hosted runner.

stages:
  - set-environment
  - check-code

set-environment:
  stage: set-environment
  script:
    - C:\Users\9279\Documents\WindowsPowerShell\profile.ps1
    - conda activate temp

run_tests:
  stage: check-code
  script:
    - pytest test.py

type_checker:
  stage: check-code
  script:
    - (ls -recurse *.py).fullname | foreach-object {echo "`n$_`n";mypy --strict $_} 

I intended to use the set-environment stage to make mypy and pytest available to the subsequent check-code stage. Unfortunately, that's not how it works. GitLab destroys the shell after each stage completes.

I know this is a flaw in my understanding of how the Gitlab Runner works. How can I have the commands in set-environment run before run_tests and type_checker without repeating them in the YML file?


Solution

  • In a gitlab-ci.yaml you can define a global before_script. It would look something like this.

    stages:
      - check-code
    
    before_script:
      - C:\Users\9279\Documents\WindowsPowerShell\profile.ps1
      - conda activate temp
    
    run_tests:
      stage: check-code
      script:
        - pytest test.py
    
    type_checker:
      stage: check-code
      script:
        - (ls -recurse *.py).fullname | foreach-object {echo "`n$_`n";mypy --strict $_} 
    

    I would highly recommend you to read the gitlab-ci.yaml documentation. As there are way more nice functions like this.