Here is some documentation on the Jenkins pipeline linter and its commands. Do you need to validate before a commit? If not, it would be really trivial to run the linting command prior to your pipeline running, and simply fail if it does not pass.
From Command-line Pipeline Linter:
Jenkins can validate, or "lint", a Declarative Pipeline from the
command line before actually running it. This can be done using a
Jenkins CLI command or by making an HTTP POST request with appropriate
parameters. We recommended using the SSH interface to run the
linter. See the Jenkins CLI documentation for details on how to
properly configure Jenkins for secure command-line access.
Linting via the CLI with SSH
# ssh (Jenkins CLI)
# JENKINS_SSHD_PORT=[sshd port on master]
# JENKINS_HOSTNAME=[Jenkins master hostname]
ssh -p $JENKINS_SSHD_PORT $JENKINS_HOSTNAME declarative-linter < Jenkinsfile
Linting via HTTP POST using curl
# curl (REST API)
# Assuming "anonymous read access" has been enabled on your Jenkins instance.
# JENKINS_URL=[root URL of Jenkins master]
# JENKINS_CRUMB is needed if your Jenkins master has CRSF protection enabled as it should
JENKINS_CRUMB=`curl "$JENKINS_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)"`
curl -X POST -H $JENKINS_CRUMB -F "jenkinsfile=<Jenkinsfile" $JENKINS_URL/pipeline-model-converter/validate
Examples
Below are two examples of the Pipeline Linter in action. This first
example shows the output of the linter when it is passed an invalid
Jenkinsfile
, one that is missing part of the agent
declaration.
Jenkinsfile
pipeline {
agent
stages {
stage ('Initialize') {
steps {
echo 'Placeholder.'
}
}
}
}
Linter output for invalid Jenkinsfile
# pass a Jenkinsfile that does not contain an "agent" section
ssh -p 8675 localhost declarative-linter < ./Jenkinsfile
Errors encountered validating Jenkinsfile:
WorkflowScript: 2: Not a valid section definition: "agent". Some extra configuration is required. @ line 2, column 3.
agent
^
WorkflowScript: 1: Missing required section "agent" @ line 1, column 1.
pipeline }
^
In this second example, the Jenkinsfile
has been updated to include
the missing any
on agent
. The linter now reports that the Pipeline
is valid.
Jenkinsfile
pipeline {
agent any
stages {
stage ('Initialize') {
steps {
echo 'Placeholder.'
}
}
}
}
Linter output for valid Jenkinsfile
ssh -p 8675 localhost declarative-linter < ./Jenkinsfile
Jenkinsfile successfully validated.