如何解决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}}"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。