DEV Community

Discussion on: GitLab CI: Creating your own pipeline template library 👷

Collapse
 
gregorip02 profile image
Gregori Piñeres

Hi, thanks for sharing!

What if I want to re-use a series of scripts in my jobs? I know you could write separate scripts to files e.g. scripts/deploy.sh and call its execution whenever you need it in the .gitlab-ci.yml file.

The extends: .my-reusable-job sentence could be overwritten.

# .gitlab-ci.yml

.my-reusable-job:
  script:
    - echo "Hello from .my-reusable-job"

testing:
  extends: .my-reusable-job
  script:
    - echo "Hello from testing job"
Enter fullscreen mode Exit fullscreen mode

Only prints "Hello from testing job". My specific question is if I can use extends without overwriting it later?

Collapse
 
anhtm profile image
Minh Trinh • Edited

Hi Gregori! Thanks for posting your question :)

I think this is an intended feature for extends. If you want the reusable script to not be overwritten, there's 2 ways I can think of:

  1. Use before_script or after_script for reusable commands so that they're appended before or after the new script:
.my-reusable-job:
  before_script:
    - echo "First, hello world"

testing:
  extends: .my-reusable-job
  script:
    - echo "Second, hello world, again!"
Enter fullscreen mode Exit fullscreen mode

This thus prints "First, hello world" and "Second, hello world, again!"

  1. Use YAML anchors to specify reusable scripts:
# &my_reusable_commands is the name of the anchor
.my_reusable_commands: &my_reusable_commands
  - echo 'First, hello world'

testing:
  script:
   # refer to the above anchor with *<anchor_name>
    - *my_reusable_commands
    - echo "Second, hello world, again!"
Enter fullscreen mode Exit fullscreen mode

This will print the same 2 lines just like the first approach.

Let me know if you have any questions!

Collapse
 
gregorip02 profile image
Gregori Piñeres

Thankssssss, it works 🙏🏾🙏🏾🙏🏾🙏🏾

Thread Thread
 
anhtm profile image
Minh Trinh

Awesome! 🎉 I'm happy to help :)