简体   繁体   中英

Jenkins Groovy - accessing map elements

I am trying to create docker-compose yaml file with Groovy:

 def depTemplate = [ version: "3.9", services:[ "${serviceName}":[ hostname: "some-hostname", environment: [], ports: [], volumes: [], restart: '' ] ] ]

I am trying to add some values to volumes: depTemplate.services."${serviceName}".volumes.add("some volume") but it fails with error Cannot get property 'volumes' on null object

Otherwise, if i declare template in following way:

 def depTemplate = [ version: "3.9", services:[ application:[ hostname: "some-hostname", environment: [], ports: [], volumes: [], restart: '' ] ] ]

and then trying to add new volume: depTemplate.services.application.volumes.add("some volume") - it works perfectly. Also when i am trying to get value from template by index: print depTemplate.services[0] - it returns null , but when i am trying to get element by name: print depTemplate.services['application'] - it returns valid value:

{hostname=some-hostname, environment="some-environment-variables", ports="some-ports, volumes="some-volumes" restart=}

So the question is how can i access map element by using variables and how can i access map elements by id?

def depTemplate = [
   version: "3.9", 
   services:[
      (serviceName):[
         hostname: "some-hostname",
         environment: [],
         ports: [],
         volumes: [],
         restart: ''
      ]
   ]
]
depTemplate.service[serviceName].volume.add("asdf")

So i found my mistake - i missed another square brackets after services:

def depTemplate = [
   version: "3.9", 
   services:[
      [(serviceName):[
         hostname: "some-hostname",
         environment: [],
         ports: [],
         volumes: [],
         restart: ''
      ]]
   ]
]
depTemplate.service[0].volume.add("asdf")

So now i am able to access elements by index.

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