简体   繁体   中英

Modify a YAML playbook in a Jenkins pipeline

I have a delivery.yaml used by Ansible to deploy data:

---
  - name: Deploy to Filer on host
    hosts: host
    tasks:
      - name: Copy files
        copy: src={{ item.src }} dest={{ item.dest }} mode=0775
        with_items:
          - { src: 'data1.xml', dest: '' }
          - { src: 'data2.so', dest: '' }
          - { src: 'data3.exe', dest: '' }
          - { src: 'data4.lib', dest: '' }

I need to complete the "dest" value according to the data extension:

xml files => target1
so files => target2
exe files => target3
lib files => target4

How to write it? I'm not used with groovy language. Currently, I write this but it does not work:

stage('YAML test'){
            steps{
                script{
                    yamlData = readYaml file: 'delivery.yaml'
                    yamlData.tasks.with_items.find{it.src.endsWith("xml")}.dest="target1"
                    writeYaml file: 'delivery_temp.yaml', data: yamlData
                    sh "cat delivery_temp.yaml"
                }
            }
        }

I got this error:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.endsWith() is applicable for argument types: (java.lang.String) values: [xml]

The problem here is, that your outermost data type is already a list. So Groovy will use the implicit spread operator. What is implied here is:

yamlData*.tasks*.with_items.find{ it*.src.endWith ... }

So you actually want to do the transformation for each element on the outer most level:

yamlData.each{ it.tasks.each { task -> task.with_items.find{it.src.endsWith("xml")}.dest="target1" } }

Whether the find here is correct depends on the data (this will only find the first one and it will fail if there is none). Most likely you want findAll instead (which results in a list of all results and the .dest assignment would still work due to the implicit spread operator).

And to get rid of the copy and paste code for doing this for all four types (or how many there will be), you are better off extracting the transformations out as data (eg a map from suffix to target)

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