
我的庫存如下所示:
db0 ansible_host=10.0.0.1
db1 ansible_host=10.0.0.2
app0 ansible_host=10.0.0.3
app1 ansible_host=10.0.0.4
...
由此,我需要提取這樣的清單:
- name: db0
ip: 10.0.0.1
- name: db1
ip: 10.0.0.2
- name: app0
ip: 10.0.0.3
- name: app1
ip: 10.0.0.4
我知道我可以讓所有主機使用groups['all']
.
我還可以ansible_host
使用 來取得每個主機的值hostvars['<hostname>']['ansible_host']
。
我如何結合它來創建我需要的清單?
答案1
例如
host_ip: "{{ dict(ansible_play_hosts_all|
zip(ansible_play_hosts_all|
map('extract', hostvars, 'ansible_host'))) }}"
創建字典
host_ip:
app0: 10.0.0.3
app1: 10.0.0.4
db0: 10.0.0.1
db1: 10.0.0.2
然後,使用字典2項創建列表
host_ip_list: "{{ host_ip|dict2items(key_name='name',
value_name='ip') }}"
給出預期的結構
host_ip_list:
- ip: 10.0.0.1
name: db0
- ip: 10.0.0.2
name: db1
- ip: 10.0.0.3
name: app0
- ip: 10.0.0.4
name: app1