B: An introduction to Ansible facts | Enable Sysadmin
Ansible fact
A fact can be the IP address, BIOS information, a system's software information, and even hardware information.
お互いのIPアドレス情報を交換したいとか、めちゃくちゃあるもんね。
The setup module fetches all the details from the remote hosts to our controller nodes and dumps them directly to our screen for the facts to be visible to users.
ansible all -m setup
ビルトインなのね。到達性確認の方法として覚えておくと良さそう。
ansible all -m setup -i inventory/mycluster/hosts.yaml
それぞれの public ip については
ansible_facts.ansible_default_ipv4.address
ansible_facts.ansible_default_ipv6.address
あたりを見ればよさそうだ。
複数の ip をもつ場合は
ansible_facts.ansible_all_ipv4_addresses
ansible_facts.ansible_all_ipv6_addresses
をフィルタするのかな。
ここにすべての変数がのっている。
with_items を使えば他のホストの変数が使える
上記に書いてあるように loop と items を使うのが新しいやりかたのよう。
code:yaml
- name: with_items -> loop
ansible.builtin.debug:
msg: "{{ item }}"
loop: "{{ items|flatten(levels=1) }}"
code:yaml
- name: foo
hosts: all
tasks:
- name: with_items -> loop
ansible.builtin.debug:
msg: "{{ hostvarsitem.ansible_default_ipv4.address }}" loop: "{{ groups'all' }}" 上記を ansible-playbook で動かせばすべての互いの IP アドレスがわかることになる
code:yaml
---
- name: foo
hosts: all
tasks:
- name: with_items -> loop
vars:
hosts: "{{ groups'all' }}" ansible.builtin.debug:
loop: "{{ hosts|product(type) }}"
ipv4,ipv6対応するならこう。 #jinja2 の product を使う。 var を使うと、べんり
thanks