Home > Mobile >  Modify a YAML playbook in a Jenkins pipeline
Modify a YAML playbook in a Jenkins pipeline

Time:11-24

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]

CodePudding user response:

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 (e.g. a map from suffix to target)

  • Related