How to determine the current operating system in a Jenkins pipeline

Viewed 22440

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

5 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"
    }
}

I initially used @fedterzi answer but I found it problematic because it caused the following crash:

org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.Launcher is missing

when attempting to call isUnix() outside of a pipeline (for example assigning a variable). I solved by relying on traditional Java methods to determine Os:

def getOs(){
    String osname = System.getProperty('os.name');
    if (osname.startsWith('Windows'))
        return 'windows';
    else if (osname.startsWith('Mac'))
        return 'macosx';
    else if (osname.contains('nux'))
        return 'linux';
    else
        throw new Exception("Unsupported os: ${osname}");
}

This allowed to call the function in any pipeline context.

Related