尝试使用 ansible 检索主机的挂载点和设备时出错

尝试使用 ansible 检索主机的挂载点和设备时出错

你好,我正在尝试使用 ansible 检索有关主机的一些信息,包括挂载点和附加设备,但出现了错误。关于列表对象。

- name : Inventory
  hosts: localhost
  tasks:
    
    - name: display infos from host
      ansible.builtin.debug:
        var: ansible_facts

    - name: store disks infos
      ansible.builtin.lineinfile:
        path: "tmp/inventory.log"
        line: "{{ item.device}}"
        create: true
      loop:
        - "{{ ansible_facts.mounts }}"

错误是:

fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'device'. 'list object' has no attribute 'device'\n\nThe error appears to be in '/home/user/workspace/.../playbook-inventory.yml': line 31, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - name: store disks infos\n      ^ here\n"}

但当我看看里面的东西时:

changed: [localhost] => (item=[{'mount': '/', 'device': '/dev/sdc', 'fstype': 'ext4', 'options': 'rw,relatime,discard,errors=remount-ro,data=ordered', 'size_total': 1081101176832, 'size_available': 1017088557056, 'block_size': 4096, 'block_total': 263940717, 'block_available': 248312636, 'block_used': 15628081, 'inode_total': 67108864, 'inode_available': 66837030, 'inode_used': 271834, 'uuid': '495dd145-115b-40d8-8fe3-e7c50afc22b4'}, {'mount': '/mnt/wslg/distro', 'device': '/dev/sdc', 'fstype': 'ext4', 'options': 'ro,relatime,discard,errors=remount-ro,data=ordered', 'size_total': 1081101176832, 'size_available': 1017088557056, 'block_size': 4096, 'block_total': 263940717, 'block_available': 248312636, 'block_used': 15628081, 'inode_total': 67108864, 'inode_available': 66837030, 'inode_used': 271834, 'uuid': '495dd145-115b-40d8-8fe3-e7c50afc22b4'}, {'mount': '/snap', 'device': '/dev/sdc', 'fstype': 'ext4', 'options': 'rw,relatime,discard,errors=remount-ro,data=ordered,bind', 'size_total': 1081101176832, 'size_available': 1017088557056, 'block_size': 4096, 'block_total': 263940717, 'block_available': 248312636, 'block_used': 15628081, 'inode_total': 67108864, 'inode_available': 66837030, 'inode_used': 271834, 'uuid': '495dd145-115b-40d8-8fe3-e7c50afc22b4'}, {'mount': '/var/lib/docker', 'device': '/dev/sdc', 'fstype': 'ext4', 'options': 'rw,relatime,discard,errors=remount-ro,data=ordered,bind', 'size_total': 1081101176832, 'size_available': 1017088557056, 'block_size': 4096, 'block_total': 263940717, 'block_available': 248312636, 'block_used': 15628081, 'inode_total': 67108864, 'inode_available': 66837030, 'inode_used': 271834, 'uuid': '495dd145-115b-40d8-8fe3-e7c50afc22b4'}])

我做错什么了吗?你知道发生了什么事吗?

谢谢你们的帮助和时间。

答案1

您需要使用{{ item['key'] }}来获取字典值。如下所示:

    - name: store disks infos
      ansible.builtin.lineinfile:
        path: "tmp/inventory.log"
        line: "{{ item['device'] }}"
        create: true
      loop: "{{ ansible_facts.mounts }}"

相关内容