Sid Anand
Sid Anand

Reputation: 237

Share script between .gitlab-ci.yml jobs

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

Upvotes: 9

Views: 6739

Answers (3)

Corina
Corina

Reputation: 1545

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.

Upvotes: 11

ihebiheb
ihebiheb

Reputation: 5173

While YML Anchors works, the recommended way now is to use Extends

You can reduce complexity and duplicated configuration in your GitLab CI/CD configuration files by using:

YAML-specific features like anchors (&), aliases (*), and map merging(<<).

The extends keyword, which is more flexible and readable. We recommend you use extends where possible.

Your pipeline will be :

.common:
  before_script:
    - command_A
    - command_B

job1:
  extends:
    - .common
  script:
    - command_C

job2:
  extends:
    - .common
  script:
    - command_D

Upvotes: 5

s510
s510

Reputation: 2812

The above answer by Corina is logically correct but technically wrong. I have put the correct script here. Please refer this link.

# 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

Upvotes: 5

Related Questions