目錄
十五、ansible介紹
十六、ansible安裝
十七、ansible遠程執行命令
十八、ansible拷貝文件或目錄
十九、ansible遠程執行腳本
二十、ansible管理任務計劃
二十一、ansible安裝包和管理服務
二十二、使用ansible playbook
二十三、playbook里的變量
二十四、playbook循環
二十五、playbook中的條件判斷
二十六、playbook中的handlers
二十七、用playbook安裝nginx
二十八、playbook管理配置文件
十五、ansible介紹
不需要安裝客戶端,通過sshd去通信
基于模塊工作,模塊可以由任何語言開發
不僅支持命令行使用模塊,也支持編寫yaml格式的playbook,易于編寫和閱讀
安裝十分簡單,centos上可直接yum安裝
有提供UI(瀏覽器圖形化)www.ansible.com/tower,收費的
官方文檔 http://docs.ansible.com/ansible/latest/index.html
ansible已經被redhat公司收購,它在github上是一個非常受歡迎的開源軟件,github地址https://github.com/ansible/ansible
一本不錯的入門電子書 https://ansible-book.gitbooks.io/ansible-first-book/
十六、ansible安裝
準備兩臺機器,前面我們做實驗的兩臺機器minglinux-01,minglinux-02
只需要在minglinux-01上安裝ansible
yum list |grep ansible 可以看到自帶源里就有ansible
yum install -y ansible
minglinux-01上生成密鑰對 ssh-keygen -t rsa
把公鑰放到minglinux-02上,設置密鑰認證
同時對本機也設置密鑰認證
vim /etc/ansible/hosts //增加
[testhost]
127.0.0.1
192.168.162.132
說明: testhost為主機組名字,自定義的。 下面兩個ip為組內的機器ip。
[root@minglinux-01 /srv/salt] yum list |grep ansible |head -2
ansible.noarch 2.7.8-1.el7 @epel
ansible-doc.noarch 2.7.8-1.el7 @epel
[root@minglinux-01 /srv/salt] yum install -y ansible ansible-doc
#查看minglinux-01上生成的公鑰,進行設置密鑰認證
[root@minglinux-01 /srv/salt] ls /root/.ssh/
authorized_keys id_rsa id_rsa.pub known_hosts
[root@minglinux-01 /srv/salt] cat /root/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLqBZ25bFoIDOLbZxWH54H2VWnkTXKf7lDC9vdCBN9C7ryA4Rb+iTp9Lzk1AJxy++Zu97nndhACxdLPLs0A4j90yoXBkZ07QNZl2PGqWFZB0mMMvwG24MUsYk+3POG1n+nY4l6J7U//XVJWHfic+WD/1+Y2mLo+zWALTHA2pV/ebcuRxE5AIWAbzTas3vSDbkHgcDEQxMJRa+nltVOald+wt4O/H1Ic8nbbwPbAvJlotxm3x59D8ul8HnmOiT4FqzngIOoijjUmyouUFJzCIQf+UZKgA1GiXDZ1ap5wq1PMp8XFJpUuuF+nVs5M86TBJ54kxD4eq+bDAJ4jOUR2s57 root@minglinux-01
#對本機設置密鑰認證
[root@minglinux-01 ~] cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
[root@minglinux-01 ~] cat .ssh/authorized_keys
···
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLqBZ25bFoIDOLbZxWH54H2VWnkTXKf7lDC9vdCBN9C7ryA4Rb+iTp9Lzk1AJxy++Zu97nndhACxdLPLs0A4j90yoXBkZ07QNZl2PGqWFZB0mMMvwG24MUsYk+3POG1n+nY4l6J7U//XVJWHfic+WD/1+Y2mLo+zWALTHA2pV/ebcuRxE5AIWAbzTas3vSDbkHgcDEQxMJRa+nltVOald+wt4O/H1Ic8nbbwPbAvJlotxm3x59D8ul8HnmOiT4FqzngIOoijjUmyouUFJzCIQf+UZKgA1GiXDZ1ap5wq1PMp8XFJpUuuF+nVs5M86TBJ54kxD4eq+bDAJ4jOUR2s57 root@minglinux-01
[root@minglinux-01 ~] ssh minglinux-01
Last login: Tue Mar 12 16:35:13 2019 from minglinux-01
[root@minglinux-01 ~] w
19:59:20 up 6:27, 2 users, load average: 0.00, 0.02, 0.05
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 192.168.162.1 13:34 0.00s 0.91s 0.02s ssh minglinux-01
root pts/1 minglinux-01 19:59 0.00s 0.05s 0.01s w
#設置minglinux-02的密鑰認證
[root@minglinux-02 ~] cat /root/.ssh/authorized_keys
···
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLqBZ25bFoIDOLbZxWH54H2VWnkTXKf7lDC9vdCBN9C7ryA4Rb+iTp9Lzk1AJxy++Zu97nndhACxdLPLs0A4j90yoXBkZ07QNZl2PGqWFZB0mMMvwG24MUsYk+3POG1n+nY4l6J7U//XVJWHfic+WD/1+Y2mLo+zWALTHA2pV/ebcuRxE5AIWAbzTas3vSDbkHgcDEQxMJRa+nltVOald+wt4O/H1Ic8nbbwPbAvJlotxm3x59D8ul8HnmOiT4FqzngIOoijjUmyouUFJzCIQf+UZKgA1GiXDZ1ap5wq1PMp8XFJpUuuF+nVs5M86TBJ54kxD4eq+bDAJ4jOUR2s57 root@minglinux-01
[root@minglinux-01 /srv/salt] ssh minglinux-02
Last login: Tue Mar 12 16:35:26 2019 from minglinux-01
#設置主機組
[root@minglinux-01 ~] vim /etc/ansible/hosts
#寫入以下內容
25 [testhost]
26 127.0.0.1
27 minglinux-02
#testhost為自定義主機組名字。 下面兩個ip為組內的機器ip。
十七、ansible遠程執行命令
ansible testhost -m command -a 'w'
這樣就可以批量執行命令了。這里的testhost 為主機組名,-m后邊是模塊名字,-a后面是命令。當然我們也可以直接寫一個ip,針對某一臺機器來執行命令。
ansible 127.0.0.1 -m command -a 'hostname'
錯誤: "msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"
解決: yum install -y libselinux-python
還有一個模塊就是shell同樣也可以實現
ansible testhost -m shell -a 'w'
[root@minglinux-01 ~] ansible testhost -m command -a 'w'
127.0.0.1 | CHANGED | rc=0 >>
21:47:32 up 8:15, 2 users, load average: 0.03, 0.06, 0.05
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 192.168.162.1 13:34 4.00s 3.72s 0.01s ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/1ad903f8ab -tt 192.168.162.132 /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-1552398450.92-236475746352593/AnsiballZ_command.py && sleep 0'
root pts/3 localhost 21:47 1.00s 0.29s 0.02s w
192.168.162.132 | CHANGED | rc=0 >>
21:47:59 up 8:15, 2 users, load average: 0.00, 0.01, 0.05
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 192.168.162.1 21:34 ? 0.17s 0.17s -bash
root pts/1 minglinux-01 21:47 1.00s 0.44s 0.01s w
[root@minglinux-01 ~] ansible testhost -m command -a 'hostname'
127.0.0.1 | CHANGED | rc=0 >>
minglinux-01
192.168.162.132 | CHANGED | rc=0 >>
minglinux-02
#僅針對一臺機器
[root@minglinux-01 ~] ansible minglinux-02 -m command -a 'hostname'
minglinux-02 | CHANGED | rc=0 >>
minglinux-02
# 還有一個模塊就是shell同樣也可以實現
[root@minglinux-01 ~] ansible testhost -m shell -a 'hostname'
192.168.162.132 | CHANGED | rc=0 >>
minglinux-02
127.0.0.1 | CHANGED | rc=0 >>
minglinux-01
十八、ansible拷貝文件或目錄
ansible minglinux-02 -m copy -a "src=/etc/ansible dest=/tmp/ansible_test owner=root group=root mode=0755"
注意:源目錄會放到目標目錄下面去,如果目標指定的目錄不存在,它會自動創建。如果拷貝的是文件,dest指定的名字和源如果不同,并且它不是已經存在的目錄,相當于拷貝過去后又重命名。但相反,如果desc是目標機器上已經存在的目錄,則會直接把文件拷貝到該目錄下面。
ansible testhost -m copy -a "src=/etc/passwd dest=/tmp/123"
這里的/tmp/123和源機器上的/etc/passwd是一致的,但如果目標機器上已經有/tmp/123目錄,則會再/tmp/123目錄下面建立passwd文件
#對目錄的操作
[root@minglinux-01 ~] ansible minglinux-02 -m copy -a "src=/etc/ansible dest=/tmp/ansible_test owner=root group=root mode=0755"
minglinux-02 | CHANGED => {
"changed": true,
"dest": "/tmp/ansible_test/",
"src": "/etc/ansible"
}
#minglinux-02可以看到目標目錄被創建且源目錄在目標目錄下面
[root@minglinux-02 ~] ls -l /tmp/ansible_test
總用量 0
drwxr-xr-x 3 root root 51 3月 12 22:08 ansible
#對文件的操作
[root@minglinux-01 ~] ansible minglinux-02 -m copy -a "src=/etc/passwd dest=/tmp/123"
[root@minglinux-02 ~] ls -l /tmp/123/passwd
-rw-r--r-- 1 root root 1754 3月 12 22:15 /tmp/123/passwd
#因為目標機器上已經有/tmp/123目錄,則會在/tmp/123目錄下面建立passwd文件
[root@minglinux-01 ~] ansible minglinux-02 -m copy -a "src=/etc/passwd dest=/tmp/1.txt"
[root@minglinux-02 ~] ls -l /tmp/1.txt
-rw-r--r-- 1 root root 1754 3月 12 22:19 /tmp/1.txt
#這里1.txt就是passwd文件
#操作時要看src和dest是文件還是目錄
十九、ansible遠程執行腳本
首先創建一個shell腳本
vim /tmp/1.sh //加入內容
#!/bin/bash
echo `date` > /tmp/ansible_test.txt
然后把該腳本分發到各個機器上
ansible testhost -m copy -a "src=/tmp/1.sh dest=/tmp/1.sh mode=0755"
最后是批量執行該shell腳本
ansible testhost -m shell -a "/tmp/1.sh"
shell模塊,還支持遠程執行命令并且帶管道
ansible testhost -m shell -a "cat /etc/passwd|wc -l "
[root@minglinux-01 ~] vim /tmp/1.sh
#腳本內容如下
1 #!/bin/bash
2 echo `date` > /tmp/ansible_test.txt
#把該腳本分發到各個機器上
[root@minglinux-01 ~] ansible testhost -m copy -a "src=/tmp/1.sh dest=/tmp/test.sh mode=0755"
minglinux-02 | CHANGED => {
"changed": true,
"checksum": "8b98a2723b00c97e5e8bee4625a90f17925bee43",
"dest": "/tmp/test.sh",
"gid": 0,
"group": "root",
"md5sum": "fff8aec86bb38a5bf14d5a878664abc0",
"mode": "0755",
"owner": "root",
"size": 51,
"src": "/root/.ansible/tmp/ansible-tmp-1552400956.53-228457569305656/source",
"state": "file",
"uid": 0
}
127.0.0.1 | CHANGED => {
"changed": true,
"checksum": "8b98a2723b00c97e5e8bee4625a90f17925bee43",
"dest": "/tmp/test.sh",
"gid": 0,
"group": "root",
"md5sum": "fff8aec86bb38a5bf14d5a878664abc0",
"mode": "0755",
"owner": "root",
"size": 51,
"src": "/root/.ansible/tmp/ansible-tmp-1552400956.51-98771450695458/source",
"state": "file",
"uid": 0
}
[root@minglinux-01 ~] ls /tmp/test.sh
/tmp/test.sh
[root@minglinux-01 ~] cat !$
cat /tmp/test.sh
#!/bin/bash
echo `date` > /tmp/ansible_test.txt
#批量執行該shell腳本
[root@minglinux-01 ~] ansible testhost -m shell -a "/tmp/test.sh"
minglinux-02 | CHANGED | rc=0 >>
127.0.0.1 | CHANGED | rc=0 >>
#腳本遠程執行成功
[root@minglinux-01 ~] ls /tmp/ansible_test.txt
/tmp/ansible_test.txt
[root@minglinux-01 ~] cat !$
cat /tmp/ansible_test.txt
2019年 03月 12日 星期二 22:31:47 CST
[root@minglinux-02 ~] ls /tmp/ansible_test.txt
/tmp/ansible_test.txt
[root@minglinux-02 ~] cat !$
cat /tmp/ansible_test.txt
2019年 03月 12日 星期二 22:32:14 CST
#shell模塊,還支持遠程執行命令并且帶管道,而command模塊是不支持帶管道的
[root@minglinux-01 ~] ansible testhost -m shell -a "cat /etc/passwd|wc -l"
minglinux-02 | CHANGED | rc=0 >>
30
127.0.0.1 | CHANGED | rc=0 >>
36
[root@minglinux-01 ~] ansible testhost -m command -a "cat /etc/passwd|wc -l"
minglinux-02 | FAILED | rc=1 >>
cat:無效選項 -- l
Try 'cat --help' for more information.non-zero return code
127.0.0.1 | FAILED | rc=1 >>
cat:無效選項 -- l
Try 'cat --help' for more information.non-zero return code
二十、ansible管理任務計劃
ansible testhost -m cron -a "name='test cron' job='/bin/touch /tmp/1212.txt' weekday=6"
若要刪除該cron 只需要加一個字段 state=absent
ansible testhost -m cron -a "name='test cron' state=absent"
其他的時間表示:分鐘 minute 小時 hour 日期 day 月份 month
#使用cron模塊創建計劃任務
[root@minglinux-01 ~] ansible minglinux-02 -m cron -a "name='test cron' job='/bin/touch /tmp/121.txt' weekday=6"
minglinux-02 | CHANGED => {
"changed": true,
"envs": [],
"jobs": [
"test cron"
]
}
#查看任務計劃
[root@minglinux-02 ~] crontab -l
# Lines below here are managed by Salt, do not edit
#Ansible: test cron
* * * * 6 /bin/touch /tmp/121.txt
#刪除任務計劃
[root@minglinux-01 ~] ansible minglinux-02 -m cron -a "name='test cron' state=absent"
minglinux-02 | CHANGED => {
"changed": true,
"envs": [],
"jobs": []
}
#再次查看任務計劃
[root@minglinux-02 ~] crontab -l
# Lines below here are managed by Salt, do not edit
[root@minglinux-02 ~] crontab -e #把那行給刪除了
crontab: installing new crontab
[root@minglinux-02 ~] crontab -l
#crontab文件中的內容不要手動更改,否則會導致使用ansible無法繼續操作
二十一、ansible安裝包和管理服務
ansible testhost -m yum -a "name=httpd"
在name后面還可以加上state=installed/removed
ansible testhost -m service -a "name=httpd state=started enabled=yes"
這里的name是centos系統里的服務名,可以通過chkconfig --list查到。
Ansible文檔的使用
ansible-doc -l 列出所有的模塊
ansible-doc cron 查看指定模塊的文檔
#因為02機器已經安裝了httpd,所以這里先執行卸載命令
[root@minglinux-01 ~] ansible minglinux-02 -m yum -a "name=httpd state=removed"
[root@minglinux-02 ~] rpm -qa httpd
#重新安裝,耗時可能較久
[root@minglinux-01 ~] ansible minglinux-02 -m yum -a "name=httpd state=installed"
[root@minglinux-02 ~] rpm -qa httpd
httpd-2.4.6-88.el7.centos.x86_64
#遠程啟動httpd
[root@minglinux-01 ~] ansible minglinux-02 -m service -a "name=httpd state=started enabled=no"
[root@minglinux-02 ~] ps aux |grep httpd
root 17984 0.1 0.2 224052 5004 ? Ss 23:16 0:00 /usr/sbin/httpd -DFOREGROUND
apache 17985 0.0 0.1 224052 2952 ? S 23:16 0:00 /usr/sbin/httpd -DFOREGROUND
apache 17986 0.0 0.1 224052 2952 ? S 23:16 0:00 /usr/sbin/httpd -DFOREGROUND
apache 17987 0.0 0.1 224052 2952 ? S 23:16 0:00 /usr/sbin/httpd -DFOREGROUND
apache 17988 0.0 0.1 224052 2952 ? S 23:16 0:00 /usr/sbin/httpd -DFOREGROUND
apache 17989 0.0 0.1 224052 2952 ? S 23:16 0:00 /usr/sbin/httpd -DFOREGROUND
root 18017 0.0 0.0 112720 984 pts/0 S+ 23:17 0:00 grep --color=auto httpd
#Ansible文檔的使用
[root@minglinux-01 ~] ansible-doc -l #列出所有的模塊
[root@minglinux-01 ~] ansible-doc cron #查看指定模塊的文檔
[root@minglinux-01 ~] ansible-doc shell
二十二、使用ansible playbook
相當于把模塊寫入到配置文件里面,例:
vi /etc/ansible/test.yml //加入如下內容
---
- hosts: minglinux-02
remote_user: root
tasks:
- name: test_playbook
shell: touch /tmp/hello.txt
說明: 第一行需要有三個杠,hosts參數指定了對哪些主機進行參作,如果是多臺機器可以用逗號作為分隔,也可以使用主機組,在/etc/ansible/hosts里定義;
user參數指定了使用什么用戶登錄遠程主機操作;
tasks指定了一個任務,其下面的name參數同樣是對任務的描述,在執行過程中會打印出來,shell是ansible模塊名字
執行:ansible-playbook test.yml
[root@minglinux-01 ~] vim /etc/ansible/test.yml
1 ---
2 - hosts: minglinux-02
3 remote_user: root
4 tasks:
5 - name: test_playbook
6 shell: touch /tmp/hello.txt
#執行
[root@minglinux-01 ~] ansible-playbook /etc/ansible/test.yml
_____________________
< PLAY [minglinux-02] >
---------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
________________________
< TASK [Gathering Facts] >
------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [minglinux-02]
______________________
< TASK [test_playbook] >
----------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
[WARNING]: Consider using the file module with state=touch rather than running 'touch'. If you need
to use command because file is insufficient you can add 'warn: false' to this command task or set
'command_warnings=False' in ansible.cfg to get rid of this message.
changed: [minglinux-02]
____________
< PLAY RECAP >
------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
minglinux-02 : ok=2 changed=1 unreachable=0 failed=0
[root@minglinux-02 ~] ls /tmp/hello.txt
/tmp/hello.txt #有了
[root@minglinux-02 ~] ll !$
ll /tmp/hello.txt
-rw-r--r-- 1 root root 0 3月 12 23:36 /tmp/hello.txt
二十三、playbook里的變量
再來一個創建用戶的例子:
vi /etc/ansible/create_user.yml //加入如下內容
---
- name: create_user
hosts: minglinux-02
user: root
gather_facts: false
vars:
- user: "test"
tasks:
- name: create user
user: name="{{ user }}"
說明:name參數對該playbook實現的功能做一個概述,后面執行過程中,會打印 name變量的值 ,可以省略;gather_facts參數指定了在以下任務部分執行前,是否先執行setup模塊獲取主機相關信息,這在后面的task會使用到setup獲取的信息時用到;vars參數,指定了變量,這里指字一個user變量,其值為test ,需要注意的是,變量值一定要用引號引住;user提定了調用user模塊,name是user模塊里的一個參數,而增加的用戶名字調用了上面user變量的值。
[root@minglinux-01 ~] vim /etc/ansible/create_user.yml
#加入如下內容
1 ---
2 - name: create_user
3 hosts: minglinux-02
4 user: root
5 gather_facts: false
6 vars:
7 - user: "test"
8 tasks:
9 - name: create user
10 user: name="{{ user }}"
[root@minglinux-01 ~] ansible-playbook /etc/ansible/create_user.yml
____________________
< PLAY [create_user] >
--------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
____________________
< TASK [create user] >
--------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
____________
< PLAY RECAP >
------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
minglinux-02 : ok=1 changed=1 unreachable=0 failed=0
#查看創建的用戶
[root@minglinux-02 ~] id test
uid=1002(test) gid=1002(test) 組=1002(test)
#如果用戶已創建,運行該操作是changed=0
[root@minglinux-01 ~] ansible-playbook /etc/ansible/create_user.yml
···
minglinux-02 : ok=1 changed=0 unreachable=0 failed=0
二十四、playbook循環
vi /etc/ansible/while.yml //加入如下內容
---
- hosts: testhost
user: root
tasks:
- name: change mode for files
file: path=/tmp/{{ item }} mode=600
with_items:
- 1.txt
- 2.txt
- 3.txt
說明: with_items為循環的對象
執行 ansible-playbook while.yml
[root@minglinux-01 ~] vim /etc/ansible/while.yml
#加入如下內容,創建文件并改權限,循環三次
1 ---
2 - hosts: minglinux-02
3 user: root
4 tasks:
5 - name: change mode for files
6 file: path=/tmp/{{ item }} state=touch mode=600
7 with_items:
8 - 1.txt
9 - 2.txt
10 - 3.txt
#執行
[root@minglinux-01 ~] ansible-playbook /etc/ansible/while.yml
_____________________
< PLAY [minglinux-02] >
---------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
________________________
< TASK [Gathering Facts] >
------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [minglinux-02]
______________________________
< TASK [change mode for files] >
------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02] => (item=1.txt)
changed: [minglinux-02] => (item=2.txt)
changed: [minglinux-02] => (item=3.txt)
____________
< PLAY RECAP >
------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
minglinux-02 : ok=2 changed=1 unreachable=0 failed=0
#禁用Gathering Facts效率更高
[root@minglinux-02 ~] ll /tmp/*.txt
-rw-r--r-- 1 root root 0 3月 12 23:55 /tmp/111.txt
-rw-r--r-- 1 root root 1754 3月 12 23:47 /tmp/123.txt
-rw------- 1 root root 0 3月 13 00:17 /tmp/1.txt
-rw------- 1 root root 0 3月 13 00:17 /tmp/2.txt
-rw------- 1 root root 0 3月 13 00:17 /tmp/3.txt
-rw-r--r-- 1 root root 43 3月 12 22:32 /tmp/ansible_test.txt
-rw-r--r-- 1 root root 0 3月 12 23:36 /tmp/hello.txt
二十五、playbook中的條件判斷
vi /etc/ansible/when.yml //加入如下內容
---
- hosts: minglinux-02
user: root
gather_facts: True
tasks:
- name: use when
shell: touch /tmp/when.txt
when: ansible_ens33.ipv4.address == "192.168.162.132“
說明:ansible aming-02 -m setup 可以查看到所有的facter信息
[root@minglinux-01 ~] vim /etc/ansible/when.yml
1 ---
2 - hosts: minglinux-02
3 user: root
4 gather_facts: True
5 tasks:
6 - name: use when
7 shell: touch /tmp/when.txt
8 when: ansible_ens33.ipv4.address == "192.168.162.132" #條件選擇,只有02機器才會執行
#執行
[root@minglinux-01 ~] ansible minglinux-02 -m setup #可以查看到所有的facter信息
[root@minglinux-01 ~] ansible-playbook /etc/ansible/when.yml
_____________________
< PLAY [minglinux-02] >
---------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
________________________
< TASK [Gathering Facts] >
------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [minglinux-02]
_________________
< TASK [use when] >
-----------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
[WARNING]: Consider using the file module with state=touch rather than running 'touch'. If you need
to use command because file is insufficient you can add 'warn: false' to this command task or set
'command_warnings=False' in ansible.cfg to get rid of this message.
changed: [minglinux-02]
____________
< PLAY RECAP >
------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
minglinux-02 : ok=2 changed=1 unreachable=0 failed=0
#查看文件
[root@minglinux-02 ~] ls /tmp/when.txt
/tmp/when.txt
[root@minglinux-02 ~] ll !$
ll /tmp/when.txt
-rw-r--r-- 1 root root 0 3月 13 00:38 /tmp/when.txt
二十六、playbook中的handlers
執行task之后,服務器發生變化之后要執行的一些操作,比如我們修改了配置文件后,需要重啟一下服務
vi /etc/ansible/handlers.yml//加入如下內容
---
- name: handlers test
hosts: minglinux-02
user: root
tasks:
- name: copy file
copy: src=/etc/passwd dest=/tmp/aaa.txt
notify: test handlers
handlers:
- name: test handlers
shell: echo "111111" >> /tmp/aaa.txt
說明,只有copy模塊真正執行后,才會去調用下面的handlers相關的操作。這種比較適合配置文件發生更改后,重啟服務的操作。
[root@minglinux-01 ~] vim /etc/ansible/handlers.yml
#寫入以下內容
1 ---
2 - name: handlers test
3 hosts: minglinux-02
4 user: root
5 tasks:
6 - name: copy file
7 copy: src=/etc/passwd dest=/tmp/aaa.txt
8 notify: test handlers
9 handlers:
10 - name: test handlers
11 shell: echo "111111" >> /tmp/aaa.txt
#執行
[root@minglinux-01 ~] ansible-playbook /etc/ansible/handlers.yml
______________________
< PLAY [handlers test] >
----------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
________________________
< TASK [Gathering Facts] >
------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [minglinux-02]
__________________
< TASK [copy file] >
------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
_________________________________
< RUNNING HANDLER [test handlers] >
---------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
____________
< PLAY RECAP >
------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
minglinux-02 : ok=3 changed=2 unreachable=0 failed=0
#查看執行后效果
[root@minglinux-02 ~] ls /tmp/aaa.txt
/tmp/aaa.txt
[root@minglinux-02 ~] cat /tmp/aaa.txt | tail -5
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
zabbix:x:998:995:Zabbix Monitoring System:/var/lib/zabbix:/sbin/nologin
memcached:x:997:994:Memcached daemon:/run/memcached:/sbin/nologin
mongod:x:996:993:mongod:/var/lib/mongo:/bin/false
111111
二十七、用playbook安裝nginx
- playbook實戰-nginx安裝1
思路:先在一臺機器上編譯安裝好nginx、打包,然后再用ansible去下發
cd /etc/ansible 進入ansible配置文件目錄
mkdir nginx_install 創建一個nginx_install的目錄,方便管理
cd nginx_install
mkdir -p roles/{common,install}/{handlers,files,meta,tasks,templates,vars}
說明:roles目錄下有兩個角色,common為一些準備操作,install為安裝nginx的操作。每個角色下面又有幾個目錄,handlers下面是當發生改變時要執行的操作,通常用在配置文件發生改變,重啟服務。files為安裝時用到的一些文件,meta為說明信息,說明角色依賴等信息,tasks里面是核心的配置文件,templates通常存一些配置文件,啟動腳本等模板文件,vars下為定義的變量
[root@minglinux-01 ~] cd /etc/ansible
[root@minglinux-01 /etc/ansible] mkdir nginx_install
[root@minglinux-01 /etc/ansible] cd nginx_install/
[root@minglinux-01 /etc/ansible/nginx_install] mkdir -p roles/{common,install}/{handlers,files,meta,tasks,templates,vars}
[root@minglinux-01 /etc/ansible/nginx_install] ls
roles
[root@minglinux-01 /etc/ansible/nginx_install] ls roles/
common install
[root@minglinux-01 /etc/ansible/nginx_install] ls roles/common/
files handlers meta tasks templates vars
[root@minglinux-01 /etc/ansible/nginx_install] ls roles/install/
files handlers meta tasks templates vars
- playbook實戰-nginx安裝2
需要事先準備好安裝用到的文件,具體如下:
在一臺機器上事先編譯安裝好nginx,配置好啟動腳本,配置好配置文件
安裝好后,我們需要把nginx目錄打包,并放到/etc/ansible/nginx_install/roles/install/files/下面,名字為nginx.tar.gz
啟動腳本、配置文件都要放到/etc/ansible/nginx_install/roles/install/templates下面
cd /etc/ansible/nginx_install/roles
定義common的tasks,nginx是需要一些依賴包的
vim ./common/tasks/main.yml //內容如下
- name: Install initializtion require software
yum: name={{ item }} state=installed
with_items:
- zlib-devel
- pcre-devel
[root@minglinux-01 /etc/ansible/nginx_install] ls /usr/local/nginx/ #nginx目錄
client_body_temp conf fastcgi_temp html logs proxy_temp sbin scgi_temp uwsgi_temp
[root@minglinux-01 /etc/ansible/nginx_install] ls /etc/init.d/nginx #啟動腳本
/etc/init.d/nginx
[root@minglinux-01 /etc/ansible/nginx_install] ls /usr/local/nginx/conf/nginx.conf #配置文件
/usr/local/nginx/conf/nginx.conf
#把nginx目錄打包
[root@minglinux-01 /usr/local] tar czvf nginx.tar.gz --exclude "nginx.conf" --exclude "vhost" nginx/
[root@minglinux-01 /usr/local] mv nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
[root@minglinux-01 /usr/local] cp nginx/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/
[root@minglinux-01 /usr/local] cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/templates/
#定義common的tasks,安裝nginx需要的一些依賴包
[root@minglinux-01 /usr/local] cd /etc/ansible/nginx_install/roles
[root@minglinux-01 ~] vim /etc/ansible/nginx_install/roles/common/tasks/main.yml
#寫入以下內容
1 - name: Install initializtion require software
2 yum: name={{ item }} state=installed
3 with_items:
4 - zlib-devel
5 - pcre-devel
- playbook實戰-nginx安裝3
定義變量
vim /etc/ansible/nginx_install/roles/install/vars/main.yml //內容如下
nginx_user: www
nginx_port: 80
nginx_basedir: /usr/local/nginx
首先要把所有用到的文檔拷貝到目標機器
vim /etc/ansible/nginx_install/roles/install/tasks/copy.yml //內容如下
- name: Copy Nginx Software
copy: src=nginx.tar.gz dest=/tmp/nginx.tar.gz owner=root group=root
- name: Uncompression Nginx Software
shell: tar zxf /tmp/nginx.tar.gz -C /usr/local/
- name: Copy Nginx Start Script
template: src=nginx dest=/etc/init.d/nginx owner=root group=root mode=0755
- name: Copy Nginx Config
template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644
#定義一些變量
[root@minglinux-01 ~] vim /etc/ansible/nginx_install/roles/install/vars/main.yml
#內容如下
1 nginx_user: www
2 nginx_port: 80
3 nginx_basedir: /usr/local/nginx
#創建配置文件用于拷貝文件到目標機器
[root@minglinux-01 ~] vim /etc/ansible/nginx_install/roles/install/tasks/copy.yml
#內容如下
1 - name: Copy Nginx Software
2 copy: src=nginx.tar.gz dest=/tmp/nginx.tar.gz owner=root group=root
3 - name: Uncompression Nginx Software
4 shell: tar zxf /tmp/nginx.tar.gz -C /usr/local/
5 - name: Copy Nginx Start Script
6 template: src=nginx dest=/etc/init.d/nginx owner=root group=root mode=0755
7 - name: Copy Nginx Config
8 template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644
#src=nginx和src=nginx.conf去template里找文件
- playbook實戰-nginx安裝4
接下來會建立用戶,啟動服務,刪除壓縮包
vim /etc/ansible/nginx_install/roles/install/tasks/install.yml //內容如下
- name: Create Nginx User
user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin
- name: Start Nginx Service
shell: /etc/init.d/nginx start
- name: Add Boot Start Nginx Service
shell: chkconfig --level 345 nginx on
- name: Delete Nginx compression files
shell: rm -rf /tmp/nginx.tar.gz
#用于建立用戶,啟動服務,刪除壓縮包的配置文件
[root@minglinux-01 ~] vim /etc/ansible/nginx_install/roles/install/tasks/install.yml
#內容如下
1 - name: Create Nginx User
2 user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin
3 - name: Start Nginx Service
4 shell: /etc/init.d/nginx start
5 - name: Add Boot Start Nginx Service
6 shell: chkconfig --level 345 nginx on
7 - name: Delete Nginx compression files
8 shell: rm -rf /tmp/nginx.tar.gz
- playbook實戰-nginx安裝5
再創建main.yml把copy和install調用
vim /etc/ansible/nginx_install/roles/install/tasks/main.yml //內容如下
- include: copy.yml
- include: install.yml
到此兩個roles:common和install就定義完成了,接下來要定義一個入口配置文件
vim /etc/ansible/nginx_install/install.yml //內容如下
---
- hosts: minglinux-02
remote_user: root
gather_facts: True
roles:
- common
- install
執行: ansible-playbook /etc/ansible/nginx_install/install.yml
#創建main.yml把copy和install調用
[root@minglinux-01 ~] ls /etc/ansible/nginx_install/roles/install/tasks
copy.yml install.yml
[root@minglinux-01 ~] vim /etc/ansible/nginx_install/roles/install/tasks/main.yml
#內容如下
1 - include: copy.yml
2 - include: install.yml
#定義總入口配置文件
[root@minglinux-01 ~] vim /etc/ansible/nginx_install/install.yml
#內容如下
1 ---
2 - hosts: minglinux-02
3 remote_user: root
4 gather_facts: True
5 roles:
6 - common
7 - install
#執行,目標機器上先yum remove nginx
[root@minglinux-02 /usr/share/nginx/html] yum remove nginx
[root@minglinux-01 ~] ansible-playbook /etc/ansible/nginx_install/install.yml
_____________________
< PLAY [minglinux-02] >
---------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
________________________
< TASK [Gathering Facts] >
------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [minglinux-02]
________________________________________________________
< TASK [common : Install initializtion require software] >
--------------------------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated.
Instead of using a loop to supply multiple items and specifying `name: "{{ item }}"`, please use `name:
['zlib-devel', 'pcre-devel']` and remove the loop. This feature will be removed in version 2.11.
Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
ok: [minglinux-02] => (item=[u'zlib-devel', u'pcre-devel'])
______________________________________
< TASK [install : Copy Nginx Software] >
--------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
_______________________________________________
< TASK [install : Uncompression Nginx Software] >
-----------------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
[WARNING]: Consider using the unarchive module rather than running 'tar'. If you need to use command
because unarchive is insufficient you can add 'warn: false' to this command task or set
'command_warnings=False' in ansible.cfg to get rid of this message.
changed: [minglinux-02]
__________________________________________
< TASK [install : Copy Nginx Start Script] >
------------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
____________________________________
< TASK [install : Copy Nginx Config] >
------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
____________________________________
< TASK [install : Create Nginx User] >
------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
______________________________________
< TASK [install : Start Nginx Service] >
--------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
_______________________________________________
< TASK [install : Add Boot Start Nginx Service] >
-----------------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
_________________________________________________
< TASK [install : Delete Nginx compression files] >
-------------------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
[WARNING]: Consider using the file module with state=absent rather than running 'rm'. If you need to
use command because file is insufficient you can add 'warn: false' to this command task or set
'command_warnings=False' in ansible.cfg to get rid of this message.
changed: [minglinux-02]
____________
< PLAY RECAP >
------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
minglinux-02 : ok=10 changed=8 unreachable=0 failed=0
#minglinux-02上查看進程
[root@minglinux-02 /usr/share/nginx/html] ps aux|grep nginx
root 6729 0.0 0.0 45928 1096 ? Ss 03:19 0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nobody 6730 0.0 0.2 48416 3740 ? S 03:19 0:00 nginx: worker process
nobody 6731 0.0 0.2 48416 3740 ? S 03:19 0:00 nginx: worker process
root 7051 0.0 0.0 112720 980 pts/0 S+ 03:22 0:00 grep --color=auto nginx
二十八、playbook管理配置文件
- playbook管理配置文件1
生產環境中大多時候是需要管理配置文件的,安裝軟件包只是在初始化環境的時候用一下。下面我們來寫個管理nginx配置文件的playbook
mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
其中new為更新時用到的,old為回滾時用到的,files下面為nginx.conf和vhosts目錄,handlers為重啟nginx服務的命令
關于回滾,需要在執行playbook之前先備份一下舊的配置,所以對于老配置文件的管理一定要嚴格,千萬不能隨便去修改線上機器的配置,并且要保證new/files下面的配置和線上的配置一致
先把nginx.conf和vhosts目錄放到files目錄下面
cd /usr/local/nginx/conf/
cp -r nginx.conf vhost /etc/ansible/nginx_config/roles/new/files/
[root@minglinux-01 ~] mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
[root@minglinux-01 ~] cd /etc/ansible/nginx_config/
[root@minglinux-01 /etc/ansible/nginx_config] ls
roles
[root@minglinux-01 /etc/ansible/nginx_config] ls roles/
new old
#把nginx.conf和vhosts目錄放到files目錄下面
[root@minglinux-01 /etc/ansible/nginx_config] cd /usr/local/nginx/conf/
[root@minglinux-01 /usr/local/nginx/conf] cp -r nginx.conf vhost /etc/ansible/nginx_config/roles/new/files/
[root@minglinux-01 /usr/local/nginx/conf] ls /etc/ansible/nginx_config/roles/new/files/
nginx.conf vhost
- playbook管理配置文件2
vim /etc/ansible/nginx_config/roles/new/vars/main.yml //定義變量
nginx_basedir: /usr/local/nginx
vim /etc/ansible/nginx_config/roles/new/handlers/main.yml //定義重新加載nginx服務
- name: restart nginx
shell: /etc/init.d/nginx reload
vim /etc/ansible/nginx_config/roles/new/tasks/main.yml //這是核心的任務
- name: copy conf file
copy: src={{ item.src }} dest={{ nginx_basedir }}/{{ item.dest }} backup=yes owner=root group=root mode=0644
with_items:
- { src: nginx.conf, dest: conf/nginx.conf }
- { src: vhosts, dest: conf/ }
notify: restart nginx
#定義變量
[root@minglinux-01 ~] vim /etc/ansible/nginx_config/roles/new/vars/main.yml
#內容如下
1 nginx_basedir: /usr/local/nginx
#定義重新加載nginx服務
[root@minglinux-01 ~] vim /etc/ansible/nginx_config/roles/new/handlers/main.yml
#內容如下
1 - name: restart nginx
2 shell: /etc/init.d/nginx reload
#核心任務
[root@minglinux-01 ~] vim /etc/ansible/nginx_config/roles/new/tasks/main.yml
#內容如下
1 - name: copy conf file
2 copy: src={{ item.src }} dest={{ nginx_basedir }}/{{ item.dest }} backup=yes owner=root group=root mode=0644
3 with_items:
4 - { src: nginx.conf, dest: conf/nginx.conf }
5 - { src: vhost, dest: conf/ }
6 notify: restart nginx
- playbook管理配置文件3
vim /etc/ansible/nginx_config/update.yml // 最后是定義總入口配置
---
- hosts: testhost
user: root
roles:
- new
執行: ansible-playbook /etc/ansible/nginx_config/update.yml
而回滾的backup.yml對應的roles為old
rsync -av /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/
回滾操作就是把舊的配置覆蓋,然后重新加載nginx服務, 每次改動nginx配置文件之前先備份到old里,對應目錄為/etc/ansible/nginx_config/roles/old/files
vim /etc/ansible/nginx_config/rollback.yml // 最后是定義總入口配置
---
- hosts: testhost
user: root
roles:
- old
#定義總入口配置
[root@minglinux-01 ~] vim /etc/ansible/nginx_config/update.yml
#內容如下
1 ---
2 - hosts: minglinux-02
3 user: root
4 roles:
5 - new
#執行
[root@minglinux-01 ~] ansible-playbook /etc/ansible/nginx_config/update.yml
_____________________
< PLAY [minglinux-02] >
---------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
________________________
< TASK [Gathering Facts] >
------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [minglinux-02]
_____________________________
< TASK [new : copy conf file] >
-----------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [minglinux-02] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
changed: [minglinux-02] => (item={u'dest': u'conf/', u'src': u'vhost'})
_______________________________________
< RUNNING HANDLER [new : restart nginx] >
---------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [minglinux-02]
____________
< PLAY RECAP >
------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
minglinux-02 : ok=3 changed=2 unreachable=0 failed=0
#查看目標機器是否重新加載
[root@minglinux-02 ~] ps aux|grep nginx
root 3868 0.0 0.1 46200 2936 ? Ss 03:32 0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/localnginx/conf/nginx.conf
nobody 6307 0.0 0.2 48688 4024 ? S 04:24 0:00 nginx: worker process
nobody 6308 0.0 0.2 48688 4024 ? S 04:24 0:00 nginx: worker process
root 6322 0.0 0.0 112720 984 pts/0 S+ 04:24 0:00 grep --color=auto nginx
[root@minglinux-02 ~] date
2019年 03月 14日 星期四 04:24:59 CST
#對/etc/ansible/nginx_config/roles/new/files/nginx.conf做變更再執行
[root@minglinux-01 ~] vim /etc/ansible/nginx_config/roles/new/files/nginx.conf
[root@minglinux-01 ~] cat /etc/ansible/nginx_config/roles/new/files/nginx.conf |grep vhost
#include vhost/*.conf;
[root@minglinux-01 ~] ansible-playbook /etc/ansible/nginx_config/update.yml
[root@minglinux-02 ~] cat /usr/local/nginx/conf/nginx.conf |grep vhost
#include vhost/*.conf;
#回滾
#old和new保持一致,相當于把當前nginx配置文件備份到old里,如需回滾就將備份還原
#每次改動nginx配置文件之前先備份到old里,目錄是/etc/ansible/nginx_config/roles/old/files
[root@minglinux-01 ~] rsync -av /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/
sending incremental file list
files/
files/nginx.conf
files/vhost/
files/vhost/aaa.com.conf
files/vhost/load.conf
files/vhost/proxy.conf
files/vhost/ssl.conf
files/vhost/test.com.conf
handlers/
handlers/main.yml
tasks/
tasks/main.yml
vars/
vars/main.yml
sent 5,233 bytes received 207 bytes 10,880.00 bytes/sec
total size is 4,409 speedup is 0.81
#定義一個總入口配置
[root@minglinux-01 ~] vim /etc/ansible/nginx_config/rollback.yml
#內容如下
1 ---
2 - hosts: minglinux-02
3 user: root
4 roles:
5 - old
#執行回滾
[root@minglinux-01 ~] ansible-playbook /etc/ansible/nginx_config/rollback.yml