自动化运维ansbile

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安装

yum安装ansible

[root@hongwei-02 ~]# yum install ansible -y

做ssh免密登录密钥认证。

[root@hongwei-02 ~]# ssh-keygen 
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 root@lb01
The key's randomart image is:
+---[RSA 2048]----+
|      .+... ooo  |
|     +o.+ .o o   |
|    o.+  Eo .    |
|   . + = + .     |
|  . o B S .      |
| . = = B         |
|o + X = .        |
|+ .B = +         |
| +ooo o.         |
+----[SHA256]-----+
[root@lb01 ~]# 
[root@lb01 ~]# ssh-copy-id [email protected]
/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
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

[root@lb01 ~]# ssh-copy-id [email protected]
/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
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

[root@hongwei-02 ~]# 

 

ansible远程执行命令

远程执行命令

[root@hongwei-02 ~]# ansible servers -m command -a 'ls'
192.168.93.128 | 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.93.131 | 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

[root@hongwei-02 ~]# 

使用shell模块:

[root@hongwei-02 ~]# 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             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    192.168.10.1     13:12    8.00s  2.51s  0.02s w

[root@hongwei-02 ~]# 

ansible拷贝文件或目录

拷贝文件或目录要使用copy模块,比如:

[root@hongwei-02 ~]# ansible 192.168.93.128 -m copy -a "src=/etc/ansible dest=/tmp owner=root group=root mode=755"
192.168.93.128 | SUCCESS => {
    "changed": true, 
    "dest": "/tmp/", 
    "src": "/etc/ansible"
}
[root@hongwei-02 ~]# 

注意:源目录会放到目标目录下面去,如果目标制定的目录不存在,则会自动创建。如果拷贝的是文件,dest指定的名字和源文件不同,并且它不是已经存在的目录,相当于拷贝过去后又重命名。但相反,如果dest是目标机器上已经存在的目录,则会直接把文件拷贝到该目录下。

[root@hongwei-02~]# ansible 192.168.93.128 -m copy -a "src=/etc/passwd dest=/tmp/123"
192.168.93.128 | 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
}
[root@hongwei-02 ~]# 

在192.168.93.131查看一下:

[root@hongwei-03 ~]# ls /tmp/123/
aaa  passwd
[root@hongwei-03~]# 

passwd文件已经拷贝过去。

ansible远程执行脚本

创建一个脚本文件,比如/tmp/test.sh

[root@hongwei-02 ~]# vim /tmp/test.sh
#!/bin/bash
echo `date` > /tmp/ansible_test.txt

将脚本分发到各个机器

[root@hongwei-02~]# ansible servers -m copy -a "src=/tmp/test.sh dest=/tmp/test_script/ mode=0755"

批量执行脚本

[root@hongwei-02 ~]# ansible servers -m shell -a "/tmp/test_script/test.sh"
192.168.93.128 | SUCCESS | rc=0 >>


192.168.93.131 | SUCCESS | rc=0 >>


[root@hongwei-02 ~]# 

查看一下:

[root@hongwei-02 ~]# cat /tmp/ansible_test.txt 
Fri Aug 31 13:38:53 CST 2018
[root@hongwei-02 ~]# 

OK,执行成功。

shell模块支持管道,command模块不支持管道:

[root@hongwei-02 ~]# ansible servers -m shell -a "cat /etc/passwd | wc -l"
192.168.93.128 | SUCCESS | rc=0 >>
23

192.168.93.131 | SUCCESS | rc=0 >>
28

[root@hongwei-02 ~]# ansible servers -m command -a "cat /etc/passwd | wc -l"
192.168.93.128 | FAILED | rc=1 >>
cat: invalid option -- 'l'
Try 'cat --help' for more information.non-zero return code

192.168.93.131 | FAILED | rc=1 >>
cat: invalid option -- 'l'
Try 'cat --help' for more information.non-zero return code

[root@hongwei-02 ~]# 

注意:使用shell模块远程执行脚本,得先把脚本分发到各个机器。如果使用script模块,则不需要把脚本分发到各个机器。

ansible管理任务计划

