简体   繁体   中英

Jenkins Groovy Pipeline Get (Windows)User Folder Per Node

I have a distributed Jenkins build and the user under which the jenkins process runs on the slaves is not necessarily static, so I need a mechanism to get the user per node.

I am trying something like

#!/usr/bin/env groovy

class TestSettings {
    public static String NuGetPackagesPath = "${env.USERPROFILE}\\.nuget\\packages"
}

node("master"){
    println env.USERPROFILE // works as expected
    println TestSettings.NuGetPackagesPath // throws exception
}

node("build"){
    println env.USERPROFILE // works as expected
    println TestSettings.NuGetPackagesPath // throws exception
}

env doesn't work in the static property, because the property is already initialized before you enter the node closure. So env just isn't available yet.

I see two ways around this:

  • Turn the property into a function and pass the env variable as parameter.
  • Make it a non-static function and pass env to the class constructor.

I would propably go with the latter as it will be easier to use when you have many test settings.

class TestSettings {
    public static String getNuGetPackagesPath( def env ) { "${env.USERPROFILE}\\.nuget\\packages" }
}

class TestSettings2 {
    def env = null
    
    TestSettings2( def env ) {
        this.env = env
    }
    
    public String getNuGetPackagesPath() { "${env.USERPROFILE}\\.nuget\\packages" }
}


node("master"){
    println env.USERPROFILE
    
    println TestSettings.getNuGetPackagesPath( env )
    
    def testSettings = new TestSettings2( env )
    // Note that we can use the method like a property!
    println testSettings.nuGetPackagesPath
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM