Ansibleを使用してIP辞書にホスト名を作成する

Ansibleを使用してIP辞書にホスト名を作成する

4つの独立した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ホスト変数を使用してクラスタホストに関する情報を取得する方法があります。考えるこれも私が期待どおりに機能します。私は何を見逃していますか?

ベストアンサー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

おすすめ記事