基于条件的Ansible词典拆分

2024-05-15 17:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用ansible在OpenShift环境中从普罗米修斯那里获取数据。我正在创建一个类似以下输出的字典。现在,我打算根据主机名将此字典拆分为三个单独的字典,分别用于主节点、工作节点和infra节点

我试过这样的方法,但失败了

- name: Seperate Dictionary Creation
  set_fact:
          master_nodes: "{{ master_nodes | combine( when: item.key == '*.master.*') }} "
  with_dict: "{{ all_host_dict }}"

可翻译字典输出

ok: [127.0.0.1] => {
    "msg": {
        "machine-worker01": {
            "cpu_percent": 0.5,
            "cpu_total": 12,
            "cpu_used": 0.06     
        },
        "machine-master01": {
            "cpu_percent": 0.58,
            "cpu_total": 12,
            "cpu_used": 0.07
        },
        "machine-master03": {
            "cpu_percent": 0.58,
            "cpu_total": 12,
            "cpu_used": 0.07
        },
        "machine-infra01": {
            "cpu_percent": 0.5,
            "cpu_total": 12,
            "cpu_used": 0.06
        },
        "machine-worker07": {
            "cpu_percent": 0.58,
            "cpu_total": 12,
            "cpu_used": 0.07
        }
    }
}

Tags: master字典节点环境ansiblecpumachinedict
2条回答

这应该做到:

- name: Seperate Dictionary Creation
  set_fact:
    master_nodes: "{{ (master_nodes | default({})) | combine({item.key: item.value}) }}"
  when: item.key is search(".*master.*")
  with_dict: "{{ all_host_dict }}"

此外,正则表达式应该从*.master.*修改为.*master.*

任务

    - set_fact:
        my_nodes: "{{ my_nodes|default({})|
                      combine({(item ~ '_nodes'):
                               all_host_dict|dict2items|
                               selectattr('key', 'search', item)|
                               list|items2dict}) }}"
      loop: [master, worker, infra]
    - debug:
        var: my_nodes

给予

    "my_nodes": {
        "infra_nodes": {
            "machine-infra01": {
                "cpu_percent": 0.5,
                "cpu_total": 12,
                "cpu_used": 0.06
            }
        },
        "master_nodes": {
            "machine-master01": {
                "cpu_percent": 0.58,
                "cpu_total": 12,
                "cpu_used": 0.07
            },
            "machine-master03": {
                "cpu_percent": 0.58,
                "cpu_total": 12,
                "cpu_used": 0.07
            }
        },
        "worker_nodes": {
            "machine-worker01": {
                "cpu_percent": 0.5,
                "cpu_total": 12,
                "cpu_used": 0.06
            },
            "machine-worker07": {
                "cpu_percent": 0.58,
                "cpu_total": 12,
                "cpu_used": 0.07
            }
        }
    }

相关问题 更多 >