Fix the 'expected a step' Jenkins error
‘Expected a step on’ error in Jenkins
The ‘expected a step’ error in Jenkins is triggered in numerous different ways.
The most common cause is the presence of a code block that is not contained within a script element. Rule this out first if you use a declarative pipeline
How to fix ‘expected a step’ Jenkins errors
If you have coded logic inside a declarative pipeline, and the pipeline now throws the ‘expected a step’ Jenkins error, follow these steps to fix it:
- Open the Jenkins pipeline source code in an editor
- Surround all code snippets in a script { } block
- Save your changes
- Re-run the Jenkins pipeline
Old versions of Jenkins did not require the script block, which is why declarative pipelines that once worked are now failing. Fortunately, the fix is relatively easy.
Jenkins best practices
The fact is, you really shouldn’t code logic within a declarative pipeline. The best place to put logic is within a Jenkins shared library, and then reference that library through a tag in your pipeline. This keeps your pipelines cleaner, the code becomes reusable, and your logic is easier to test.
So while you’re fixing the ‘expected a step’ Jenkins error, you might want to rethink the way your pipelines are coded, and refactor them in a way that embraces Jenkins best practices.