What I wish I knew about Jenkinsfiles
November 18, 2018
Every now and then I find myself in the situation where I want to set up a Declarative Jenkins Pipeline for a new application. Usually I have access to plenty of other repositories and thus the opportunity to check out their Jenkinsfile, which is a great source of inspiration. However, sometimes the pipeline I need can’t simply be copy-pasted from bits and pieces of other pipelines I know.
Normally this is when I start my journey on the bumpy road of trial and error, but recently I finally managed to level up my Jenkins Pipeline development tooling.
The Jenkins Pipeline Linter
Obviously when getting into the situation where you don’t know how to achieve your goal, just copy-pasting stuff and going down the trial and error road indefinitely is neither efficient nor educational. Instead you take the time to educate yourself further and read the documentation, right?
Well, when you do so for Jenkins Pipeline Development Tools you might be more knowledgable, because you just found out that you can validate a Jenkinsfile upfront instead of just pushing the next change and crossing your fingers. And yet, you might be no step closer to improve on how you write and verify your pipeline. Reason being the fact that the two options described in the documentation have some prerequisites and chances are your Jenkins instance does not fulfil them. You either have the SSH service enabled on your Jenkins server for command line access or “anonymous read access” has been enabled on your Jenkins instance, since the documentation suggests that this is what you need to perform linting via HTTP POST using curl. Turns out the latter is not actually the case.
If you can log in to Jenkins, you can use curl to let your Jenkins instance validate your Jenkinsfile, regardless of your server allowing “anonymous read access”!
At the risk of stating the obvious: You can just use the documented curl command and add -u <your_username>
as parameter. The command could look something like this:
curl -X POST -u <your_username> \-F "jenkinsfile=<Jenkinsfile" \$JENKINS_URL/pipeline-model-converter/validate
I myself needed a friend to point this out to me.
Lint before wasting your Jenkin’s time
Now there are no excuses left, Not even that the curl command might be hard to remember! Just add it as a bash function, if you like:
function jenkins-validate() {curl -X POST -u <your*username> -F "jenkinsfile=<$1" $JENKINS_URL/pipeline-model-converter/validate;}
Now validating your Jenkinsfile is as easy as this:
$ jenkins-validate Jenkinsfile
This way you finally have the confidence that your Jenkinsfile is at least syntactically correct before pushing a change to your repository to trigger the pipeline!