如何循环ansible_devices [elements]

时间:2015-08-20 22:14:45

标签: ansible

我可以从主机收集事实,我可以看到我的驱动器。如何使用ansible_devices变量来获取驱动器(sda,sdb等)?

我试图做类似的事情:

tasks:
- debug: msg={{item.mount}}
  with_items: ansible_mounts

我尝试了以下调试消息,但我能看到的唯一变量只是一个驱动器:

debug: msg={{ hostvars[inventory_hostname]["ansible_devices"] }}

 "ansible_devices": {
        "sda": {
            "holders": [],
            "host": "Serial Attached SCSI controller: LSI Logic / Symbios Logic SAS2008 PCI-Express Fusion-MPT SAS-2 [Falcon] (rev 03)",
            "model": "Crucial_CT480M50",
            "partitions": {
                "sda1": {
                    "sectors": "2097152",
                    "sectorsize": 512,
                    "size": "1.00 GB",
                    "start": "2048"
                },
                "sda2": {
                    "sectors": "8388608",
                    "sectorsize": 512,
                    "size": "4.00 GB",
                    "start": "2099200"
                },
                "sda3": {
                    "sectors": "927213568",
                    "sectorsize": 512,
                    "size": "442.13 GB",
                    "start": "10487808"
                }
            },
            "removable": "0",
            "rotational": "0",
            "scheduler_mode": "cfq",
            "sectors": "937703088",
            "sectorsize": "4096",
            "size": "3.49 TB",
            "support_discard": "33553920",
            "vendor": "ATA"
        },
        "sdb": {
            "holders": [],
            "host": "Serial Attached SCSI controller: LSI Logic / Symbios Logic SAS2008 PCI-Express Fusion-MPT SAS-2 [Falcon] (rev 03)",
            "model": "Micron_M500_MTFD",
            "partitions": {
                "sdb1": {
                    "sectors": "1875380224",
                    "sectorsize": 512,
                    "size": "894.25 GB",
                    "start": "4096"
                }
            },
            "removable": "0",
            "rotational": "0",
            "scheduler_mode": "cfq",
            "sectors": "1875385008",
            "sectorsize": "4096",
            "size": "6.99 TB",
            "support_discard": "33553920",
            "vendor": "ATA"
        },

2 个答案:

答案 0 :(得分:3)

您在模块参数解析时遇到问题。尝试引用这样的论点:

- debug: msg="{{ hostvars[inventory_hostname]["ansible_devices"] }}"

最好使用var代替debug modulemsg

- debug: var=hostvars[inventory_hostname]["ansible_devices"]

我总是建议将模块参数作为dict传递,以降低引用的复杂性:

- debug:
    var: hostvars[inventory_hostname]["ansible_devices"]

您可以使用keys()获取一系列设备名称,如@ ydaetskcoR的回答:

- debug:
    var: hostvars[inventory_hostname]["ansible_devices"].keys()

答案 1 :(得分:0)

您可以看到ansible_devices是附加到主机的所有不同设备的字典,因此您可以使用.keys()轻松获取所有设备名称的列表。

此外,在测试以查看设置变量的内容时,应使用debug' var而不是msg

所以你的调试命令应该是:

debug: var={{ hostvars[inventory_hostname]["ansible_devices"].keys() }}