Consice, Reusable and Refactored Definitions
31%
Reusable Configuration Sections Using the "extends" Keyword
Sometimes you may find yourself repeating the same configuration in multiple jobs. This is an example:
stages:
- test
test1:
stage: test
image: alpine:latest
before_script:
- echo "Setting up the environment..."
script:
- echo "Running tests for test1..."
after_script:
- echo "Cleaning up..."
test2:
stage: test
image: alpine:latest
before_script:
- echo "Setting up the environment..."
script:
- echo "Running tests for test2..."
after_script:
- echo "Cleaning up..."
ℹ️ The keyword
before_scriptis used to define a script that runs before each job in the pipeline. The keywordafter_scriptis used to define a script that runs after each job in the pipeline.
As you can see, test1 and test2 are almost identical since they share the same configuration. Using the extends keyword, you can define a base configuration that can be reused across multiple jobs. Here is how we can refactor the pipeline:
stages:
- test
.base_test:
stage: test
image: alpine:latest
before_script:
- echo "Setting up the environment..."
after_script:
- echo "Cleaning up..."
test1:
extends: .base_test
script:
- echo "Running tests for test1..."
test2:
extends: .base_test
script:
- echo "Running tests for test2..."
We can also combine the extends keyword with the include keyword. This is an example:
Step 1: Create the file base_test.yml:
cat <$HOME/todo/app/.includes/base_test.yml
# base_test.yml
.base_test:
stage: test
image: alpine:latest
before_script:
- echo "Setting up the environment..."
after_script:
- echo "Cleaning up..."
EOF
Cloud Native CI/CD with GitLab
From Commit to Production ReadyEnroll now to unlock all content and receive all future updates for free.
