Solutions Delivery Platform

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:

Table 1. JTE LifeCycle Hook annotations
Annotation Description

@Validate

Will get executed at the beginning of a pipeline run, should throw exception if this step does not have its prerequesites

@Init

Will get executed at the beginning of a pipeline run, after Validate

@BeforeStep

Will get executed before every pipeline step invocation

@AfterStep

Will get executed after every pipeline step invocation

@CleanUp

Will get executed at the end of a pipeline run

@Notify

Will get executed after every pipeline step invocation as well as at the end of the pipeline run

Lifecycle Hook Flow Diagram

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.

Table 2. JTE LifeCycle Hooks hookContext Variable
Variable Description

hookContext.library

The name of the Library that contributed the step associated with the hook

hookContext.step

The name of the Step associated with the hook

hookContext.library and hookContext.step will be null before and after pipeline execution due to the fact that the hook is not in response to a particular pipeline step.

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.