cron模块用户管理任务计划。比如:

1、添加任务计划:

[root@hongwei-02 ~]# ansible servers -m cron -a "name='test cron' job='/usr/bin/echo haha' weekday=6"
192.168.93.128 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test cron"
    ]
}
192.168.93.131 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test cron"
    ]
}
[root@hongwei-02 ~]# 

查看一下任务计划:

[root@hongwei-02 ~]# crontab -l
#Ansible: test cron
* * * * 6 /usr/bin/echo haha
[root@hongwei-02 ~]# 

添加成功。

时间表示:minute(分钟)、hour(小时)、day(日期)、month(月份)、weekday(星期)

删除任务计划

前面已经添加了一个test cron任务计划,要想删除此任务计划如下:

[root@hongwei-02 ~]# ansible servers -m cron -a "name='test cron' state=absent"
192.168.93.128 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.93.131 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
[root@hongwei-02 ~]# 

查看一下:

[root@hongwei-02 ~]# crontab -l
[root@hongwei-02 ~]# 

删除成功。

注意:不能使用crontab -e去编辑ansible添加的任务计划。

ansible安装包和服务管理

使用ansible的yum模块安装httpd

[root@hongwei-02 ~]# ansible servers -m yum -a "name=httpd"

卸载httpd:

[root@hongwei-02 ~]# ansible servers -m yum -a "name=httpd state=removed"

启动httpd服务

前面已经卸载了httpd,所以要重新安装。

[root@hongwei-02 ~]# ansible servers -m yum -a "name=httpd"

使用service模块启动httpd服务:

[root@hongwei-02 ~]# ansible servers -m service -a "name=httpd state=started enabled=No"

anbisle文档使用

ansible-doc -l :列出全部模块

ansible-doc -l  模块名:查看某个模块

使用playbook

playbook相当于把模块写入配置文件里,例如:

[root@hongwei-02 ~]# 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:

[root@hongwei-02 ~]# ansible-playbook /etc/ansible/test.yml

PLAY [servers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.93.128]
ok: [192.168.93.131]

TASK [test_playbook] **************************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.93.128]
changed: [192.168.93.131]

PLAY RECAP ************************************************************************************************************
192.168.93.128             : ok=2    changed=1    unreachable=0    failed=0   
192.168.93.131             : ok=2    changed=1    unreachable=0    failed=0   

[root@hongwei-02 ~]# 

查看一下:

[root@hongwei-02 ~]# ll /tmp/test-palybook.txt 
-rw-r--r-- 1 root root 0 Aug 31 14:08 /tmp/test-palybook.txt
[root@hongwei-02 ~]# 

OK,文件创建成功。

playbook中的变量

一个创建用户的palybook:

[root@hongwei-02 ~]# vim create_user.yml
- name: create_user
  hosts: servers
  user: root
  gather_facts: false
  vars:
  - user: "test"
  tasks:
  - name: create user
    user: name="{{user}}"

解释:

- 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:

[root@hongwei-02 ~]# vim create_user.yml
[root@hongwei-02 ~]# ansible-playbook create_user.yml 

PLAY [create_user] ****************************************************************************************************

TASK [create user] ****************************************************************************************************
changed: [192.168.93.128]
changed: [192.168.93.131]

PLAY RECAP ************************************************************************************************************
192.168.93.128             : ok=1    changed=1    unreachable=0    failed=0   
192.168.93.131             : ok=1    changed=1    unreachable=0    failed=0   

[root@hongwei-02 ~]# 

查看一下test用户是否创建:

[root@hongwei-02 ~]# id test
uid=1001(test) gid=1001(test) groups=1001(test)
[root@hongwei-02 ~]# 

playbook中的循环

创建一个playbook:

[root@hongwei-02 ~]# 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

创建/tmp/1.txt、2.txt、3.txt文件

[root@hongwei-02 ~]# touch /tmp/{1.txt,2.txt,3.txt}
[root@hongwei-02 ~]# 

执行playbook

[root@hongwei-02 ~]# ansible-playbook while.yml

查看02上的tmp/1.txt、2.txt、3.txt

