简体   繁体   English

Jenkins Groovy - 访问 map 元素

[英]Jenkins Groovy - accessing map elements

I am trying to create docker-compose yaml file with Groovy:我正在尝试使用 Groovy 创建 docker-compose yaml 文件:

 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我正在尝试向卷添加一些值: depTemplate.services."${serviceName}".volumes.add("some volume")但它失败并显示错误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.然后尝试添加新卷: depTemplate.services.application.volumes.add("some volume") - 它工作得很好。 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:此外,当我尝试通过索引从模板获取值时:print depTemplate.services[0] - 它返回null ,但是当我尝试通过名称获取元素时:print depTemplate.services['application'] - 它返回有效值:

{hostname=some-hostname, environment="some-environment-variables", ports="some-ports, volumes="some-volumes" restart=} {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?所以问题是如何使用变量访问 map 元素以及如何通过 id 访问 map 元素?

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.所以现在我可以通过索引访问元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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