怎麼使用 setup 取得 Managed node 的 facts?

13. 怎麼使用 setup 取得 Managed node 的 facts?

使用 Playbooks 時,Ansible 會自動執行 setup module 以蒐集各個 Managed node 的 facts。對凍仁而言這個 facts 就如同系統變數般的存在,從 IP 位址、作業系統、CPU 等資訊應有盡有。

automate_with_ansible_practice-18.jpg

官方文件介紹如下:

This module is automatically called by playbooks to gather useful variables about remote hosts that can be used in playbooks. It can also be executed directly by /usr/bin/ansible to check what variables are available to a host. Ansible provides many facts about the system, automatically.

Ad-Hoc Commands

凍仁一般會先使用 Ad-Hoc Commands 呼叫 setup 看看有哪些用的上的資訊,這對撰寫些較複雜的 Playbooks 時是很有用的。

底下凍仁將使用 chusiang/ansible-managed-node:ubuntu-14.04 這個 Docker image 作為 Managed node。

  1. 藉由 less 快速搜尋所有的變數。

  1. 搭配 filter 將發行版本 (distribution) 的資訊給過濾出來。

  1. 取得套件管理員的種類資訊,此例取得的值為 apt

撰寫跨 Linux distribution 的 Playbooks

取得 ansible_pkg_mgr 後,我們可以 Playbooks 裡加個判斷式使用。

  1. 建立支援 Debian, Ubuntu, CentOS 安裝 Vim 的 playbook。

  1. 執行 playbook,且當條件不符時,即會跳過該 task。。

後語

setup module 是每位 Ansibler 一定會接觸到的!我們可以善加利用它,並與各種需求搭配使用,這樣會讓 Playbooks 更具彈性且易於維護。

相關連結

Last updated

Was this helpful?