Fix the 'expected a step' Jenkins error

‘Expected a step on’ error in Jenkins

The ‘expected a step’ error in Jenkins can be triggered in a number of different ways.

But the most common cause, which should be ruled out first for anyone who uses a declarative pipeline is the presence of a code block that is not contained within a script element.

Jenkins expected a step error

A declarative pipeline’s ‘expected a step’ error in Jenkins.

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:

  1. Open the Jenkins  pipeline source code in an editor
  2. Surround all code snippets in a script { } block
  3. Save your changes
  4. Re-run the Jenkins pipeline

To fix the ‘expected a step’ Jenkins error, put any coded logic inside a script block.

In previous versions of Jenkins, the script block was not a requirement, 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 be coding logic within a declarative pipeline. The best place to put logic is within a Jenkins shared library which can be then referenced through a tag in your pipeline. It keeps your pipelines, cleaner, the code becomes reusable, and you 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.