1.Playbook劇本初識
1.什么是playbook,playbook翻譯過來就是“劇本”,那playbook組成如下
play: 定義的是主機的角色
task: 定義的是具體執行的任務
playbook: 由一個或多個play組成,一個play可以包含多個task任務
簡單理解為: 使用不同的模塊完成一件事情
2.playbook的優勢
1.功能比ad-hoc更全
2.能很好的控制先后執行順序, 以及依賴關系
3.語法展現更加的直觀
4.ad-hoc
無法持久使用,playbook
可以持久使用
3.playbook的配置語法是由yaml語法描述的,擴展名是yaml
- 縮進
- YAML使用固定的縮進風格表示層級結構,每個縮進由兩個空格組成, 不能使用tabs
- 冒號
- 以冒號結尾的除外,其他所有冒號后面所有必須有空格。
- 短橫線
- 表示列表項,使用一個短橫杠加一個空格。
- 多個項使用同樣的縮進級別作為同一列表。
#playbook示例
[root@m01 ~]# cat f1.yml
---
- hosts: all
remote_user: root
vars:
file_name: weiaixiong
tasks:
- name: Create New File
file: name=/tmp/{{ file_name }} state=touch
#檢測語法
[root@m01 ~]# ansible-playbook --syntax f1.yml
#模擬執行
[root@m01 ~]# ansible-playbook -C f1.yml
#playbook執行方式
[root@m01 ~]# ansible-playbook f1.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [10.0.0.30]
TASK [使用變量] *******************************************************************************************************************************
changed: [10.0.0.30]
PLAY RECAP ********************************************************************************************************************************
10.0.0.30 : ok=2 changed=1 unreachable=0 failed=0
Playbook執行結果返回顏色狀態
紅色: 表示有task執行失敗或者提醒的信息
黃色:表示執行了且改變了遠程主機狀態
綠色:表示執行成功
2.Playbook變量使用
Playbook定義變量有三種方式
ansible怎么定義變量 怎么使用變量{{ 變量名稱 }}
1.通過playbook文件中的play進行定義
通過vars來進行定義變量
通過vars_files來進行定義變量
2.通過inventory主機清單進行變量定義
通過host_vars對主機進行定義
通過group_vars對主機組進行定義
3.通過執行playbook時使用-e參數指定變量
1、playbook的yaml文件中定義變量賦值
#playbook中定義
[root@m01 project1]# cat vars_1.yml
- hosts: web
vars:
- web_packages: httpd-2.4.6
- ftp_packages: vsftpd-3.0.2
tasks:
- name: Installed {{ web_packages }} {{ ftp_packages }}
yum:
name:
- "{{ web_packages }}"
- "{{ ftp_packages }}"
state: present
2.通過定義一個變量文件,然后使用playbook進行調用
[root@m01 project1]# cat vars_public.yml
web_packages: httpd-2.4.6
ftp_packages: vsftpd-3.0.2
[root@m01 project1]# cat vars_1.yml
- hosts: web
vars_files: ./vars_public.yml
tasks:
- name: Installed {{ web_packages }} {{ ftp_packages }}
yum:
name:
- "{{ web_packages }}"
- "{{ ftp_packages }}"
state: present
2、通過inventory主機清單進行變量定義
在項目目錄下創建兩個變量的目錄,host_vars group_vars
#1)在當前的項目目錄中創建兩個變量的目錄
[root@m01 project1]# mkdir host_vars
[root@m01 project1]# mkdir group_vars
#2)在group_vars目錄中創建一個文件,文件名與inventory清單中的組名稱要保持完全一致。
[root@m01 project1]# cat group_vars/oldboy
web_packages: wget
ftp_packages: tree
#3)編寫playbook,只需在playbook文件中使用變量即可。
[root@m01 project1]# cat f4.yml
- hosts: web
tasks:
- name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}"
yum:
name:
- "{{ web_packages }}"
- "{{ ftp_packages }}"
state: present
注意: 默認情況下,group_vars目錄中文件名與hosts清單中的組名保持一致.
比如在group_vars目錄中創建了oldboy組的變量,其他組是無法使用oldboy組的變量
系統提供了一個特殊組,all,只需要在group_vars目錄下建立一個all文件,編寫好變量,所有組都可使用.
#---------------------hosts_vars----------------
#1)在host_vars目錄中創建一個文件,文件名與inventory清單中的主機名稱要保持完全一致
[root@ansible project1]# cat hosts
[oldboy]
172.16.1.7
172.16.1.8
#2)在host_vars目錄中創建文件,給172.16.1.7主機定義變量
[root@ansible project1]# cat host_vars/172.16.1.7
web_packages: zlib-static
ftp_packages: zmap
#3)準備一個playbook文件調用host主機變量
[root@ansible project1]# cat f4.yml
- hosts: 172.16.1.7
tasks:
- name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}"
yum:
name:
- "{{ web_packages }}"
- "{{ ftp_packages }}"
state: present
- hosts: 172.16.1.8
tasks:
- name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}"
yum:
name:
- "{{ web_packages }}"
- "{{ ftp_packages }}"
state: present
host_vars 特殊的變量目錄,針對單個主機進行變量.
group_vars 特殊的變量目錄,針對inventory主機清單中的組進行變量定義. 對A組定義的變量 B組無法調用
group_vars/all 特殊的變量文件,可以針對所有的主機組定義變量.
3.通過執行playbook時使用-e參數指定變量
[root@m01 project1]# cat vars_7.yml
- hosts: "{{ hosts }}" #注意:這是一個變量名稱
tasks:
- name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}"
yum:
name:
- "{{ web_packages }}"
- "{{ ftp_packages }}"
state: present
[root@m01 project1]# #ansible-playbook -i hosts vars_7.yml -e "hosts=web"
如果定義的變量出現重復,且造成沖突,優先級如下:
變量的優先級
外置傳參-->playbook(vars_files-->vars)-->inventory(host_vars-->group_vars/group_name-->group_vars-all)
3.Playbook變量注冊
1) 注冊變量: register關鍵字可以存儲指定命令的輸出結果到一個自定義的變量中
[root@m01 ~]# cat f5.yml
---
- hosts: all
tasks:
- name:
shell: netstat -lntp
register: System_Status
- name: Get System Status
debug: msg={{System_Status.stdout_lines}}
#playbook執行結果
[root@m01 ~]# ansible-playbook f5.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [10.0.0.30]
TASK [shell] ******************************************************************************************************************************
changed: [10.0.0.30]
TASK [Get System Status] ******************************************************************************************************************
ok: [10.0.0.30] => {
"msg": [
"tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 925/sshd ",
"tcp6 0 0 :::22 :::* LISTEN 925/sshd "
]
}
PLAY RECAP ********************************************************************************************************************************
10.0.0.30 : ok=3 changed=1 unreachable=0 failed=0
4..ansible facts變量
用來采集被控端的狀態指標,比如: IP地址 主機名稱 cpu信息 內存 等等
默認情況的facts變量名都已經預先定義好了, 只需要采集被控端的信息,然后傳遞至facts變量即可.
#1.如何提取被控端的總內存大小
[root@m01 project1]# ansible 172.16.1.8 -m setup -a "filter=ansible_memtotal_mb" -i hosts
172.16.1.8 | SUCCESS => {
"ansible_facts": {
"ansible_memtotal_mb": 1996,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
#2.通過注冊變量獲取facts值
[root@m01 project1]# cat vars_12.yml
- hosts: web
tasks:
- name: Installed Memcached Server
yum: name=memcached state=present
- name: Configure Memcached Server
template: src=./memcached.j2 dest=/etc/sysconfig/memcached
- name: Service Memcached Server
service: name=memcached state=started enabled=yes
- name: Check Memcached Server
shell: ps aux|grep memcached
register: check_mem
- name: Debug Memcached Variables
debug:
msg: "{{ check_mem.stdout_lines }}"
5.Playbook條件語句
playbook中的條件判斷語句使用when
[root@m01 ~]# cat f6.yml
- hosts: all
remote_user: root
tasks:
- name: Create File
file: path=/tmp/this_is_{{ ansible_hostname }}_file state=touch
when: (ansible_hostname == "nfs") or (ansible_hostname == "backup")
#系統為centos的主機才會執行
- name: Centos Install httpd
yum: name=httpd state=present
when: (ansible_distribution == "CentOS")
#系統為ubuntu的主機才會執行
- name: Ubuntu Install httpd
yum: name=httpd2 state=present
when: (ansible_distribution == "Ubuntu")
#playbook執行結果:
[root@m01 ~]# vim f6.yml
[root@m01 ~]# ansible-playbook f6.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [10.0.0.30]
TASK [Create File] ************************************************************************************************************************
skipping: [10.0.0.30] #主機名不匹配則跳過, 匹配則會進行創建文件
PLAY RECAP ********************************************************************************************************************************
10.0.0.30 : ok=1 changed=0 unreachable=0 failed=0
6.Playbook循環語句
1、標準循環使用場景-批量安裝軟件
[root@m01 ~]# cat f7.yml
---
- hosts: all
remote_user: root
tasks:
- name: Installed Pkg
yum: name={{ item }} state=present
with_items:
- wget
- tree
- lrzsz
#palybook執行結果
[root@m01 ~]# ansible-playbook f7.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [10.0.0.30]
TASK [Installed Pkg] **********************************************************************************************************************
ok: [10.0.0.30] => (item=[u'wget', u'tree', u'lrzsz'])
PLAY RECAP ********************************************************************************************************************************
10.0.0.30 : ok=2 changed=0 unreachable=0 failed=0
2、標準循環使用場景-批量創建用戶
[root@m01 ~]# cat f7.yml
- hosts: all
remote_user: root
tasks:
- name: Add Users
user: name={{ item.name }} groups={{ item.groups }} state=present
with_items:
- { name: 'testuser1', groups: 'bin' }
- { name: 'testuser2', groups: 'root' }
#palybook執行結果
[root@m01 ~]# ansible-playbook f7.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [10.0.0.30]
TASK [Add Users] **************************************************************************************************************************
changed: [10.0.0.30] => (item={u'name': u'testuser1', u'groups': u'bin'})
changed: [10.0.0.30] => (item={u'name': u'testuser2', u'groups': u'root'})
PLAY RECAP ********************************************************************************************************************************
10.0.0.30 : ok=2 changed=1 unreachable=0 failed=0
3、標準循環使用場景-拷貝多個目錄
[root@m01 ~]# cat f7.yml
- hosts: all
remote_user: root
tasks:
- name: Configure Rsync Server
copy: src={{ item.src }} dest=/etc/{{ item.dest }} mode={{ item.mode }}
with_items:
- {src: "rsyncd.conf", dest: "rsyncd.conf", mode: "0644"}
- {src: "rsync.passwd", dest: "rsync.passwd", mode: "0600"}
7.Playbook異常處理
默認Playbook會檢查命令和模塊的返回狀態,如遇到錯誤就中斷playbook的執行
加入參數: ignore_errors: yes 忽略錯誤
[root@m01 ~]# cat f9.yml
---
- hosts: all
remote_user: root
tasks:
- name: Ignore False
command: /bin/false
ignore_errors: yes
- name: touch new file
file: path=/tmp/weiaixiong_ignore state=touch
playbook過程中會跳過錯誤
[root@m01 ~]# ansible-playbook f9.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [10.0.0.30]
TASK [Ignore False] ***********************************************************************************************************************
fatal: [10.0.0.30]: FAILED! => {"changed": true, "cmd": ["/bin/false"], "delta": "0:00:00.002819", "end": "2018-11-13 07:22:47.301758", "msg": "non-zero return code", "rc": 1, "start": "2018-11-13 07:22:47.298939", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
...ignoring
TASK [touch new file] *********************************************************************************************************************
changed: [10.0.0.30]
PLAY RECAP ********************************************************************************************************************************
10.0.0.30 : ok=3 changed=2 unreachable=0 failed=0
8.Playbook tags標簽
1、打標簽
對一個對象打一個標簽
對一個對象打多個標簽
對多個對象打一個標簽
2、標簽使用,通過tags和任務對象進行捆綁,控制部分或者指定的task執行
-t: 執行指定的tag標簽任務
--skip-tags: 執行--skip-tags之外的標簽任務
[root@m01 ~]# cat f10.yml
---
- hosts: all
remote_user: root
tasks:
- name: Install Nfs Server
yum: name=nfs-utils state=present
tags:
- install_nfs
- install_nfs-server
- name: Service Nfs Server
service: name=nfs-server state=started enabled=yes
tags: start_nfs-server
#正常執行playbook
[root@m01 ~]# ansible-playbook f10.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [10.0.0.30]
TASK [Install Nfs Server] *****************************************************************************************************************
ok: [10.0.0.30]
TASK [Service Nfs Server] *****************************************************************************************************************
ok: [10.0.0.30]
PLAY RECAP ********************************************************************************************************************************
10.0.0.30 : ok=3 changed=0 unreachable=0 failed=0
使用-t指定tags執行, 多個tags使用逗號隔開即可
[root@manager ~]# ansible-playbook -t install_nfs-server f10.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [10.0.0.30]
TASK [Install Nfs Server] *****************************************************************************************************************
ok: [10.0.0.30]
PLAY RECAP ********************************************************************************************************************************
10.0.0.30 : ok=2 changed=0 unreachable=0 failed=0
使用--skip-tags排除不執行的tags
[root@m01 ~]# ansible-playbook --skip-tags install_nfs-server f10.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [10.0.0.30]
TASK [Service Nfs Server] *****************************************************************************************************************
ok: [10.0.0.30]
PLAY RECAP ********************************************************************************************************************************
10.0.0.30 : ok=2 changed=0 unreachable=0 failed=0
9.Playbook Handlers
playbook
安裝Apache
示例
[root@m01 ~]# cat webserver.yml
- hosts: web
remote_user: root
#1.定義變量,在配置文件中調用
vars:
http_port: 8881
#2.安裝httpd服務
tasks:
- name: Install Httpd Server
yum: name=httpd state=present
#3.使用template模板,引用上面vars定義的變量至配置文件中
- name: Configure Httpd Server
template: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf
notify: Restart Httpd Server
#4.啟動Httpd服務
- name: Start Httpd Server
service: name=httpd state=started enabled=yes
#5.檢查Httpd服務當前的運行的端口狀態
- name: Get Httpd Server Port
shell: netstat -lntp|grep httpd
register: Httpd_Port
#6.輸出Httpd運行的狀態至面板
- name: Out Httpd Server Status
debug: msg={{ Httpd_Port.stdout_lines }}
ignore_errors: yes
#7.如果配置文件發生變化會調用該handlers下面的模塊
handlers:
- name: Restart Httpd Server
service: name=httpd state=restarted
#handlers注意事項:
1.無論多少個task通知了相同的handlers,handlers僅會在所有tasks結束后運行一次。
2.只有task發生改變了才會通知handlers,沒有改變則不會觸發handlers
3.不能使用handlers替代tasks、因為handlers是一個特殊的tasks。
10.Playbook Include
include用來動態的包含tasks任務列表,include_tasks新版/include老版
include調用任務方式
#主入口文件
[root@m01~]# cat main.yml
- hosts: all
remote_user: root
tasks:
- include_tasks: f20.yml
- include_tasks: f21.yml
#f20.yml
[root@m01 ~]# cat f20.yml
- name: create file1
command: touch file1
#21.yml
[root@m01 ~]# cat f21.yml
- name: create file2
command: touch file2
11.playbook_import
#導入一個完整的playbook文件 (play task)
[root@m01 project1]# cat tasks_total.yml
- import_playbook: ./tasks_1.yml
- import_playbook: ./tasks_2.yml
12.template之for if
通過使用for,if可以更加靈活的生成配置文件等需求,還可以在里面根據各種條件進行判斷,然后生成不同的配置文件、或者服務器配置相關等。
示例1
1)編寫playbook
# template for 示例 ---
- hosts: all
remote_user: root
vars:
nginx_vhost_port: - 81
- 82
- 83
tasks:
- name: Templage Nginx Config
template: src=nginx.conf.j2 dest=/tmp/nginx_test.conf
2)模板文件編寫
# 循環playbook文件中定義的變量,依次賦值給port
[root@m01 PlayBook]# cat templates/nginx.conf.j2
{% for port in nginx_vhost_port %}
server{
listen: {{ port }};
server_name: localhost;
}
{% endfor %}
3)執行playbook
并查看生成結果
[root@m01 PlayBook]# ansible-playbook testfor01.yml
# 去到一個節點看下生成的結果發現自動生成了三個虛擬主機
[root@linux ~]# cat /tmp/nginx_test.conf
server{
listen: 81;
server_name: localhost;
}
server{
listen: 82;
server_name: localhost;
}
server{
listen: 83;
server_name: localhost;
}
示例2
1)編寫playbook
[root@m01 PlayBook]# cat testfor02.yml
# template for 示例 ---
- hosts: all
remote_user: root
vars:
nginx_vhosts: - web1:
listen: 8081 server_name: "web1.example.com" root: "/var/www/nginx/web1"
- web2:
listen: 8082 server_name: "web2.example.com" root: "/var/www/nginx/web2"
- web3:
listen: 8083 server_name: "web3.example.com" root: "/var/www/nginx/web3" tasks: - name: Templage Nginx Config
template: src=nginx.conf.j2 dest=/tmp/nginx_vhost.conf
2)模板文件編寫
[root@m01 PlayBook]# cat templates/nginx.conf.j2
{% for vhost in nginx_vhosts %}
server{
listen: {{ vhost.listen }};
server_name: {{ vhost.server_name }};
root: {{ vhost.root }};
}
{% endfor %}
3)執行playbook并查看生成結果
[root@m01 PlayBook]# ansible-playbook testfor02.yml
# 去到一個節點看下生成的結果發現自動生成了三個虛擬主機
[root@linux ~]# cat /tmp/nginx_vhost.conf
server{
listen: 8081;
server_name: web1.example.com;
root: /var/www/nginx/web1;
}
server{
listen: 8082;
server_name: web2.example.com;
root: /var/www/nginx/web2;
}
server{
listen: 8083;
server_name: web3.example.com;
root: /var/www/nginx/web3;
}
示例3
在for循環中再嵌套if判斷,讓生成的配置文件更加靈活
1)編寫playbook
[root@m01 PlayBook]# cat testfor03.yml
# template for 示例 ---
- hosts: all
remote_user: root
vars:
nginx_vhosts: - web1:
listen: 8081 root: "/var/www/nginx/web1"
- web2:
server_name: "web2.example.com" root: "/var/www/nginx/web2"
- web3:
listen: 8083 server_name: "web3.example.com" root: "/var/www/nginx/web3" tasks: - name: Templage Nginx Config
template: src=nginx.conf.j2 dest=/tmp/nginx_vhost.conf
2)模板文件編寫
# 說明:這里添加了判斷,如果listen沒有定義的話,默認端口使用8888,如果server_name有定義,那么生成的配置文件中才有這一項。
[root@m01 PlayBook]# cat templates/nginx.conf.j2
{% for vhost in nginx_vhosts %}
server{
{% if vhost.listen is defined %}
listen: {{ vhost.listen }};
{% else %}
listen: 8888;
{% endif %}
{% if vhost.server_name is defined %}
server_name: {{ vhost.server_name }};
{% endif %}
root: {{ vhost.root }};
}
{% endfor %}
3)執行playbook
并查看生成結果
[root@m01 PlayBook]# ansible-playbook testfor03.yml
# 去到一個節點看下生成的結果發現自動生成了三個虛擬主機
[root@linux ~]# cat /tmp/nginx_vhost.conf
server{
listen: 8081;
root: /var/www/nginx/web1;
}
server{
listen: 8888;
serverb2.example.com;
root: /var/www/nginx/web2;
}
server{
listen: 8083;
server_name: web3.example.com;
root: /var/www/nginx/web3;
}
上面三個示例的圖片展示效果
例一
例二
例三