我正在尝试编写一个剧本,从我的四个独立的 Docker 主机创建一个 Docker Swarm 集群。作为其中的一部分,我通过 Ansible 事实从每个节点收集 Ansible 主机名和特定以太网设备 IPv4 地址并创建字典:
- name: "Clear swarm_ips dictionary"
set_fact:
swarm_ips: "{{ swarm_ips | default([]) }}"
- name: "Create dictionary with enp42s0 IP and hostname of manager"
set_fact:
swarm_ips: "{{ swarm_ips | combine ({item.key : item.value}) }}"
with_items:
- { 'key': '{{ ansible_facts.hostname | string }}.ip' , 'value': '{{ ansible_facts.enp42s0.ipv4.address | string }}' }
when: (ansible_facts.hostname == "manager")
- name: "Add eth0 IP and hostname of worker[1,2] to swarm_ips"
set_fact:
swarm_ips: "{{ swarm_ips | combine ({item.key : item.value}) }}"
with_items:
- { 'key': '{{ ansible_facts.hostname | string }}.ip' , 'value': '{{ ansible_facts.eth0.ipv4.address | string }}' }
when: (ansible_facts.hostname == "worker1") or
(ansible_facts.hostname == "worker2")
- name: "Add br0 IP and hostname of worker0 to swarm_ips dictionary"
set_fact:
swarm_ips: "{{ swarm_ips | combine ({item.key : item.value}) }}"
with_items:
- { 'key': '{{ ansible_facts.hostname | string }}.ip' , 'value': '{{ ansible_facts.br0.ipv4.address | string }}' }
when: (ansible_facts.hostname == "worker0")
- name: "Echo IP for all nodes from swarm_ips dict"
debug:
var: swarm_ips
我预计剧中最后一步的输出如下所示:
ok: {
"swarm_ips": {
"manager.ip": "10.0.1.203"
"worker0.ip": "10.0.1.42"
"worker1.ip": "10.0.1.201"
"worker2.ip": "10.0.1.252"
}
}
相反我得到
ok: [manager.local] => {
"swarm_ips": {
"manager.ip": "10.0.1.203"
}
}
ok: [worker0.local] => {
"swarm_ips": {
"worker0.ip": "10.0.1.42"
}
}
ok: [worker1.local] => {
"swarm_ips": {
"worker1.ip": "10.0.1.201"
}
}
ok: [worker2.local] => {
"swarm_ips": {
"worker2.ip": "10.0.1.252"
}
}
我可能有一种方法可以运行其中的部分或全部localhost
并使用 hostvars 来获取有关集群主机的信息,但我思考这也应该按我的预期工作。我缺少什么?
答案1
提取字典swarm_ips从主机变量和结合他们,例如
- set_fact:
swarm_ips: "{{ ansible_play_hosts|
map('extract', hostvars, 'swarm_ips')|
combine }}"
run_once: true
给出
swarm_ips:
manager.ip: 10.0.1.203
worker0.ip: 10.0.1.42
worker1.ip: 10.0.1.201
worker2.ip: 10.0.1.252