自动化运维基础-ansible
一、Ansible介绍
ansible介绍:
不需要安装客户端,通过sshd去通信(需要做好sshd**认证)
基于模块工作,模块可以使用任何语言开发
不仅支持命令行使用模块,也支持编写yaml格式的playbook,易于编写和阅读
安装十分方便,centos上可以直接yum安装
有提供GUI图形界面:www.ansible.com/tower,收费的
ansible被红帽收购了
官方文档:https://docs.ansible.com/ansible/latest/index.html
中文教程:https://ansible-book.gitbooks.io/ansible-first-book/content/
二、ansible安装
1、yum安装ansible
[aaa@qq.com ~]# yum install ansible -y
2、做ssh免密登录**认证。
[aaa@qq.com ~]# ssh-******
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:orKC9yrUB5XjZ1tTXJSpqDSbqNcuGE65TZ9YkBWj9eE aaa@qq.com
The key's randomart image is:
+---[RSA 2048]----+
| .+... ooo |
| +o.+ .o o |
| o.+ Eo . |
| . + = + . |
| . o B S . |
| . = = B |
|o + X = . |
|+ .B = + |
| +ooo o. |
+----[SHA256]-----+
[aaa@qq.com ~]#
[aaa@qq.com ~]# ssh-copy-id aaa@qq.com
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
aaa@qq.com's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'aaa@qq.com'"
and check to make sure that only the key(s) you wanted were added.
[aaa@qq.com ~]# ssh-copy-id aaa@qq.com
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
aaa@qq.com's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'aaa@qq.com'"
and check to make sure that only the key(s) you wanted were added.
[aaa@qq.com ~]#
这里只做两台机子的免密登录,192.168.10.101、192.168.10.102,其中,192.168.10.101安装ansible。
如果要批量设置免密登录,可以使用except做分发,例如
(1)把需要做免密登录的主机ip写到一个文件
[aaa@qq.com ~]#vim ip.txt
192.168.10.101
192.168.10.102
192.168.10.103
192.168.10.104
192.168.10.105
192.168.10.106
192.168.10.107
(2)创建except脚本
[aaa@qq.com ~]#vim ssh.expect
#!/usr/bin/expect
set user [lindex $argv 0]
set password [lindex $argv 1]
set host [lindex $argv 2]
spawn ssh-copy-id aaa@qq.com$host
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$password\r" }
}
[aaa@qq.com ~]#chmod +x ssh.expect
此脚本的作用是批量将公钥发送到目标主机。
(3)创建一个shell脚本
[aaa@qq.com ~]# vim ssh.sh
#!/bin/bash
user="root"
passwd="123456"
for host in `cat ip.txt`
do
./ssh.expect "$user" "$passwd" "$host"
done [aaa@qq.com ~]# chmod +x ssh.sh
该脚本调用ssh.expect脚本,实现批量传输**。需要注意的是,所有的主机root用户密码都是一样的,如果root密码各不相同,可以写到一个文件,然后在脚本中使用循环迭代读取。
(4)执行shell脚本即可
[aaa@qq.com ~]# ./ssh.sh
3、配置ansible的hosts文件
[aaa@qq.com ~]# vim /etc/ansible/hosts
[servers]
192.168.10.101
192.168.10.102
[servers]:为组名,自定义
三、ansible远程执行命令
远程执行命令:ansible 组名 -m 模块 -a '命令'
[aaa@qq.com ~]# ansible servers -m command -a 'ls'
192.168.10.101 | SUCCESS | rc=0 >>
anaconda-ks.cfg
centos-7-x86_64-minimal.tar.gz
keepalived-2.0.6
keepalived-2.0.6.tar.gz
my-cetnos7.tar
nginx-1.14.0
nginx-1.14.0.tar.gz
192.168.10.102 | SUCCESS | rc=0 >>
anaconda-ks.cfg
keepalived-2.0.6
keepalived-2.0.6.tar.gz
myproject
nginx-1.14.0
nginx-1.14.0.tar.gz
sample
[aaa@qq.com ~]#
使用shell模块:
[aaa@qq.com ~]# ansible 127.0.0.1 -m shell -a 'w'
127.0.0.1 | SUCCESS | rc=0 >>
13:21:44 up 12 min, 1 user, load average: 0.13, 1.30, 1.29
USER TTY FROM aaa@qq.com IDLE JCPU PCPU WHAT
root pts/0 192.168.10.1 13:12 8.00s 2.51s 0.02s w
[aaa@qq.com ~]#
四、ansible拷贝文件或目录
拷贝文件或目录要使用copy模块,比如:
[aaa@qq.com ~]# ansible 192.168.10.102 -m copy -a "src=/etc/ansible dest=/tmp owner=root group=root mode=755"
192.168.10.102 | SUCCESS => {
"changed": true,
"dest": "/tmp/",
"src": "/etc/ansible"
}
[aaa@qq.com ~]#
注意:源目录会放到目标目录下面去,如果目标制定的目录不存在,则会自动创建。如果拷贝的是文件,dest指定的名字和源文件不同,并且它不是已经存在的目录,相当于拷贝过去后又重命名。但相反,如果dest是目标机器上已经存在的目录,则会直接把文件拷贝到该目录下。
[aaa@qq.com ~]# ansible 192.168.10.102 -m copy -a "src=/etc/passwd dest=/tmp/123"
192.168.10.102 | SUCCESS => {
"changed": true,
"checksum": "b230ebaa79927e9369eeb4a41c4acd3156095276",
"dest": "/tmp/123/passwd",
"gid": 0,
"group": "root",
"md5sum": "c552b951a8d1a592f799bfe408571fac",
"mode": "0644",
"owner": "root",
"size": 1367,
"src": "/root/.ansible/tmp/ansible-tmp-1535693205.48-96045408061935/source",
"state": "file",
"uid": 0
}
[aaa@qq.com ~]#
在192.168.10.102查看一下:
[aaa@qq.com ~]# ls /tmp/123/
aaa passwd
[aaa@qq.com ~]#
passwd文件已经拷贝过去。
五、ansible远程执行脚本
1、创建一个脚本文件,比如/tmp/test.sh
[aaa@qq.com ~]# vim /tmp/test.sh
#!/bin/bash
echo `date` > /tmp/ansible_test.txt
2、将脚本分发到各个机器
[aaa@qq.com ~]# ansible servers -m copy -a "src=/tmp/test.sh dest=/tmp/test_script/ mode=0755"
3、批量执行脚本
[aaa@qq.com ~]# ansible servers -m shell -a "/tmp/test_script/test.sh"
192.168.10.102 | SUCCESS | rc=0 >>
192.168.10.101 | SUCCESS | rc=0 >>
[aaa@qq.com ~]#
查看一下:
[aaa@qq.com ~]# cat /tmp/ansible_test.txt
Fri Aug 31 13:38:53 CST 2018
[aaa@qq.com ~]#
OK,执行成功。
shell模块支持管道,command模块不支持管道:
[aaa@qq.com ~]# ansible servers -m shell -a "cat /etc/passwd | wc -l"
192.168.10.102 | SUCCESS | rc=0 >>
23
192.168.10.101 | SUCCESS | rc=0 >>
28
[aaa@qq.com ~]#
[aaa@qq.com ~]# ansible servers -m command -a "cat /etc/passwd | wc -l"
192.168.10.102 | FAILED | rc=1 >>
cat: invalid option -- 'l'
Try 'cat --help' for more information.non-zero return code
192.168.10.101 | FAILED | rc=1 >>
cat: invalid option -- 'l'
Try 'cat --help' for more information.non-zero return code
[aaa@qq.com ~]#
注意:使用shell模块远程执行脚本,得先把脚本分发到各个机器。如果使用script模块,则不需要把脚本分发到各个机器。
六、ansible管理任务计划
cron模块用户管理任务计划。比如:
1、添加任务计划:
[aaa@qq.com ~]# ansible servers -m cron -a "name='test cron' job='/usr/bin/echo haha' weekday=6"
192.168.10.102 | SUCCESS => {
"changed": true,
"envs": [],
"jobs": [
"test cron"
]
}
192.168.10.101 | SUCCESS => {
"changed": true,
"envs": [],
"jobs": [
"test cron"
]
}
[aaa@qq.com ~]#
查看一下任务计划:
[aaa@qq.com ~]# crontab -l
#Ansible: test cron
* * * * 6 /usr/bin/echo haha
[aaa@qq.com ~]#
添加成功。
时间表示:minute(分钟)、hour(小时)、day(日期)、month(月份)、weekday(星期)
2、删除任务计划
前面已经添加了一个test cron任务计划,要想删除此任务计划如下:
[aaa@qq.com ~]# ansible servers -m cron -a "name='test cron' state=absent"
192.168.10.102 | SUCCESS => {
"changed": true,
"envs": [],
"jobs": []
}
192.168.10.101 | SUCCESS => {
"changed": true,
"envs": [],
"jobs": []
}
[aaa@qq.com ~]#
查看一下:
[aaa@qq.com ~]# crontab -l
[aaa@qq.com ~]#
删除成功。
注意:不能使用crontab -e去编辑ansible添加的任务计划。
七、ansible安装包和服务管理
1、使用ansible的yum模块安装httpd
[aaa@qq.com ~]# ansible servers -m yum -a "name=httpd"
2、卸载httpd:
[aaa@qq.com ~]# ansible servers -m yum -a "name=httpd state=removed"
3、启动httpd服务
前面已经卸载了httpd,所以要重新安装。
[aaa@qq.com ~]# ansible servers -m yum -a "name=httpd"
使用service模块启动httpd服务:
[aaa@qq.com ~]# ansible servers -m service -a "name=httpd state=started enabled=No"
4、anbisle文档使用
ansible-doc -l :列出全部模块
ansible-doc -l 模块名:查看某个模块
八、使用playbook
playbook相当于把模块写入配置文件里,例如:
[aaa@qq.com ~]# vim /etc/ansible/test.yml
---
- hosts: servers
remote_user: root
tasks:
- name: test_playbook
shell: touch /tmp/test-palybook.txt
此playbook的作用是创建/tmp/test-palybook.txt 文件。
解释:
--- #第一行必须要3个-,顶格写,新版中可以省略
- hosts: servers # hosts参数指定了对哪些主机进行操作,多台用逗号分隔,也可以使用主机组
remote_user: root #远程执行的用户
tasks: #制定了一个任务
- name: test_playbook #对任务的描述
shell: touch /tmp/test-palybook.txt #shell是模块名,这里使用shell模块
注意空格问题。
执行playbook:
[aaa@qq.com ~]# ansible-playbook /etc/ansible/test.yml
PLAY [servers] ********************************************************************************************************
TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.10.102]
ok: [192.168.10.101]
TASK [test_playbook] **************************************************************************************************
[WARNING]: Consider using file module with state=touch rather than running touch
changed: [192.168.10.102]
changed: [192.168.10.101]
PLAY RECAP ************************************************************************************************************
192.168.10.101 : ok=2 changed=1 unreachable=0 failed=0
192.168.10.102 : ok=2 changed=1 unreachable=0 failed=0
[aaa@qq.com ~]#
查看一下:
[aaa@qq.com ~]# ll /tmp/test-palybook.txt
-rw-r--r-- 1 root root 0 Aug 31 14:08 /tmp/test-palybook.txt
[aaa@qq.com ~]#
OK,文件创建成功。
九、playbook中的变量
一个创建用户的palybook:
[aaa@qq.com ~]# vim create_user.yml
- name: create_user
hosts: servers
user: root
gather_facts: false
vars:
- user: "test"
tasks:
- name: create user
user: name="{{user}}"
此playbook创建一个test用户。
解释:
- name: create_user
hosts: servers
user: root
gather_facts: false #gather_facts参数指定了在以下任务部分执行前,是否先执行setup模块获取主机信息
vars: #vars参数,指定了变量
- user: "test" #变量名为user,值为:test,变量值要用双引号引起来
tasks:
- name: create user
user: name="{{user}}" #user为user模块,name是user模块的一个参数,“{{user}}"调用user变量的值
执行playbook:
[aaa@qq.com ~]# vim create_user.yml
[aaa@qq.com ~]# ansible-playbook create_user.yml
PLAY [create_user] ****************************************************************************************************
TASK [create user] ****************************************************************************************************
changed: [192.168.10.102]
changed: [192.168.10.101]
PLAY RECAP ************************************************************************************************************
192.168.10.101 : ok=1 changed=1 unreachable=0 failed=0
192.168.10.102 : ok=1 changed=1 unreachable=0 failed=0
[aaa@qq.com ~]#
查看一下test用户是否创建:
[aaa@qq.com ~]# id test
uid=1001(test) gid=1001(test) groups=1001(test)
[aaa@qq.com ~]#
十、playbook中的循环
1、创建一个playbook:
[aaa@qq.com ~]# vim while.yml
- hosts: servers
user: root
tasks:
- name: change mode for files
file: path=/tmp/{{item}} mode=600
with_items:
- 1.txt
- 2.txt
- 3.txt
说明:with_items为循环对象。将/tmp/1.txt、2.txt、3.txt文件的权限改为600
2、创建/tmp/1.txt、2.txt、3.txt文件
[aaa@qq.com ~]# touch /tmp/{1.txt,2.txt,3.txt}
[aaa@qq.com ~]#
3、执行playbook
[aaa@qq.com ~]# ansible-playbook while.yml
由于192.168.10.102没有创建/tmp/1.txt、2.txt、3.txt所以报错。
查看lb01上的tmp/1.txt、2.txt、3.txt
[aaa@qq.com ~]# ll /tmp/?.txt
-rw------- 1 root root 0 Aug 31 22:59 /tmp/1.txt
-rw------- 1 root root 0 Aug 31 22:59 /tmp/2.txt
-rw------- 1 root root 0 Aug 31 22:59 /tmp/3.txt
[aaa@qq.com ~]#
OK,文件权限为600。
十一、playbook中的条件判断
1、创建一个playbook
[aaa@qq.com ~]# vim when.yml
- hosts: servers
user: root
gather_facts: True
tasks:
- name: use when
shell: touch /tmp/when.txt
when: ansible_ens33.ipv4.address=="192.168.10.102"
此playbook判断当ip为192.168.10.102的主机就创建/tmp/when.txt文件
2、执行playbook
[aaa@qq.com ~]# ansible-playbook when.yml
PLAY [servers] ********************************************************************************************************
TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.10.101]
ok: [192.168.10.102]
TASK [use when] *******************************************************************************************************
skipping: [192.168.10.101]
[WARNING]: Consider using file module with state=touch rather than running touch
changed: [192.168.10.102]
PLAY RECAP ************************************************************************************************************
192.168.10.101 : ok=1 changed=0 unreachable=0 failed=0
192.168.10.102 : ok=2 changed=1 unreachable=0 failed=0
[aaa@qq.com ~]#
分别查看192.168.10.101、102的/tmp目录:
[aaa@qq.com ~]# ls /tmp/when.txt
ls: cannot access /tmp/when.txt: No such file or directory
[aaa@qq.com ~]#
192.168.10.102:
[aaa@qq.com ~]# ls /tmp/when.txt
/tmp/when.txt
[aaa@qq.com ~]#
查看某个机子的facts信息:
ansible 主机 -m setup
[aaa@qq.com ~]# ansible 192.168.10.101 -m setup
192.168.10.101 | SUCCESS => {
"ansible_facts": {
"ansible_all_ipv4_addresses": [
"172.17.0.1",
"192.168.10.101"
],
"ansible_all_ipv6_add
。。。
十二、playbook中的handlers
handlers:执行task之后,服务器发生变化之后要执行的一些操作。比如修改了配置文件,就需要重启服务。
1、创建一个playbook:
[aaa@qq.com ~]# vim handlers.yml
- name: handlers test
hosts: servers
user: root
tasks:
- name: copy file
copy: src=/etc/passwd dest=/tmp/aaa.txt
notify: test handlers
handlers:
- name: test handlers
shell: echo "2222" >> /tmp/aaa.txt
此playbook,只有copy模块真正执行之后,才会去调用下面的handlers相关的操作。
notify:tasks执行成功后,会调用handlers,notify的值与handlers中的name值相同,在上面的脚本中就是:test handlers。此值是自定义的。
注意:此playbook作用是复制文件,如果源文件和目标文件的内容一样,则不会执行copy模块,copy模块不执行那么就不会执行notify,也就不会执行handlers。
2、执行
[aaa@qq.com ~]# ansible-playbook handlers.yml
PLAY [handlers test] **************************************************************************************************
TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.10.102]
ok: [192.168.10.101]
TASK [copy file] ******************************************************************************************************
changed: [192.168.10.101]
changed: [192.168.10.102]
RUNNING HANDLER [test handlers] ***************************************************************************************
changed: [192.168.10.102]
changed: [192.168.10.101]
PLAY RECAP ************************************************************************************************************
192.168.10.101 : ok=3 changed=2 unreachable=0 failed=0
192.168.10.102 : ok=3 changed=2 unreachable=0 failed=0
[aaa@qq.com ~]#
查看:
[aaa@qq.com ~]# tail /tmp/aaa.txt
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
git:x:1000:1000::/var/opt/gitlab:/bin/sh
gitlab-www:x:997:993::/var/opt/gitlab/nginx:/bin/false
gitlab-redis:x:996:992::/var/opt/gitlab/redis:/bin/false
gitlab-psql:x:995:991::/var/opt/gitlab/postgresql:/bin/sh
gitlab-prometheus:x:994:990::/var/opt/gitlab/prometheus:/bin/sh
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
saslauth:x:993:76:Saslauthd user:/run/saslauthd:/sbin/nologin
test:x:1001:1001::/home/test:/bin/bash
2222
[aaa@qq.com ~]#
显然,handlers操作已执行。
十三、使用playbook安装nginx
1、在lb01(192.168.10.101)主机上编译安装好nginx
编译安装过程省略。nginx编译目录:/usr/local/nginx/
2、创建/etc/ansible/nginx_install目录
[aaa@qq.com ~]# mkdir /etc/ansible/nginx_install
在nginx_install创建以下目录:
[aaa@qq.com ~]# cd /etc/ansible/nginx_install
[aaa@qq.com nginx_install]#
[aaa@qq.com nginx_install]# mkdir -p roles/{common,install}/{handlers,files,meta,tasks,templates,vars}
目录说明:
roles 此目录中有common、install两个目录
├── common 此目录为一些准备操作
│ ├── files 此目录存放一些安装nginx时用到的文件
│ ├── handlers 当发生改变时要执行的操作,比如配置文件发生改变了,就要重启nginx服务
│ ├── meta 此目录存放说明信息
│ ├── tasks 存放核心的配置文件
│ ├── templates 存放一些配置文件,启动脚本等模块文件
│ └── vars 自定义变量
└── install 此目录为安装nginx操作。
├── files
├── handlers
├── meta
├── tasks
├── templates
└── vars
3、将编译的nginx打包
[aaa@qq.com nginx_install]# cd /usr/local/
[aaa@qq.com local]# ls nginx/
client_body_temp conf conf.d fastcgi_temp html logs proxy_temp sbin scgi_temp uwsgi_temp
[aaa@qq.com local]#
[aaa@qq.com local]# tar cf nginx.tar.gz --exclude "nginx.conf" --exclude "conf.d" nginx/
[aaa@qq.com local]# ls
bin etc games include keepalived lib lib64 libexec nginx nginx.tar.gz sbin share src
[aaa@qq.com local]# mv nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
[aaa@qq.com local]#
nginx打包后放到/etc/ansible/nginx_install/roles/install/files/目录中。
将nginx的nginx.conf,conf.d/server.conf,/etc/rc.d/init.d/nginx文件复制到/etc/ansible/nginx_install/roles/install/templates/目录中
/etc/rc.d/init.d/nginx为nginx启动脚本,需自己创建。
[aaa@qq.com local]# cp nginx/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/
[aaa@qq.com local]# cp nginx/conf.d/server.conf /etc/ansible/nginx_install/roles/install/templates/
[aaa@qq.com local]# cp /etc/rc.d/init.d/nginx /etc/ansible/nginx_install/roles/install/templates/
4、定义common的tasks
[aaa@qq.com local]# cd /etc/ansible/nginx_install/roles/common/
[aaa@qq.com common]# vim tasks/main.yml
- name: Install initializtion require software
yum: name={{ item }} state=installed
with_items:
- zlib-devel
- pcre-devel
5、定义变量
[aaa@qq.com common]# vim /etc/ansible/nginx_install/roles/install/vars/main.yml
nginx_user: www
nginx_port: 80
nginx_basedir: /usr/local/nginx
6、定义拷贝nginx相关文件的playbook:
[aaa@qq.com ~]# cd /etc/ansible/nginx_install/
[aaa@qq.com nginx_install]#
[aaa@qq.com nginx_install]# vim 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 xf /tmp/nginx.tar.gz -C /usr/local
- name: Copy Nginx Start Script
template: src=nginx dest=/etc/rc.d/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
- name: Copy Nginx Virtual Config
template: src=server.conf dest={{ nginx_basedir }}/conf.d/ owner=root group=root mode=0644
7、创建用户,启动服务,删除压缩包
[aaa@qq.com nginx_install]# vim 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/rc.d/init.d/nginx start
- name: Add Boot Start Nginx Service
shell: chkconfig --add nginx
- name: Delete Nginx compression files
shell: rm -rf /tmp/nginx.tar.gz
8、创建总的playbook,调用copy,install的playbook
[aaa@qq.com nginx_install]# vim roles/install/tasks/main.yml
- include: copy.yml
- include: install.yml
至此,两个roles:common、install定义完成。
9、定义一个总入口配置文件
[aaa@qq.com nginx_install]# pwd
/etc/ansible/nginx_install
[aaa@qq.com nginx_install]# vim install.yml
---
- hosts: servers
remote_user: root
gather_facts: True
roles:
- common
- install
10、执行总入口的playbook
[aaa@qq.com nginx_install]# pwd
/etc/ansible/nginx_install
[aaa@qq.com nginx_install]# ansible-playbook install.yml
[DEPRECATION WARNING]: The use of 'include' for tasks has been deprecated. Use 'import_tasks' for static inclusions or 'include_tasks' for dynamic inclusions. This feature
will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
[DEPRECATION WARNING]: include is kept for backwards compatibility but usage is discouraged. The module documentation details page may explain more about this rationale..
This feature will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
PLAY [servers] *************************************************************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [192.168.10.102]
ok: [192.168.10.101]
TASK [common : Install initializtion require software] *********************************************************************************************************************
ok: [192.168.10.102] => (item=[u'zlib-devel', u'pcre-devel'])
ok: [192.168.10.101] => (item=[u'zlib-devel', u'pcre-devel'])
TASK [install : Copy Nginx Software] ***************************************************************************************************************************************
ok: [192.168.10.102]
ok: [192.168.10.101]
TASK [install : Uncompression Nginx Software] ******************************************************************************************************************************
[WARNING]: Consider using unarchive module rather than running tar
changed: [192.168.10.102]
changed: [192.168.10.101]
TASK [install : Copy Nginx Start Script] ***********************************************************************************************************************************
ok: [192.168.10.102]
ok: [192.168.10.101]
TASK [install : Copy Nginx Config] *****************************************************************************************************************************************
changed: [192.168.10.102]
changed: [192.168.10.101]
TASK [install : Copy Nginx Virtual Config] *********************************************************************************************************************************
changed: [192.168.10.102]
changed: [192.168.10.101]
TASK [install : Create Nginx User] *****************************************************************************************************************************************
ok: [192.168.10.102]
ok: [192.168.10.101]
TASK [install : Start Nginx Service] ***************************************************************************************************************************************
changed: [192.168.10.102]
changed: [192.168.10.101]
TASK [install : Add Boot Start Nginx Service] ******************************************************************************************************************************
changed: [192.168.10.101]
changed: [192.168.10.102]
TASK [install : Delete Nginx compression files] ****************************************************************************************************************************
[WARNING]: Consider using file module with state=absent rather than running rm
changed: [192.168.10.102]
changed: [192.168.10.101]
PLAY RECAP *****************************************************************************************************************************************************************
192.168.10.101 : ok=11 changed=6 unreachable=0 failed=0
192.168.10.102 : ok=11 changed=6 unreachable=0 failed=0
[aaa@qq.com nginx_install]#
清空防火墙规则,浏览器打开192.168.10.101、192.168.10.102:
OK,成功。
十四、playbook管理配置文件
生产环境中需要管理配置文件的,安装软件时只是在初始化环境的时候用一下。下面写一个管理nginx配置文件的palybook。
目录结构如下:
[aaa@qq.com ~]#
[aaa@qq.com ~]# tree nginx_config/
nginx_config/
├── roles
│ ├── old
│ │ ├── files
│ │ ├── handlers
│ │ ├── tasks
│ │ └── vars
│ └── new
│ ├── files
│ │ ├── conf.d
│ │ │ └── server.conf
│ │ └── nginx.conf
│ ├── handlers
│ │ └── main.yml
│ ├── nginx.conf
│ ├── tasks
│ │ └── main.yml
│ └── vars
│ └── main.yml
└── update.yml12 directories, 7 files
[aaa@qq.com ~]#
1、创建一个nginx_config目录
这里在root目录下创建。
[aaa@qq.com ~]# mkdir nginx_config/roles/{new,old}/{files,handlers,vars,tasks} -p
[aaa@qq.com ~]#
其中,new为更新时用到的目录,old为回滚时用到的目录,files为nginx.conf和虚拟主机配置文件,handlsers为启动nginx服务的命令。
2、把相关配置文件放到files里面
[aaa@qq.com ~]# cd /usr/local/nginx
[aaa@qq.com nginx]# cp -r conf.d/ conf/nginx.conf /root/nginx_config/roles/new/files/
这里是nginx使用编译安装,虚拟主机配置文件目录为安装目录下的conf.d
3、new目录相关配置
(1)定义变量
[aaa@qq.com ~]# cd nginx_config/
[aaa@qq.com nginx_config]# vim roles/new/vars/main.yml
nginx_basedir: /usr/local/nginx
(2)配置handlers
[aaa@qq.com nginx_config]# vim roles/new/handlers/main.yml
- name: restart nginx
shell: /usr/local/nginx/sbin/nginx -s reload
(3)配置核心的任务
[aaa@qq.com nginx_config]# vim 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: conf.d,dest: }
notify: restart nginx
(4)定义总入口
[aaa@qq.com nginx_config]# pwd
/root/nginx_config
[aaa@qq.com nginx_config]# vim update.yml
---
- hosts: servers
user: root
roles:
- new
(5)执行测试
修改一下server.conf之后执行:
[aaa@qq.com nginx_config]# ansible-playbook update.yml
PLAY [servers] ********************************************************************************************************
TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.10.102]
ok: [192.168.10.101]
TASK [new : copy conf file] *******************************************************************************************
ok: [192.168.10.102] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.10.101] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
changed: [192.168.10.101] => (item={u'dest': None, u'src': u'conf.d'})
changed: [192.168.10.102] => (item={u'dest': None, u'src': u'conf.d'})
RUNNING HANDLER [new : restart nginx] *********************************************************************************
changed: [192.168.10.102]
changed: [192.168.10.101]
PLAY RECAP ************************************************************************************************************
192.168.10.101 : ok=3 changed=2 unreachable=0 failed=0
192.168.10.102 : ok=3 changed=2 unreachable=0 failed=0
[aaa@qq.com nginx_config]#
如果源文件和目标文件内容一样,则不会更新文件:
[aaa@qq.com nginx_config]# ansible-playbook update.yml
PLAY [servers] ********************************************************************************************************
TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.10.102]
ok: [192.168.10.101]
TASK [new : copy conf file] *******************************************************************************************
ok: [192.168.10.102] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.10.101] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.10.102] => (item={u'dest': None, u'src': u'conf.d'})
ok: [192.168.10.101] => (item={u'dest': None, u'src': u'conf.d'})
PLAY RECAP ************************************************************************************************************
192.168.10.101 : ok=2 changed=0 unreachable=0 failed=0
192.168.10.102 : ok=2 changed=0 unreachable=0 failed=0
[aaa@qq.com nginx_config]#
配置文件的回滚
在修改配置文件之前,先备份。那么更新了修改后的文件,如有问题,则可以使用备份的文件去同步,也就是回滚了。
1、把new下的所有文件备份到old目录里面
[aaa@qq.com ~]# cd nginx_config/
[aaa@qq.com nginx_config]# rsync -av roles/new/ roles/old
sending incremental file list
created directory roles/old
./
nginx.conf
files/
files/nginx.conf
files/conf.d/
files/conf.d/server.conf
handlers/
handlers/main.yml
tasks/
tasks/main.yml
vars/
vars/main.yml
sent 4,318 bytes received 193 bytes 9,022.00 bytes/sec
total size is 3,674 speedup is 0.81
[aaa@qq.com nginx_config]#
2、创建回滚的playbook
回滚,就用old目录中的文件去覆盖,然后重启nginx服务即可。但每次改动nginx配置文件都先备份到old目录。
[aaa@qq.com nginx_config]# vim rollback.yml
---
- hosts: servers
user: root
roles:
- old
3、测试一下
比如:在nginx.conf文件中添加一行:#hahaha
[aaa@qq.com nginx_config]# echo "#hahaha" >> /usr/local/nginx/conf/nginx.conf
[aaa@qq.com nginx_config]#
回滚:
[aaa@qq.com nginx_config]# ansible-playbook rollback.yml
PLAY [servers] ********************************************************************************************************
TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.10.102]
ok: [192.168.10.101]
TASK [old : copy conf file] *******************************************************************************************
ok: [192.168.10.102] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
changed: [192.168.10.101] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.10.102] => (item={u'dest': None, u'src': u'conf.d'})
ok: [192.168.10.101] => (item={u'dest': None, u'src': u'conf.d'})
RUNNING HANDLER [old : restart nginx] *********************************************************************************
changed: [192.168.10.101]
PLAY RECAP ************************************************************************************************************
192.168.10.101 : ok=3 changed=2 unreachable=0 failed=0
192.168.10.102 : ok=2 changed=0 unreachable=0 failed=0
[aaa@qq.com nginx_config]#
转载于:https://my.oschina.net/logmm/blog/1936820