[root@hongwei-02 ~]# 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
[root@hongwei-02 ~]# 

OK,文件权限为600。

playbook中的条件判断

创建一个playbook

[root@hongwei-02 ~]# vim when.yml
- hosts: servers
  user: root
  gather_facts: True
  tasks:
  - name: use when
    shell: touch /tmp/when.txt
    when: ansible_eno16777736.ipv4.address=="192.168.93.128"

此playbook判断当ip为192.168.93.128的主机就创建/tmp/when.txt文件

执行playbook

[root@hongwei-02 ~]# ansible-playbook when.yml 

PLAY [servers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.93.128]
ok: [192.168.93.131]

TASK [use when] *******************************************************************************************************
skipping: [192.168.93.128]
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.93.131]

PLAY RECAP ************************************************************************************************************
192.168.93.128             : ok=1    changed=0    unreachable=0    failed=0   
192.168.93.131             : ok=2    changed=1    unreachable=0    failed=0   

[root@hongwei-02 ~]# 

分别查看192.168.93.128、131的/tmp目录:

192.168.93.131:

[root@hongwei-03 ~]# ls /tmp/when.txt 
/tmp/when.txt
[root@hongwei-03 ~]# 

查看某个机子的facts信息:

ansible 主机  -m setup

[root@hongwei-02 ~]# ansible 192.168.93.128  -m setup
192.168.93.128 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "172.17.0.1", 
            "192.168.93.128"
        ], 
        "ansible_all_ipv6_add

playbook中的handlers

handlers:执行task之后,服务器发生变化之后要执行的一些操作。比如修改了配置文件,就需要重启服务。

1、创建一个playbook:

[root@hongwei-02 ~]# 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。

执行

[root@hongwei-02 ~]# ansible-playbook handlers.yml 

PLAY [handlers test] **************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.93.128]
ok: [192.168.93.131]

TASK [copy file] ******************************************************************************************************
changed: [192.168.93.128]
changed: [192.168.93.131]

RUNNING HANDLER [test handlers] ***************************************************************************************
changed: [192.168.93.128]
changed: [192.168.93.131]

PLAY RECAP ************************************************************************************************************
192.168.93.128             : ok=3    changed=2    unreachable=0    failed=0   
192.168.93.131             : ok=3    changed=2    unreachable=0    failed=0   

[root@hongwei-02 ~]# 

查看:


[root@hongwei-02 ~]# 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
[root@hongwei-02 ~]# 

显然,handlers操作已执行。

使用playbook安装nginx

1、在02(192.168.93.128)主机上编译安装好nginx

nginx编译目录:/usr/local/nginx/

2、创建/etc/ansible/nginx_install目录

[root@hongwei-02 ~]# mkdir /etc/ansible/nginx_install

在nginx_install创建以下目录:

