Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the current operating system in a Jenkins pipeline

What would be the way to determine the current OS a Jenkins pipeline is running?

Context: I'm building a shared Jenkins pipeline script that should run on all platforms (windows, OSX, linux) and execute something different in each platform.

I tried something like:

import org.apache.commons.lang.SystemUtils

if (SystemUtils.IS_OS_WINDOWS){
   bat("Command")
}
if (SystemUtils.IS_OS_MAC){
   sh("Command")
}
if (SystemUtils.IS_OS_LINUX){
   sh("Command")
}

But even it is running on windows or mac node it always goes into the SystemUtils.IS_OS_LINUX branch

I tried a quick pipeline like this.

node('windows ') {
     println ('## OS ' + System.properties['os.name'])
}
node('osx ') {
     println ('## OS ' + System.properties['os.name'])
}
node('linux') {
     println ('## OS ' + System.properties['os.name'])
}

Each node get correctly run in a machine with the correct OS but all of them print ## OS Linux

any ideas?

Thanks Fede

like image 435
FedeN Avatar asked May 22 '17 06:05

FedeN


People also ask

What OS is Jenkins?

Jenkins requires Java 11 Since its inception, the Jenkins project has been a major consumer of Java, distributing over 1,800 plugins to an installed base of over 300,000...

How can I see Jenkins pipeline configuration?

Click New Item on your Jenkins home page, enter a name for your (pipeline) job, select Pipeline, and click OK. In the Script text area of the configuration screen, enter your pipeline syntax.

Which Jenkins variable is used to discover information about the currently executing pipeline?

currentBuild. May be used to discover information about the currently executing Pipeline, with properties such as currentBuild.


1 Answers

Assuming you have Windows as your only non-unix platform, you can use the pipeline function isUnix() and uname to check on which Unix OS you're on:

def checkOs(){
    if (isUnix()) {
        def uname = sh script: 'uname', returnStdout: true
        if (uname.startsWith("Darwin")) {
            return "Macos"
        }
        // Optionally add 'else if' for other Unix OS  
        else {
            return "Linux"
        }
    }
    else {
        return "Windows"
    }
}
like image 127
fedterzi Avatar answered Sep 21 '22 16:09

fedterzi