Skip to main content

How do I use the before_script and after_script sections in a pipeline as code?

The before_script and after_script sections in a pipeline as code allow you to define commands or scripts that will be executed before and after each job in your pipeline, respectively. These sections provide a convenient way to set up any necessary environment, dependencies, or cleanup tasks that are required for your jobs.

Here's how you can use the before_script and after_script sections in your pipeline as code:

before_script: The before_script section allows you to define a set of commands or scripts that will be executed before each job in your pipeline. These commands are useful for setting up the environment, installing dependencies, or configuring any prerequisites for your jobs. For example, you can use this section to install specific software, set environment variables, or configure authentication.

before_script:
- echo "Setting up environment"
- apt-get install -y software-package
- export ENV_VAR=value

Generic

after_script: The after_script section allows you to define commands or scripts that will be executed after each job in your pipeline. These commands are useful for performing cleanup tasks, generating reports, or collecting artifacts from your jobs. For example, you can use this section to archive log files, generate test reports, or clean up temporary resources.

after_script:
- echo "Performing cleanup tasks"
- tar -czvf logs.tar.gz logs/
- rm -rf temp/

Generic

By using the before_script and after_script sections, you can define reusable setup and cleanup tasks that are automatically executed before and after each job in your pipeline. This helps ensure consistent and efficient execution of your pipeline while reducing duplication of code or commands across multiple jobs.

Remember that the commands or scripts defined in these sections are executed for every job in your pipeline, so it's important to consider the scope and purpose of the commands to avoid unnecessary overhead or duplication.