AWS Ansible创建按实例标记分组的IP地址的字典

时间:2018-10-09 21:51:42

标签: amazon-web-services ansible

我有几个EC2实例,我需要从中提取IP地址并按特定的实例标记对其进行分组。

这个示例JSON:

{
    "changed": true,
    "instances": [ 
        {
            "ami_launch_index": 0,
            "architecture": "x86_64",
            "private_ip_address": "11.111.1.111", 
            "public_dns_name": "",
            "tags": {
                "Environment": "dev",
                "Role": "role1",
            }
        },
        { 
            "ami_launch_index": 0,
            "architecture": "x86_64",
            "private_ip_address": "22.222.2.222",
            "public_dns_name": "",
            "tags": {
                "Environment": "dev",
                "Role": "role1",
            }
        },
        {
            "ami_launch_index": 0,
            "architecture": "x86_64",
            "private_ip_address": "33.333.3.333",
            "public_dns_name": "",
            "tags": {
                "Environment": "dev",
                "Role": "role2",
            }
        },
        {
            "ami_launch_index": 0,
            "architecture": "x86_64",
            "private_ip_address": "44.444.4.444",
            "public_dns_name": "",
            "tags": {
                "Environment": "dev",
                "Role": "role2",
            }
        }
    ]
}

将产生以下内容:

{
    "role1": [
        "11.111.1.111",
        "22.222.2.222"
    ],
    "role2": [
        "33.333.3.333",
        "44.444.4.444"
    ]
}

从AWS中获取实例信息没有问题,但是我正在努力创建包含IP地址分组列表的字典。我已经尝试了this similar issue中提供的解决方案的几种变体,但是没有任何运气。

1 个答案:

答案 0 :(得分:1)

您在这里:

- set_fact:
    my_result: "{{ my_result | default({}) | combine({item.0: item.1|map(attribute='private_ip_address')|list}) }}"
  loop: "{{ my_input.instances|groupby('tags.Role') }}"