简体   繁体   English

在 Jenkins 管道中修改 YAML 剧本

[英]Modify a YAML playbook in a Jenkins pipeline

I have a delivery.yaml used by Ansible to deploy data:我有一个 Delivery.yaml 被 Ansible 用来部署数据:

---
  - 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:我需要根据数据扩展完成“dest”值:

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

How to write it?怎么写? I'm not used with groovy language.我不使用 groovy 语言。 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.所以 Groovy 将使用隐式扩展运算符。 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).这里的find是否正确取决于数据(这只会找到第一个,如果没有就会失败)。 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).很可能您想要findAll (这会导致所有结果的列表,并且.dest分配由于隐式传播运算符仍然有效)。

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)为了摆脱对所有四种类型(或有多少种)执行此操作的复制和粘贴代码,最好将转换提取为数据(例如,从后缀到目标的 map)

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

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