0

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

- 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

主机2:

# 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
4

2 回答 2

0

例如

- 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

...
于 2020-12-26T14:04:22.487 回答
0

如果我使用下面示例中提到的 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}}"
于 2020-12-26T14:39:06.240 回答