Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins - Is there a way to parse console output and set environment variable

Tags:

jenkins

I am relatively new to Jenkins. I am into a scenario where I need to read the console output and find a specific string and set this as environment variable. This variable I would be using in some downstream jobs.

for example: my jenkins job's console would contain something like

product_build_number: 123456

I have looked into FindText, log parser like plugins but they don't help me in setting this value as environment variable

Can somebody help in finding this number and pass it to downstream jobs?

**

Updated with Answer:

**

def matcher = manager.getLogMatcher(".*product_build_number=(\\d+.*)")
if(matcher.matches()) {
    pbn= matcher.group(1).substring(0)
    manager.build.setDescription(pbn) // you can do anything with this here
}
like image 907
abdulH Avatar asked Oct 30 '22 06:10

abdulH


1 Answers

Consider using Groovy Postbuild Plugin.

Example:

The script below puts a warning badge and mark the build as unstable if it detects that deprecated methods were used.

if(manager.logContains(".*uses or overrides a deprecated API.*")) {
    manager.addWarningBadge("Thou shalt not use deprecated methods.")
    manager.createSummary("warning.gif").appendText("<h1>You have been warned!</h1>", false, false, false, "red")
    manager.buildUnstable()
}

Solution

Complete solutions uses not only Groovy Postbuild Plugin to parse console output and to set variable BUILD_MSG, but also needs Parameterized Trigger Plugin to trigger downstream job with predefined parameter MSG=${BUILD_MSG}. Downstream job automatically has access to MSG parameter.

Groovy Postbuild script:

import hudson.model.*


matcher = manager.getLogMatcher('^build msg: (.*)$')

if (matcher.matches()) {
    buildMsg=matcher.group(1)

    manager.build.addAction(
        new ParametersAction([
            new StringParameterValue("BUILD_MSG", "${buildMsg}")
        ])
    )
}
like image 138
luka5z Avatar answered Nov 08 '22 05:11

luka5z