ansible 问题返回唯一的键/值

问题描述

很抱歉再次提出一个 bockinfile 问题,但对于之前的案例,我不认为,这与它们相似。 我如何使用键/值对,在每个主机的输出文件中返回一个唯一的键/值。 使用下面提到的剧本,它循环键/值并在所有输出中返回相同的键/值

- hosts: all
  gather_facts: yes
  become: yes
  tasks:
     - blockinfile:
           create: yes
           path: /root/hardware_report
           block: |
             hostname: "{{inventory_hostname}}"
             total_mem: "{{ansible_memtotal_mb}}"
             bios_version: "{{ansible_bios_version}}"
             device_size: "{{ansible_devices.nvme0n1.size | default ('NONE')}}"
             device_size: "{{ansible_devices.nvme1n1.size | default ('NONE')}}"
             "{{item.key}}: {{item.value}}" # (the line main of my issue)
       with_dict: {a: 1,b: 2,c: 3,d: 4}

预期输出: 主机 1:

# BEGIN ANSIBLE MANAGED BLOCK
hostname: "node6"
total_mem: "966"
bios_version: "1.0"
vda_size: "20.00 GB"
vdb_size: "2.00 GB"
"b: 2"
# END ANSIBLE MANAGED BLOCK

host2:

# BEGIN ANSIBLE MANAGED BLOCK
hostname: "node6"
total_mem: "966"
bios_version: "1.0"
vda_size: "20.00 GB"
vdb_size: "2.00 GB"
"d: 4"
# END ANSIBLE MANAGED BLOCK

解决方法

例如

- hosts: test_11,test_12,test_13,test_14
  vars:
    dict: {a: 1,b: 2,c: 3,d: 4}
    list: "{{ dict|dict2items }}"
  tasks:
    - blockinfile:
        create: yes
        path: /root/hardware_report
        block: |
          hostname: {{ inventory_hostname }}
          total_mem: {{ ansible_memtotal_mb }}
          bios_version: {{ ansible_bios_version }}
          {% set index = ansible_play_hosts_all.index(inventory_hostname) %}
          "{{ list[index].key }}: {{ list[index].value }}"
      become: yes

给予

shell> root@test_11:/home/admin # cat /root/hardware_report 
# BEGIN ANSIBLE MANAGED BLOCK
hostname: test_11
total_mem: 3915
bios_version: NA
"a: 1"
# END ANSIBLE MANAGED BLOCK

shell> root@test_12:/home/admin # cat /root/hardware_report 
# BEGIN ANSIBLE MANAGED BLOCK
hostname: test_12
total_mem: 3915
bios_version: NA
"b: 2"
# END ANSIBLE MANAGED BLOCK

...
,

如果我将语法与 jinja2 一起使用,如下面的示例中所述,它是否有效?

  vars:
     keys:
        a:1
        b:2  
        c:3
        d:4
  tasks:
     - blockinfile:
           create: yes
           path: /root/hwreport.txt
           block: |
             hostname: "{{inventory_hostname}}"
             total_mem: "{{ansible_memtotal_mb}}"
             bios_version: "{{ansible_bios_version}}"
             "{{keys|random|unique}}"

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...