简体   繁体   中英

Groovy code for reading a key:value from a text file

I have a config file config.txt with following key:values

a=1,2,3
b=5,6,7

I want to read the keys a nd b using groovy script but its giving following error message:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods withInputStream java.io.File groovy.lang.Closure

The code is as under:

Properties properties = new Properties()
File propertiesFile = new File('config.txt')
propertiesFile.withInputStream {
    properties.load(it)
}

def runtimeString = 'a'
assert properties."$runtimeString" == '1'
assert properties.b == '2'

What am I missing?

Pipeline DSL context runs on master node even that your write node('someAgentName') in your pipeline. new File will work only on master.

But you can read data from file via sh() . Something like:

def a = sh(returnStdout: true, script: "cat config.txt | grep a | cut -f2 -d'='").trim()
def b = sh(returnStdout: true, script: "cat config.txt | grep b | cut -f2 -d'='").trim()

I tested the following in the Groovy console and the assertions pass

new File('config.txt').withReader {
   def props = new Properties()
   props.load(it)

   assert props.getProperty('a') == '1,2,3'
   assert props.getProperty('b') == '5,6,7'
}

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