[root@hongwei-02 ~]# cd /etc/ansible/nginx_install
[root@hongwei-02 nginx_install]# 
[root@hongwei-02 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打包

[root@hongwei-02 nginx_install]# cd /usr/local/
[root@hongwei-02 local]# ls nginx/
client_body_temp  conf  conf.d  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@hongwei-02 local]# 
[root@hongwei-02 local]# tar cf nginx.tar.gz --exclude "nginx.conf" --exclude "conf.d" nginx/
[root@hongwei-02 local]# ls
bin  etc  games  include  keepalived  lib  lib64  libexec  nginx  nginx.tar.gz  sbin  share  src
[root@hongwei-02 local]# mv nginx.tar.gz  /etc/ansible/nginx_install/roles/install/files/
[root@hongwei-02 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启动脚本,需自己创建。

[root@hongwei-02 local]# cp nginx/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/
[root@hongwei-02 local]# cp nginx/conf.d/server.conf /etc/ansible/nginx_install/roles/install/templates/
[root@hongwei-02 local]# cp /etc/rc.d/init.d/nginx  /etc/ansible/nginx_install/roles/install/templates/ 

4、定义common的tasks

[root@hongwei-02 local]# cd /etc/ansible/nginx_install/roles/common/
[root@hongwei-02 common]# vim tasks/main.yml
- name: Install initializtion require software
  yum: name={{ item }} state=installed
  with_items:
    - zlib-devel
    - pcre-devel

5、定义变量

[root@hongwei-02 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:

[root@hongwei-02 ~]# cd /etc/ansible/nginx_install/
[root@hongwei-02 nginx_install]# 
[root@hongwei-02 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、创建用户,启动服务,删除压缩包

[root@hongwei-02 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

[root@hongwei-02 nginx_install]# vim roles/install/tasks/main.yml
- include: copy.yml
- include: install.yml

至此,两个roles:common、install定义完成。

9、定义一个总入口配置文件

[root@hongwei-02 nginx_install]# pwd
/etc/ansible/nginx_install
[root@hongwei-02 nginx_install]# vim install.yml
---
- hosts: servers
  remote_user: root
  gather_facts: True
  roles:
    - common
    - install

10、执行总入口的playbook

[root@hongwei-02 nginx_install]# pwd
/etc/ansible/nginx_install
[root@hongwei-02 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.93.128]
ok: [192.168.93.131]

TASK [common : Install initializtion require software] *********************************************************************************************************************
ok: [192.168.93.128] => (item=[u'zlib-devel', u'pcre-devel'])
ok: [192.168.93.131] => (item=[u'zlib-devel', u'pcre-devel'])

TASK [install : Copy Nginx Software] ***************************************************************************************************************************************
ok: [192.168.93.128]
ok: [192.168.93.131]

TASK [install : Uncompression Nginx Software] ******************************************************************************************************************************
 [WARNING]: Consider using unarchive module rather than running tar

changed: [192.168.93.128]
changed: [192.168.93.131]

TASK [install : Copy Nginx Start Script] ***********************************************************************************************************************************
ok: [192.168.93.128]
ok: [192.168.93.131]

TASK [install : Copy Nginx Config] *****************************************************************************************************************************************
changed: [192.168.93.128]
changed: [192.168.93.131]

TASK [install : Copy Nginx Virtual Config] *********************************************************************************************************************************
changed: [192.168.93.128]
changed: [192.168.93.131]

TASK [install : Create Nginx User] *****************************************************************************************************************************************
ok: [192.168.93.128]
ok: [192.168.93.131]

TASK [install : Start Nginx Service] ***************************************************************************************************************************************
changed: [192.168.93.128]
changed: [192.168.93.131]

TASK [install : Add Boot Start Nginx Service] ******************************************************************************************************************************
changed: [192.168.93.128]
changed: [192.168.93.131]

TASK [install : Delete Nginx compression files] ****************************************************************************************************************************
 [WARNING]: Consider using file module with state=absent rather than running rm

changed: [192.168.93.128]
changed: [192.168.93.131]

PLAY RECAP *****************************************************************************************************************************************************************
192.168.93.128             : ok=11   changed=6    unreachable=0    failed=0   
192.168.93.131             : ok=11   changed=6    unreachable=0    failed=0   

[root@hongwei-02 nginx_install]# 

清空防火墙规则

playbook管理配置文件

生产环境中需要管理配置文件的,安装软件时只是在初始化环境的时候用一下。下面写一个管理nginx配置文件的palybook。

目录结构如下:

[root@hongwei-02 ~]# 
[root@hongwei-02 ~]# 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.yml

1、创建一个nginx_config目录

这里在root目录下创建。

[root@hongwei-02 ~]# mkdir nginx_config/roles/{new,old}/{files,handlers,vars,tasks} -p
[root@hongwei-02 ~]# 

其中,new为更新时用到的目录,old为回滚时用到的目录,files为nginx.conf和虚拟主机配置文件,handlsers为启动nginx服务的命令。

2、把相关配置文件放到files里面

[root@hongwei-02 ~]# cd /usr/local/nginx
[root@hongwei-02 nginx]# cp -r conf.d/ conf/nginx.conf /root/nginx_config/roles/new/files/

这里是nginx使用编译安装,虚拟主机配置文件目录为安装目录下的conf.d

3、new目录相关配置

(1)定义变量

[root@hongwei-02 ~]# cd nginx_config/
[root@hongwei-02 nginx_config]# vim roles/new/vars/main.yml
nginx_basedir: /usr/local/nginx

(2)配置handlers

[root@hongwei-02 nginx_config]# vim roles/new/handlers/main.yml
- name: restart nginx
  shell: /usr/local/nginx/sbin/nginx -s reload

(3)配置核心的任务

[root@hongwei-02 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)定义总入口

[root@hongwei-02 nginx_config]# pwd
/root/nginx_config
[root@hongwei-02 nginx_config]# vim update.yml
---
- hosts: servers
  user: root
  roles:
    - new        

(5)执行测试

修改一下server.conf之后执行:

[root@hongwei-02 nginx_config]# ansible-playbook update.yml 

PLAY [servers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.93.128]
ok: [192.168.93.131]

TASK [new : copy conf file] *******************************************************************************************
ok: [192.168.93.128] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.93.131] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
changed: [192.168.93.128] => (item={u'dest': None, u'src': u'conf.d'})
changed: [192.168.93.131] => (item={u'dest': None, u'src': u'conf.d'})

RUNNING HANDLER [new : restart nginx] *********************************************************************************
changed: [192.168.93.131]
changed: [192.168.93.128]

PLAY RECAP ************************************************************************************************************
192.168.93.131             : ok=3    changed=2    unreachable=0    failed=0   
192.168.93.128             : ok=3    changed=2    unreachable=0    failed=0   

[root@hongwei-02 nginx_config]# 

如果源文件和目标文件内容一样,则不会更新文件:

[root@hongwei-02 nginx_config]# ansible-playbook update.yml 

PLAY [servers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.93.128]
ok: [192.168.93.131]

TASK [new : copy conf file] *******************************************************************************************
ok: [192.168.93.131] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.93.128] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.93.131] => (item={u'dest': None, u'src': u'conf.d'})
ok: [192.168.93.128] => (item={u'dest': None, u'src': u'conf.d'})

PLAY RECAP ************************************************************************************************************
192.168.93.128             : ok=2    changed=0    unreachable=0    failed=0   
192.168.93.131             : ok=2    changed=0    unreachable=0    failed=0   

[root@hongwei-02 nginx_config]# 

配置文件的回滚

在修改配置文件之前,先备份。那么更新了修改后的文件,如有问题,则可以使用备份的文件去同步,也就是回滚了。

1、把new下的所有文件备份到old目录里面

[root@hongwei-02 ~]# cd nginx_config/
[root@hongwei-02 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
[root@hongwei-02 nginx_config]# 

2、创建回滚的playbook

回滚,就用old目录中的文件去覆盖,然后重启nginx服务即可。但每次改动nginx配置文件都先备份到old目录。

[root@hongwei-02 nginx_config]# vim rollback.yml
---
- hosts: servers
  user: root
  roles:
    - old         

3、测试一下

比如:在nginx.conf文件中添加一行:#lalalal

[root@hongwei-02 nginx_config]# echo "#lalalal" >> /usr/local/nginx/conf/nginx.conf
[root@hongwei-02 nginx_config]# 

回滚:

[root@hongwei-02 nginx_config]# ansible-playbook rollback.yml 
PLAY [servers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.93.128]
ok: [192.168.93.131]

TASK [old : copy conf file] *******************************************************************************************
ok: [192.168.93.128] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
changed: [192.168.93.128] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.93.131] => (item={u'dest': None, u'src': u'conf.d'})
ok: [192.168.93.128] => (item={u'dest': None, u'src': u'conf.d'})

RUNNING HANDLER [old : restart nginx] *********************************************************************************
changed: [192.168.93.128]

PLAY RECAP ************************************************************************************************************
192.168.93.128             : ok=3    changed=2    unreachable=0    failed=0   
192.168.93.131             : ok=2    changed=0    unreachable=0    failed=0   

[root@hongwei-02 nginx_config]# 

 

转载于:https://my.oschina.net/u/3851487/blog/1973343

你可能感兴趣的:(自动化运维ansbile)