How do I optimise common code from stages in gitlabci file?

Viewed 31

I am trying to optimise below gitlabci file

stages:
  - lint
  - publish

lint:example1
  stage: lint
  script:
    - command1
    - command2
    - command3
    - command4

publish:docker-image
  stage: publish
  script:
    - command1 # same command from lint stage
    - command2 # same command from lint stage
    - command3 # same command from lint stage
    - command5

Now, how do I carve out common part from both stages so that my ci file look cleaner? Is there anything like functions in gitlab-ci.yml?

1 Answers

You can use YAML anchors with script, before_script, and after_script to use predefined commands in multiple jobs:

.some-script-before: &some-script-before
  - echo "Execute this script first"

.some-script: &some-script
  - echo "Execute this script second"
  - echo "Execute this script too"

.some-script-after: &some-script-after
  - echo "Execute this script last"

job1:
  before_script:
    - *some-script-before
  script:
    - *some-script
    - echo "Execute something, for this job only"
  after_script:
    - *some-script-after

job2:
  script:
    - *some-script-before
    - *some-script
    - echo "Execute something else, for this job only"
    - *some-script-after

For more info check docs

Related