Ansible 模擬考考題 + 考題詳解 – 創建Roles並安裝httpd – part 3
環境配置請參考第0章環境配置喔 ~~
Ansible 模擬考第四題,創建Roles並安裝httpd
請寫一個 Roles 名為 httpd 存放於 /home/student/ansible/roles ,內容要求如下:
* 安裝httpd並將其啟動、開機後自動啟動
* 在firewalld上啟動http的存取
* 有一個template名稱為 index.html.j2 用來建立網站,其内容(變數)為
{{HOSTNAME-FQDN}} -- {{IPADDRESS}}
* 請在 webservers 群組執行
* 寫一個 PlayBook -> install_httpd.yml 執行httpd roles
- 小技巧,考試時可以多開啟另一個終端機,準備的 ansible-doc ,隨時查閱相關參數
考題解答
- 使用 ansible-galaxy 創建 ROLE角色
ansible-galaxy role init httpd
- 模組使用計有: yum、 service、 template
- 透過 ansible-doc yum 可以顯示相關 example範例(如下圖)
- 編輯 /home/student/ansible/roles/httpd/templates/index.html.j2 創建 Template 模版
{{ ansible_fqdn }} -- {{ ansible_default_ipv4.address }}
- 透過Jinja2引擎即可透過"Ansible 魔法變數(詳情可參閱官網)"改變其變數內容
- Ansible 魔法變數不用死背,可以透過 setup 將所有魔法變數輸出至 file 方便查詢,使用方式如下圖
- 編輯 httpd roles 的 tasks 來安裝httpd及改變防火牆規則 -> /home/student/ansible/roles/httpd/tasks/main.yml
- 注意: 此為編輯 Roles tasks 任務,並不需要填入hosts 表頭
# tasks file for httpd
- name: install httpd
yum:
name: httpd
state: present
- name: enable httpd
service:
name: httpd
state: started
enabled: yes
- name: template web
template:
src: index.html.j2
dest: /var/www/html/index.html
- name: firewalld rules
firewalld:
service: http
permanent: yes
immediate: yes
state: enabled
- 創建 playbook -> /home/student/ansible/install_httpd.yml
---
- name:
hosts: webservers
roles:
- httpd
- 執行
ansible-playbook install_httpd.yml -C
檢查測試playbook有沒有問題,如無出錯(如下圖),另可以執行playbook並至受控節點端驗證。
- 執行完 playbook 驗證模版是否正確
curl http://serverb.lab.example.com
# serverb.lab.example.com - 172.25.250.11
curl http://serverc.lab.example.com
# serverc.lab.example.com - 172.25.250.12