1)Playbook由一個或多個"play"組成的列表,play的主要功能Ansible中的Task定義好的角色,指定劇本對應的服務器組。nginx
於Ansible Playbook還能夠收集命令、能夠建立任務集,這樣可以大大下降管理工做的複雜程度,Playbook採用YAML語法結構,易於閱讀、方便配置。web
2)Playbooks組件包括以下:shell
Target 定義playbook的遠程主機組
Variable 定義playbook使用的變量
Task 定義遠程主機上執行的任務列表
Handler 定義task執行完成之後須要調用的任務
3)Target 經常使用參數以下:服務器
hosts 定義遠程主機組;
user 執行該任務的用戶;
sudo 設置爲yes的時候,執行任務的時候使用root權限;
sudo_user 指定sudo普通用戶;
connection 默認基於SSH鏈接客戶端;
gather_facks 獲取遠程主機facts基礎信息。
4)Variable 經常使用參數以下:spa
vars 定義格式,變量名:變量值;
vars_files 指定變量文件;
vars_prompt 用戶交互模式自定義變量;
setup 模塊去遠程主機的值;
5)Task經常使用參數以下:code
name 任務顯示名稱即屏幕顯示信息
action 定義執行動做
copy 複製本地文件到遠程主機
template 複製本地文件到遠程主機,能夠引用本地變量
service 定義服務的狀態
二、遠程主機安裝Nginx WEB服務,playbook代碼以下server
-host:all remote_user: root tasks: -name:pcre pcre-devel and zlib lib install yum: name=pcre,pcre-devel,zlib,zlib-devel state=install -name: Nginx WEB Server Install Process shell: cd /tmp;rm -rf nginx-1.12.2.tar.gz;wget http://nginx.org/download/nginx-1.12.2.tar.gz;tar xzf nginx-1.12.2.tar.gz;cd nginx-1.12.2;./configure --prefix=/usr/local/nginx;make;make install
1)檢測遠程主機Nginx目錄是否存在,不存在則安裝Nginx WEB服務,安裝完並啓動Nginx,playbook代碼以下blog
- hosts: all remote_user: root tasks: - name: Nginx server Install file: path=/usr/local/nginx/ state=directory notify: - nginx install - nginx start handlers: - name: nginx install shell: cd /tmp;rm -rf nginx-1.12.2.tar.gz;wget http://nginx.org/download/nginx-1.12.2.tar.gz;tar xzf nginx-1.12.2 .tar.gz;cd nginx-1.12.2;./configure --prefix=/usr/local/nginx;make;make install - name: nginx start shell: /usr/local/nginx/sbin/nginx
2)檢測遠程主機內核參數配置文件是否更新,若是更新則執行命令sysctl –p使內核參數生效,playbook代碼以下rem
- hosts: all remote_user: root tasks: - name: Linux kernel config 2019 copy: src=/data/sh/sysctl.conf dest=/etc/ notify: - source sysctl handlers: - name: source sysctl shell: sysctl -p
3)基於列表items多個值建立用戶,經過{{}}定義列表變量,with_items選項傳入變量的值get
- hosts: all remote_user: root tasks: - name: Linux system Add User list. user: name={{ item }} state=present with_items: - jfedu1 - jfedu2 - jfedu3 - jfedu4
4)Ansible Playbook能夠自定義template模板文件,模板文件主要用於服務器需求不一致的狀況,須要獨立定義的,例如兩臺服務器安裝了Nginx,安裝完畢以後將服務器A的HTTP端口改爲80,服務器B的HTTP端口改爲81,基於tempalte模塊輕鬆實現
Ansible hosts文件指定不一樣服務器不一樣httpd_port端口
[web] 192.168.0.112 httpd_port=80 192.168.0.113 httpd_port=81
Ansible 建立nginx.conf jinja2模板文件,cp nginx.conf nginx.conf.j2,並修改listen 80爲listen {{httpd_port}},Nginx其餘配置項不變
cp nginx.conf nginx.conf.j2
listen {{httpd_port}};
Ansible playbook劇本yaml文件建立
- hosts: all remote_user: root tasks: - name: Nginx server Install 2019 file: path=/usr/local/nginx/ state=directory notify: - nginx install - nginx config handlers: - name: nginx install shell: cd /tmp;rm -rf nginx-1.12.2.tar.gz;wget http://nginx.org/download/nginx-1.12.2.tar.gz;tar xzf nginx-1.12.2 .tar.gz;cd nginx-1.12.2;./configure --prefix=/usr/local/nginx;make;make install - name: nginx config template: src=/root/nginx.conf.j2 dest=/usr/local/nginx/conf/nginx.conf
Ansible playbook執行劇本文件