2017-05-22 36 views
1

什麼是確定當前OS一詹金斯管道運行方式的?如何確定當前的操作系統在詹金斯管道

語境:我建設,應該在所有平臺上運行的共享詹金斯管道腳本(在Windows,OSX和Linux)並執行一些在各個平臺不同。

我想是這樣的:

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

但是,即使它是在Windows或Mac node運行它總是進入SystemUtils.IS_OS_LINUX分支

我試過一個快速管道這樣。

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

每個節點得到正確的機器用正確的操作系統,但它們都打印## OS Linux

任何想法運行?

感謝 菲德

+0

你怎麼測試您的管道? – moritzg

回答

2

的功能,據我知道詹金斯只是Windows和UNIX,也就是說,如果在Windows之間的區別,使用蝙蝠,在unix/mac/linux上,使用sh。所以,你可以使用isUnix()more info here,以確定如果你是在UNIX或Windows和UNIX系統中使用sh和@Spencer馬龍的回答的情況下,以prope有關該系統的詳細信息(如果需要)。

+0

感謝[@Jon S](https://stackoverflow.com/users/7509826/jon-s),這是最好的答案,完美地工作。 – FedeN

0

使用Java類可能不是最好的辦法。我很肯定,除非是jenkins/groovy插件,那些在Jenkins JVM主控線程上運行的插件。我會尋找到一個殼的方法,比如一個這裏概述:https://stackoverflow.com/a/8597411/5505255

你可以換一個配件臺階該腳本來獲得標準輸出,像這樣:

def osName = sh(script: './detectOS', returnStdout: true) 

調用腳本的副本如上所述。然後只需讓該腳本返回所需的操作系統名稱,並根據osName var分支邏輯。

+1

嗨@ spencer-malone,感謝您的回覆,但這並不奏效。 'SH()'只適用於Linux和Mac,如果被稱爲Windows主機它失敗:':java.io.IOException異常:\赫德森\工作區\ UT_jenkins_pipeline:無法在目錄「C運行程序「的nohup」( -5OP3ADAIV7CDIC63NI2TISW764YRHIQ2D5YCXCVKLV2UJ32W5XNA「):CreateProces'。 – FedeN

+0

對不起,應該指定可能需要msys。 –

0

,我發現這種情況的解決方法是

try{ 
    sh(script: myScript, returnStdout: true) 
}catch(Exception ex) { 
    //assume we are on windows 
    bat(script: myScript, returnStdout: true) 
} 

使用或不使用的try/catch是使用env.NODE_LABELS多一點點優雅的解決方案。假設你已經在所有節點正確標記,你可以這樣寫

def isOnWindows(){ 
    def os = "windows" 
    def List nodeLabels = NODE_LABELS.split() 
    for (i = 0; i <nodeLabels.size(); i++) 
    { 
     if (nodeLabels[i]==os){ 
     return true 
     } 
    } 
    return false 
} 

然後

if (isOnWindows()) { 
    def osName = bat(script: command, returnStdout: true) 
} else { 
    def osName = sh(script: command, returnStdout: true) 
}