Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jenkins pipeline if condition not working

I have a Jenkins pipeline that uses an if statement to check if a docker container is running. I run the following command to get the running state:

def containerStatus = sh(script: "ssh -o StrictHostKeyChecking=no -l <user> <server> 'docker container inspect -f '{{.State.Status}}' ${tagName}'", returnStdout: true)

I have added

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

echo containerStatus

and in the Jenkins console the output for this is "running"

However, when I have the following in the pipeline:

if(containerStatus.toString() == 'running'){
    echo 'Initial status: Container running'
    ...some code...
}

this condition is not executed (I hit my defined error condition). I have also tried removing the .toString(), but no luck.

The complete stage in the pipeline is:

stage("Container") {
    steps {
        script{
            def containerStatus = sh(script: "ssh -o StrictHostKeyChecking=no -l <user> <server> 'docker container inspect -f '{{.State.Status}}' ${tagName}'", returnStdout: true)
            echo containerStatus
            
            if(containerStatus.toString() == 'running'){
                echo 'Initial status: Container running'
                ...some code...
            }
            else {
                error "Container not running"
            }           
        }
    }
}

>Solution :

You need to trim the resulted output:

def containerStatus = sh(script: "ssh -o StrictHostKeyChecking=no -l <user> <server> 'docker container inspect -f '{{.State.Status}}' ${tagName}'", returnStdout: true).trim()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading