B: An introduction to Ansible facts | Enable Sysadmin
#An #introduction #to #Ansible #facts #Enable #Sysadmin #ブックマーク #bookmark
An introduction to Ansible facts | Enable Sysadmin
#:memo
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
all はすべてのホストだね。setupモジュールは具体的になんだろう。 https://docs.ansible.com/ansible/latest/collections/ansible/builtin/setup_module.html
ビルトインなのね。到達性確認の方法として覚えておくと良さそう。
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
をフィルタするのかな。
https://docs.ansible.com/ansible/latest/user_guide/playbooks_vars_facts.html
ここにすべての変数がのっている。
with_items を使えば他のホストの変数が使える
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html
上記に書いてあるように 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' }}"
type: "{{ 'ipv4', 'ipv6' }}"
ansible.builtin.debug:
msg: "{{ hostvarsitem.0'ansible_default_' + item.1.address }}"
loop: "{{ hosts|product(type) }}"
ipv4,ipv6対応するならこう。 #jinja2 の product を使う。
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#iterating-over-nested-lists に書いていた
var を使うと、べんり
これで ufw https://docs.ansible.com/ansible/2.7/modules/ufw_module.html 使って互いのIPを許可とかできますね
thanks
https://serverfault.com/questions/638507/how-to-access-host-variable-of-a-different-host-with-ansibleb