Home > Enterprise >  Jenkins Groovy - accessing map elements
Jenkins Groovy - accessing map elements

Time:03-31

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related