Home > Software design >  Jenkins pipeline - Read yaml and append to a list
Jenkins pipeline - Read yaml and append to a list

Time:08-25

I have the below template yaml in my github

kind: Endpoints
apiVersion: v1
metadata:
 name: SERVICENAME
 namespace: NAMESPACE
subsets:
 - addresses:
     - ip: SERVICEADDRESS
   ports:
     - port: SERVICEPORT

I am trying to parse this yaml file in Jenkins pipeline and append values to placeholders like below.

kind: Endpoints
apiVersion: v1
metadata:
 name: test
 namespace: testnamespace
subsets:
 - addresses:
     - ip: 10.22.33.22
     - ip: 10.22.11.33
   ports:
     - port: 1042

I am able to read the yaml as an object using below code

def extEpData = readYaml (file: 'external-ep.yaml')

Not able to append multiple ip addresses to the list

 extEpData.metadata.name = serviceName
 extEpData.metadata.namespace = namespace
 extEpData.subsets[0].ports[0].port = servicePort as int
 for (int i=0; i<=addressList.size(); i  ) {
           echo addressList[i]
           extEpData.subsets[0].addresses[0].ip = addressList[i]
  }
  writeYaml file: 'external-ep.yaml', data: extEpData, overwrite: true

addressList array holds the ip list. Above code is not appending multiple ip addresses. Its only working for one ip address. What am I doing wrong?

CodePudding user response:

If you update the accessed element index in the nested array/list on each iteration, then you should be good to go:

for (int i=0; i<=addressList.size(); i  ) {
  extEpData.subsets[0].addresses[i].ip = addressList[i]
}

However, this is only true if the number of elements of the placeholder is equal to the number of inserted elements. This is not necessarily always true, so you should append by Map instead of by value associated with Map key:

for (int i=0; i<=addressList.size(); i  ) {
  extEpData.subsets[0].addresses[i] = ['ip': addressList[i]]
}
  • Related