在Ansible中处理dict变量中的嵌入式列表

时间:2019-03-01 06:42:08

标签: ansible

我在Ansible中获得了示例代码:

    - name: testing
      hosts: localhost
      vars:
        svc:
          https: ['tcp/443']
          app_svc: ['tcp/5543', 'udp/5543', 'tcp/3100']
      tasks:
      - name: print
        debug:
          msg: port={{item.key}} value={{item.value}}

        with_dict:
         - "{{svc}}"
And this outputs to:
  

好:[127.0.0.1] =>(项目=无)=> {          “ msg”:“端口= app_svc值= [u'tcp / 5543',u'udp / 5543',u'tcp / 3100']”      }      好的:[127.0.0.1] =>(item = None)=> {          “ msg”:“端口= https值= [u'tcp / 443']”      }

我想要实现的是,当值列表中有多个元素时,它将像这样拆分:

 - name=https, prot=tcp, port=443
 - name=app_svc, prot=tcp, port=5543
 - name=app_svc, prot=udp, port=5543
 - name=app_svc, prot=tcp, port=3100

with_dict节仅显示了整个列表,而我找不到其他方法来执行此操作。是否可以这样做而不重新组织var节?预先感谢您的输入。

1 个答案:

答案 0 :(得分:0)

要查看语法错误,请运行

exports.config = {
  tests: './*_test.js',
  output: './output',
  helpers: {
    Puppeteer: {
      url: 'https://url/',
      fullPageScreenshots: true,
         chrome: {
            args: ['--use-fake-ui-for-media-stream',
            '--disable-web-security',
            '--use-fake-device-for-media-stream',
            '--use-file-for-fake-video-capture="C:\Users\user\Desktop\test\bridge_far_cif.y4m"',
            '--allow-file-access',
            '--allow-running-insecure-content',
            ]
        }
    }
  },
  include: {
    I: './steps_file.js'
  },
  bootstrap: null,
  mocha: {},
  name: 'test',
  translation: 'ru-RU'
}

正确的语法应为

# ansible-lint <YOUR-PLAYBOOK>

给予

- hosts: localhost
  gather_facts: no
  vars:
    svc:
      https: ['tcp/443']
      app_svc: ['tcp/5543', 'udp/5543', 'tcp/3100']
  tasks:
    - name: print
      debug:
        msg: "port={{ item.key }} value={{ item.value }}"
      with_dict: "{{ svc }}"

更改循环

"msg": "port=app_svc value=[u'tcp/5543', u'udp/5543', u'tcp/3100']"
"msg": "port=https value=[u'tcp/443']"

获取格式

- name: print
  debug:
    msg: "name={{ item.0.key }},
          prot={{ item.1.split('/')[0] }},
          port={{ item.1.split('/')[1] }}"
  loop: "{{ lookup('subelements', svc|dict2items, 'value') }}"

dict2items从2.6版开始可用。如果没有“ dict2items ”,则首先转换数据。参见下文(未经测试)。

"msg": "name=app_svc, prot=tcp, port=5543"
"msg": "name=app_svc, prot=udp, port=5543"
"msg": "name=app_svc, prot=tcp, port=3100"
"msg": "name=https, prot=tcp, port=443"