根据其他物料清单创建物料清单

时间:2019-12-18 21:20:03

标签: list ansible

我有json文件(我无法更改json文件中的内容)

touch tmp
ls *.txt | for i in 250; do awk -v a=$i '{print $1,a}' tmp; echo "" ; done >  tmp2

我需要使用该文件来创建仅包含一些信息的列表。

所以目前我像这样导入json文件:

{
    "application": {
        ...,
        "VS": [
            {
                "LTM": "server1",
                "ltm_vs": "VS_1",
                "address": "IP",
                "port": "80",
                "link": "/Common/link"
            },
            {
                "LTM": "server1",
                "ltm_vs": "VS_2",
                "address": "IP",
                "port": "8081",
                "link": "/Common/link"
            },
            {
                "LTM": "server1",
                "ltm_vs": "VS_3",
                "address": "IP",
                "port": "443",
                "link": "/Common/link"
            }
        ] 
    }
}

并创建了一个变量列表应用程序。VS,我需要将LTM属性映射到服务器,将ltm_vs映射到virtual_server并创建列表:

...
  tasks:    

    - name: Include application information
      include_vars:
        file: path/file.json

...

我尝试过:

VS_lst:
  - { server: "server1", virtual_server: "VS_1" }
  - { server: "server1", virtual_server: "VS_2" }
  - { server: "server1", virtual_server: "VS_3" }

输出:

    - name: Add variables
      set_fact:
        VS_lst: >- 
          {{ VS_lst +[{
            'server': "{{ item.LTM }}",
            'virtual_server': "{{ item.ltm_vs }}"
          }]
          }}
      with_items: "{{ application.VS }}"

    - debug:
        msg: "{{VS_lst}}"

1 个答案:

答案 0 :(得分:0)

这是固定版本

- name: Add variables
  set_fact:
    VS_lst: "{{ VS_lst|default([]) +
                [{'server': item.LTM,
                  'virtual_server': item.ltm_vs}] }}"
  loop: "{{ application.VS }}"

还有其他选择。例如,可以使用 json_query

- set_fact:
    VS_lst: "{{ application.VS|
                json_query('[].{server: LTM,
                                virtual_server: ltm_vs}') }}"
- debug:
    var: VS_lst

给予

"VS_lst": [
    {
        "server": "server1", 
        "virtual_server": "VS_1"
    }, 
    {
        "server": "server1", 
        "virtual_server": "VS_2"
    }, 
    {
        "server": "server1", 
        "virtual_server": "VS_3"
    }
]

没有 json_query ,此任务“基于另一个项目列表创建项目列表” 并给出相同的结果

- set_fact:
    VS_lst: "{{ VS_lst|default([]) +
                [dict(dictionary_keys|
                      zip(selected_params|
                          map('extract', item)))] }}"
  loop: "{{ application.VS }}"
  vars:
    selected_params: ['LTM','ltm_vs']
    dictionary_keys: ['server', 'virtual_server']