In GitLab CI/CD, the .gitlab-ci.yml
file orchestrates the pipeline's activities. One of its core functionalities is to trigger scripts that facilitate automated processes such as testing, building, deploying, among others. This section delves into various methods to run scripts within this file.
Directly embed scripts within the .gitlab-ci.yml
file for straightforward tasks.
- Simplicity: Best for simple actions without separate files.
- Visibility: Direct visibility of script actions in the CI configuration.
- Clutter: Longer scripts can make
.gitlab-ci.yml
hard to read. - Reusability: In-line scripts are less reusable across jobs or projects.
build_job:
script:
- echo "Compiling the source code..."
- gcc -o output_file source_file.c
- echo "Compilation completed."
- Ideal for succinct scripts.
- Document each script step for clarity.
Write scripts in separate files for complex operations, then reference them in .gitlab-ci.yml
.
- Organization: Keeps CI configuration clean and manageable.
- Reusability: Facilitates script use across different scenarios.
- Separation: Script logic is detached from the CI configuration.
Create deploy_script.sh
and reference it in .gitlab-ci.yml
:
deploy_job:
script:
- chmod +x ./deploy_script.sh
- ./deploy_script.sh
- Store scripts in the repository or a script repository.
- Ensure script executability (
chmod +x
). - Use descriptive script file names.
For advanced scenarios, source external scripts and call specific functions within your CI pipeline.
- Flexibility: Execute only required script parts as needed.
- Modularity: Maintain organizational clarity by using functions.
- Complexity: Demands a solid grasp of scripting and CI mechanics.
Define functions in script_library.sh
and invoke them in .gitlab-ci.yml
:
#!/bin/bash
function deploy_to_production {
echo "Deploying to production server..."
# Deployment commands here
}
function rollback {
echo "Rolling back deployment..."
# Rollback commands here
}
production_deploy_job:
script:
- source script_library.sh
- deploy_to_production
rollback_job:
script:
- source script_library.sh
- rollback
- Utilize descriptive function names.
- Document each function's purpose in the script.
- Test scripts locally before CI/CD integration.