How to fix Pipeline-Script “Expected a step” error

戏子无情 提交于 2019-12-11 04:27:18

问题


I am trying to run a simple pipeline-script in jenkins with 2 stages. The Script itself creates a textFile and checks if this one exists. But when i try to run the job i get an "Expected a step" error.

the ('Write') stage seems to work perfectly fine so its something with the ('Check') stage.

I have read somewhere that you cant have an if inside a step so that might be the or one problem but if so how can i check without using the if?

pipeline {
    agent {label 'Test'}
    stages {
        stage('Write') {
            steps {
                writeFile file: 'NewFile.txt', text: 
                '''Sample HEADLINE
                This is the secondary HEADLINE ...
                In this third Line below the HEADLINE we will write some larger Text, to give the HEADLINE some Context lets see how that ends up looking. HEADLINE ... HEADLINE ... This should be long enough ...'''
                println "New File created..."
            }
        }
        stage('Check') {
            steps {        
                Boolean bool = fileExists 'NewFile.txt'
                if(bool) {
                    println "The File exists :)"
                }
                else {
                    println "The File does not exist :("
                }            
            }
        }
    }
}

I expect the script to create a "NewFile" in the agents workspace and print a text to the console confirming that it exists.

But i actually get two "Expected a step" error. At the Line starting with Boolean bool = ... and at if(bool) ...


回答1:


You are missing a script block. Quote (Source):

The script step takes a block of Scripted Pipeline and executes that in the Declarative Pipeline.

    stage('Check') {
        steps {        
            script {
                Boolean bool = fileExists 'NewFile.txt'
                if(bool) {
                    println "The File exists :)"
                }
                else {
                    println "The File does not exist :("
                }   
            }         
        }
    }

Basically in the script block you can use everything you want. Groovy, if, try-catch etc. etc.



来源:https://stackoverflow.com/questions/55508871/how-to-fix-pipeline-script-expected-a-step-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!