簡體   English   中英

Jenkins Groovy - 訪問 map 元素

[英]Jenkins Groovy - accessing map elements

我正在嘗試使用 Groovy 創建 docker-compose yaml 文件:

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

我正在嘗試向卷添加一些值: depTemplate.services."${serviceName}".volumes.add("some volume")但它失敗並顯示錯誤Cannot get property 'volumes on null object

否則,如果我以下列方式聲明模板:

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

然后嘗試添加新卷: depTemplate.services.application.volumes.add("some volume") - 它工作得很好。 此外,當我嘗試通過索引從模板獲取值時:print depTemplate.services[0] - 它返回null ,但是當我嘗試通過名稱獲取元素時:print depTemplate.services['application'] - 它返回有效值:

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

所以問題是如何使用變量訪問 map 元素以及如何通過 id 訪問 map 元素?

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

所以我發現了我的錯誤——我在服務后錯過了另一個方括號:

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

所以現在我可以通過索引訪問元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM