Jorge V
Jorge V

Reputation: 21

How to get the logs from previous build in Jenkins pipeline?

In my Jenkins Pipeline, the first stage executes a freestyle job. Therefore, I need to get the output/logs from that job because it will return a string of IPs which will be used on my second stage.

def getEc2ListResult = []
pipeline {
    agent {
        label 'master'
    }

stages{
    stage('Get EC2 List'){
        steps {
            script {
                def getEc2List = build job: 'get-ec2-by-tag', parameters: [
                    string(name: 'envTagValue', value: "${envTagValue}"),
                    string(name: 'OS', value: "${OS}")
                ]
                getEc2ListResult = getEc2List.getPreviousBuild().getLog(20)
            }
        }
    }
}
}

This is the error that I'm getting:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper.getLog() is applicable for argument types: (java.lang.Integer) values: [20]
Possible solutions: getId(), getAt(java.lang.String), getClass()

Upvotes: 1

Views: 2711

Answers (1)

yong
yong

Reputation: 13712

getEc2List is of type RunWrapper, also getEc2List.getPreviousBuild().

RunWrapper doesn't supply a getLog() api, it is supplied by rawBuild.

you can get getEc2List's rowBuild by call getEc2List.rawBuild or getEc2List.getRawBuild().

But getRawBuild() is not in @Whitelisted of RunWrapper, so you will get following message in jenkins log:

Scripts not permitted to use method org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper getRawBuild. Administrators can decide whether to approve or reject this signature.

One option, it's to ask Jenkins admin to change Script Approve

Another option, it's do as following:

stage('') {

    environment {
      JENKINS_AUTH = credentials('<credentail id of jenkins auth>')
      // add an credentail with a jenkins user:password before use it at here
    }

    steps {
        script {
            def getEc2List = build job: 'get-ec2-by-tag', parameters: [
                string(name: 'envTagValue', value: "${envTagValue}"),
                string(name: 'OS', value: "${OS}")
            ]
            logUrl = getEc2List.absoluteUrl + 'consoleText'

            log = sh(script: 'curl -u {JENKINS_AUTH} -k' + logUrl, 
                     returnStdout: true).trim()

            // parse the log to extract the ip
            ...
        }
    }

}

Upvotes: 3

Related Questions