Leverage Lifecycle Hooks
Sometimes it is necessary to trigger specific pipeline actions at certain times during pipeline execution. For example, if you wanted to send multiple notification types after a particular pipeline step or at the conclusion of a pipeline if the build was failure.
JTE supports this type of Aspect Oriented Programming style event handling through annotation markers that can be placed on methods defined within library steps.
The following lifecycle hook annotations are available:
Annotation | Description |
---|---|
|
Will get executed at the beginning of a pipeline run, should throw exception if this step does not have its prerequesites |
|
Will get executed at the beginning of a pipeline run, after Validate |
|
Will get executed before every pipeline step invocation |
|
Will get executed after every pipeline step invocation |
|
Will get executed at the end of a pipeline run |
|
Will get executed after every pipeline step invocation as well as at the end of the pipeline run |
Implementation
Lifecycle Hook annotations can be placed on any method inside a step.
Every step has an autowired hookContext
variable which provides steps with relevant information about what triggered the hook.
Variable | Description |
---|---|
|
The name of the Library that contributed the step associated with the hook |
|
The name of the Step associated with the hook |
|
Conditional Execution
Sometimes you’ll only want to invoke the Hook when certain conditions are met, such as a build failure or in relation to another step (like before static code analysis).
Each annotation accepts a Closure
parameter. If the return object of this closure is truthy then the hook will be executed.
While executing, the code within the Closure
parameter will be able to resolve the hookContext
variable, the library configuration of the library that loads the step via the config
variable, and the currentBuild
variable made available in Jenkins Pipelines.
Example Syntax:
@BeforeStep({ hookContext.step.equals("build") })
void call(){
// execute something right before the library step called build is executed.
}
The closure parameter is optional. If omitted, the hook will always be executed. |