Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share script between .gitlab-ci.yml jobs

Tags:

gitlab-ci

Have a look at the snippet below. I want to find a way to reduce duplicate code by placing command_A and command_B at a location where job1 and job2 both run it

job1:
  script:
    - command_A
    - command_B
    - command_C

job2:
  script: 
    - command_A
    - command_B
    - command_D
like image 716
Sid Anand Avatar asked Apr 17 '26 02:04

Sid Anand


1 Answers

In your case, probably the easiest would be to use YML Anchors.

Anchors are YML's way of reusing code - you can think of them a little bit like functions.

You can define a block of configuration somewhere and create a reference to it using &. Then, you can use it with *.

# Create an anchor called `&common`
.common: &common
  - command_A
  - command_B

job1:
  script:
   # Merge the anchor into the `script` using `<<*:`
    - *common
    - command_C

job2:
  script: 
    - *common
    - command_D

To learn more, I found this article to be helpful, and of course, the official Gitlab docs on anchors.

Alternatively, you could simply put all common code in a before_script tag or use .extends keyword - you can see some examples on my blog.

like image 88
Corina Avatar answered Apr 28 '26 12:04

Corina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!