Linting Jenkinsfiles to find syntax errors


As a long time Jenkins user I periodically need to add new steps or Groovy logic to my Jenkinsfiles. The last thing you want to do when updating your pipeline configuration is to make a typo which causes a build to break. To avoid these scenarios, I like to use a git pre-commit hook along with the Jenkins CLI “declarative-linter” option. To use this super useful feature to check for syntax errors, you will first need to download the Jenkins CLI client. You can do this with wget:

$ wget -O jenkins-cli.jar https://JENKINS_SERVER:JENKINS_PORT/jnlpJars/jenkins-cli.jar

One the Java archive is installed, you can use the following syntax to check if a Jenkinsfile is structurally sound:

$ export API_TOKEN="RANDOM_FOO"

$ java -jar jenkins-cli.jar -auth ${LIMITED_PERM_USER}:${API_TOKEN} -s http://JENKINS_SERVER:JENKINS_PORT declarative-linter < Jenkinsfile

Dec 19, 2019 9:33:30 AM org.apache.sshd.common.util.security.AbstractSecurityProviderRegistrar getOrCreateProvider
INFO: getOrCreateProvider(EdDSA) created instance of net.i2p.crypto.eddsa.EdDSASecurityProvider
Jenkinsfile successfully validated.

$ echo $?

0

If the file looks good you will get a return code of 0 and the string “Jenkinsfile successfully validated” will be printed on the console. If you fat fingered something (e.g., left out a parentheis or semicolon), you will get a return code of 1 and the string “Errors encountered validating Jenkinsfile:” will be printed:

$ java -jar jenkins-cli.jar -auth ${LIMITED_PERM_USER}:${API_TOKEN} -s http://JENKINS_SERVER:JENKINS_PORT declarative-linter < Jenkinsfile

Dec 19, 2019 9:33:40 AM org.apache.sshd.common.util.security.AbstractSecurityProviderRegistrar getOrCreateProvider
INFO: getOrCreateProvider(EdDSA) created instance of net.i2p.crypto.eddsa.EdDSASecurityProvider
Errors encountered validating Jenkinsfile:
WorkflowScript: 39: unexpected token: } @ line 39, column 1.
   }
   ^

$ echo $?

1

In the case of an error, the linter will give you a breadcrumb to help you track down the issue. One important item to remember is that this checks the structure of the Jenksinfiles passed to STDIN. It won’t pick up logic errors in your Groovy code or the incorrect use of steps in your stages. But as a first line of defense it works pretty well. It also ensures you won’t be “the guy” that gets asked about TPS reports when your co-workers joke about the build being broken at the water cooler.

This article was posted by on 2019-12-18 21:47:16 -0500 -0500