使用 Playbooks 時(shí),Ansible 會(huì)自動(dòng)執(zhí)行 setup module 以收集各個(gè) Managed node 的 facts。對(duì)凍仁而言這個(gè) facts 就如同系統(tǒng)變數(shù)般的存在,從 IP 位址、作業(yè)系統(tǒng)、CPU 等資訊應(yīng)有盡有。
官方文件介紹如下:
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.
凍仁一般會(huì)先使用 Ad-Hoc Commands 呼叫 setup
看看有哪些用的上的資訊,這對(duì)撰寫些較復(fù)雜的 Playbooks 時(shí)是很有用的。
底下凍仁將使用 chusiang/ansible-managed-node:ubuntu-14.04
這個(gè) Docker image 作為 Managed node。
借由 less 快速搜尋所有的變數(shù)。1
$ ansible all -m setup | less
server1 | SUCCESS => {
"ansible_facts": {
"ansible_all_ipv4_addresses": [
"172.19.0.2"
],
"ansible_all_ipv6_addresses": [
"fe80::42:acff:fe13:2"
],
"ansible_architecture": "x86_64",
"ansible_bios_date": "03/14/2014",
"ansible_bios_version": "1.00",
"ansible_cmdline": {
"com.docker.database": "com.docker.driver.amd64-linux",
"com.docker.driver": "com.docker.driver.amd64-linux,",
"console": "ttyS0",
"earlyprintk": "serial",
"mobyplatform": "mac",
"ntp": "gateway"
},
"ansible_date_time": {
"date": "2016-12-13",
:
搭配 filter
將發(fā)行版本 (distribution) 的資訊給過濾出來。
$ ansible all -m setup -a "filter=ansible_distribution*"
server1 | SUCCESS => {
"ansible_facts": {
"ansible_distribution": "Ubuntu",
"ansible_distribution_major_version": "14",
"ansible_distribution_release": "trusty",
"ansible_distribution_version": "14.04"
},
"changed": false
}
取得套件管理員的種類資訊,此例取得的值為 apt。
$ ansible all -m setup -a "filter=ansible_pkg_mgr"
server1 | SUCCESS => {
"ansible_facts": {
"ansible_pkg_mgr": "apt"
},
"changed": false
}
取得 ansible_pkg_mgr
后,我們可以 Playbooks 里加個(gè)判斷式使用。
建立支持 Debian, Ubuntu, CentOS 安裝 Vim 的 playbook。
$ vim setup_vim.yml
---
- name: Setup the vim
hosts: all
become: true
tasks:
# Debian, Ubuntu.
- name: install apt packages
apt: name=vim state=present
when: ansible_pkg_mgr == "apt"
# CentOS.
- name: install yum packages
yum: name=vim-minimal state=present
when: ansible_pkg_mgr == "yum"
# vim:ft=ansible :
執(zhí)行 playbook,且當(dāng)條件不符時(shí),即會(huì)跳過該 task。。
$ ansible-playbook setup_vim.yml
PLAY [Setup the vim] **************************************************
TASK [setup] **********************************************************
ok: [server1]
TASK [install apt packages] *******************************************
changed: [server1]
TASK [install yum packages] *******************************************
skipping: [server1]
PLAY RECAP ************************************************************
server1 : ok=2 changed=1 unreachable=0 failed=0
setup
module 是每位 Ansibler 一定會(huì)接觸到的!我們可以善加利用它,并與各種需求搭配使用,這樣會(huì)讓 Playbooks 更具彈性且易于維護(hù)。
1. 在 less 里我們可使用/
+ 關(guān)鍵字 +Enter
進(jìn)行搜尋。 ?
更多建議: