EDIT: Added support for returning the right answer also when running in agents
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 combining a check on Java system properties together testing the output of uname
in the actual executing node to determine the OS:
def getOs()
{
// Determine if I'm running in the Built-In node
def nodeName = env.NODE_NAME;
if (nodeName == null || nodeName == 'master' || nodeName == 'built-in')
{
// If so determine the OS using JDK system properties
String osname = System.getProperty('os.name');
if (osname.startsWith('Windows'))
return 'windows';
else if (osname.startsWith('Mac'))
return 'macos';
else if (osname.contains("nux"))
return 'linux';
else
throw new Exception("Unsupported os: ${osname}");
}
else
{
if (isUnix())
{
// See https://mcmap.net/q/652247/-how-to-determine-the-current-operating-system-in-a-jenkins-pipeline
// See https://mcmap.net/q/351270/-how-to-disable-command-output-in-jenkins-pipeline-build-logs
def uname = sh(script:"#!/bin/sh -e\nuname", returnStdout: true).trim();
if (uname.startsWith('Darwin'))
return 'macos';
else if (uname.contains("Linux"))
return 'linux';
else
throw new Exception("Unsupported os: ${uname}");
}
else
{
return 'windows';
}
}
}
This allowed the function to be called in any pipeline context and returning the expected result also when running in agents. Be warned that when called out of the pipeline block it will return the OS of the controller node. Note: the function must be declared in a Jenkins shared library, to bypass security restrictions. That is, save the above code in the library repository as vars/utils.groovy
and then you can use it in a pipeline as it follows:
@Library('MySharedLibrary@master') _
// The following returns the OS of the controller,
// in my case 'linux'
echo("${utils.getOs()}")
pipeline {
agent none
stages {
stage('Arch') {
parallel {
stage('MacOs') {
agent {
label 'macos'
}
steps {
script {
echo "${utils.getOs()}" // Prints 'macos'
}
}
}
stage('Windows') {
agent {
label 'Windows'
}
steps {
script {
echo "${utils.getOs()}" // Prints 'windows'
}
}
}
}
}
}
}