1. 利用主機模式選擇主機
使用通配符匹配多個主機:
- hosts: '*' ##所有主機
- hosts: '*.example.com' #以exmaple.com結尾的主機
- hosts: '172.25.254.*' #匹配172.25.254網段的所有主機
通過列表匹配主機或主機組:
- hosts: www1.example.com,www2.example.com,172.25.254.250 #主機
- hosts: webservers,westos #主機組
也可以將通配符和列表等一起使用
- hosts: webservers,&westos #即屬於 webserver 組,也屬於 westos 組
- hosts: westos,!servera.lab.example.com #匹配 westos 組中所有主機,但是 servera.lab.example.com 除外
- hosts:all,!servera.lab.example.com ##所有主機除了 servera.lab.example.com
2. 管理動態清單
將 INI 格式的清單轉換爲 JSON 格式 ansible-inventory -i inventory --list
2.1 配置並行
使用 forks 在 ansible 中配置並行 ;ansible 最大同時連接數由 ansible 配置文件中 forks 參數控制
查看默認forks值
管理滾動更新:
如果更新發生在負載均衡服務器,更新完成會重啓,可能導致後端所有 web 服務器停止服務, 可以使用 serial 關鍵字來分批運行
---
- name: Rolling update
hosts: webservers
serial: 2
tasks:
- name: Install apache
yum:
name: httpd
state: latest
notify: restart apache
handlers:
- name: restart apache
service:
name: httpd
state: restarted
‘serial 參數還有一個優點:在更新時如果出現問題,那麼在前 2 臺發生問題是 playbook 就會 停止運行,後面的服務器不會執行,那麼也就保證了服務的高可用’
3. 包含和導入文件
大型 playbook 管理起來比較複雜,可以用模塊化的方式管理 ;兩種方法:包含、導入
導入 playbook:
- name: configure webserver
import_playbook: web.yml
導入和包含任務的 playbook:
①:編寫一個只有任務的 playbook vim tasks.yml
- name: Install apache
yum:
name: httpd
state: latest
- name: Start Apache
service:
name: httpd
state: started
②:導入任務:使用導入時,when 等條件語句應用於導入的每個任務;循環不能作用於導入的任務
---
- name: Install web
hosts: webservers
tasks:
- import_tasks: tasks.yml
③:包含任務
---
- name: Install web
hosts: webservers
tasks:
- include_tasks: tasks.yml
爲外部 play 和任務定義變量:
提高複用性
---
- name: Install the {{ packages }}
yum:
name: "{{ packages }}"
state: latest
- name: Start the {{ service }}
service:
name: "{{ service }}"
enabled: true
state: started
4. 練習
目錄結構
①:vim install_and_enabled.yml
##編寫安裝和啓用服務的playbook
---
- name: Install the {{ packages }}
yum:
name: "{{ packages }}"
state: latest
- name: Start the {{ service }}
service:
name: "{{ service }}"
enabled: true
state: started
②:apache 配置 vim web_tasks.yml
---
- name: Install and start httpd
import_tasks: install_and_enabled.yml
vars:
packages: httpd
service: httpd
- name: Configure apache
copy:
src: files/example.conf
dest: /etc/httpd/conf.d/example.conf
owner: root
group: root
mode: 0644
notify:
- restart httpd
③:vim firewall_tasks.yml
firewall 配置
---
- name: Install and start firewalld
import_tasks: install_and_enabled.yml
vars:
packages: firewalld
service: firewalld
- name: firewalld permit apache
firewalld:
service: http
immediate: true
permanent: true
state: enabled
④:vim playbook.yml
##編寫主playbook
---
- name : install and configure web service
hosts: webservers
tasks:
- name: impoirt web_tasks.yml
import_tasks: tasks/web_tasks.yml
- name: impoirt firewall_tasks.yml
import_tasks: tasks/firewall_tasks.yml
handlers:
- name: restart httpd
service:
name: httpd
state: restarted
運行結果