Ansible playbook剧本介绍, 变量, 循环, 条件判断, handlers, 复制nginx, 管理配置文件

playbook - 剧本介绍

  • 核心元素
    Tasks:任务,由模板定义的操作列表
    Variables:变量
    Templates:模板,即使用模板语法的文件
    Handlers:处理器 ,当某条件满足时,触发执行的操作
    Roles:角色

  • hosts和users介绍
    在playbook中的每一个play都可以选择在哪些服务器和以什么用户完成,hosts一行可以是一个主机组、主机、多个主机,中间以冒号分隔,可使用通配模式。其中remote_user表示执行的用户账号。

---
- hosts: abc               #指定主机组,可以是一个或多个组。
    remote_user: root                #指定远程主机执行的用户名

指定远程主机sudo切换用

# vim ping.yml
---
- hosts: abc
    remote_user: root            
    become: yes                #2.6版本以后的参数,之前是sudo,意思为切换用户运行
    become_user: mysql          #指定sudo用户为mysql

执行playbook
# ansible-playbook ping.yml -K
  • Tasks list 和action介绍
  1. Play的主体部分是task列表,task列表中的各任务按次序逐个在hosts中指定的主机上执行,即在所有主机上完成第一个任务后再开始第二个任务。
    在运行playbook时(从上到下执行),如果一个host执行task失败,整个tasks都会回滚,请修正playbook 中的错误,然后重新执行即可。
    Task的目的是使用指定的参数执行模块,而在模块参数中可以使用变量,模块执行时幂等的,这意味着多次执行是安全的,因为其结果一致。
  2. 每一个task必须有一个名称name,这样在运行playbook时,从其输出的任务执行信息中可以很好的辨别出是属于哪一个task的。如果没有定义name,‘action’的值将会用作输出信息中标记特定的task。
  3. 定义一个task,常见的格式:”module: options” 例如:yum: name=httpd
  4. ansible的自带模块中,command模块和shell模块无需使用key=value格式
  • 常用命令
    ansible-playbook [yaml文件名、也可以yml结尾]
    例如:ansible-playbook a.yml
    参数:
    -k(–ask-pass) 用来交互输入ssh密码
    -K(-ask-become-pass) 用来交互输入sudo密码
    -u 指定用户
     ansible-playbook a.yml --syntax-check    #检查yaml文件的语法是否正确,感觉比较有用;
     ansible-playbook a.yml --list-task       #检查tasks任务
     ansible-playbook a.yml --list-hosts      #检查生效的主机
     ansible-playbook a.yml --start-at-task='Copy Nginx.conf'     #指定从某个task开始运行,感觉比较有用;

create user

<root@linux0 /etc/ansible>$ vim create_user.yml
<root@linux0 /etc/ansible>$ cat create_user.yml 
---    #必要;
- name: create_user   
  hosts: linux1    #实施的主机列表;
  user: root       #实施操作的帐号;
  gather_facts: false  #收集信息;
  vars:
    - user: "test"     #新建用户名字赋值;
  tasks:
    - name: create user
      user: name="{{ user }}"   #使用变量创建用户;
#修改版:      
---
- hosts: linux1
  user: root
  gather_facts: false   #不收集信息,运行更快;
  vars:
    - user: "test"
  tasks:   #任务列表;
    - name: create user   #每一个动作之前的提示做什么动作;
      user: name="{{ user }}"   #引用user模块;
<root@linux0 /etc/ansible>$ ansible-playbook create_user.yml   #第一次实施;

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

TASK [create user] ***************************************************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=1    changed=1    unreachable=0    failed=0   

<root@linux0 /etc/ansible>$ ansible-playbook create_user.yml  #第二次实施,没改变;

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

TASK [create user] ***************************************************************************************
ok: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=1    changed=0    unreachable=0    failed=0   

<root@linux0 /etc/ansible>$ ansible linux1 -m command -a "tail -2 /etc/passwd"
linux1 | SUCCESS | rc=0 >>
saslauth:x:995:76:Saslauthd user:/run/saslauthd:/sbin/nologin
test:x:1004:1004::/home/test:/bin/bash   #生成新的用户;

Ansible playbook中的循环

  • vi /etc/ansible/while.yml //加入如下内容
<root@linux0 /etc/ansible>$ vim while.yml  #内容如下:
---
- hosts: linux1
  user: root
  gather_facts: false
  tasks:
    - name: change mode for files
      file: path=/tmp/{{ item }} state=touch mode=600   #引用file模块,
      with_items:  #循环的变量;
        - 1.txt
        - 2.txt
        - 3.txt
<root@linux0 /etc/ansible>$ ansible-playbook while.yml 

PLAY [linux1] ********************************************************************************************

TASK [change mode for files] *****************************************************************************
changed: [linux1] => (item=1.txt)
changed: [linux1] => (item=2.txt)
changed: [linux1] => (item=3.txt)

PLAY RECAP ***********************************************************************************************
linux1                     : ok=1    changed=1    unreachable=0    failed=0  
<root@linux1 /tmp>$ ll [0-9].txt
-rw------- 1 root root 0 12月 31 12:10 1.txt
-rw------- 1 root root 0 12月 31 12:10 2.txt
-rw------- 1 root root 0 12月 31 12:10 3.txt

Ansible playbook中的条件判断

<root@linux0 /etc/ansible>$ ansible linux1 -m setup   #命令可查出机器的特征参数;
<root@linux0 /etc/ansible>$ cat when.yml 
---
- hosts: thosts
  user: root
  gather_facts: True    #收集特征参数,用在下面的条件里;
  tasks:
    - name: use when
      shell: touch /tmp/when.txt
      when: ansible_ens33.ipv4.address == "192.168.87.150"  #先判断IP再完成任务;
<root@linux0 /etc/ansible>$ ansible-playbook  when.yml 

PLAY [thosts] ********************************************************************************************

TASK [Gathering Facts] ***********************************************************************************
ok: [linux1]
ok: [192.168.87.149]

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

changed: [linux1]

PLAY RECAP ***********************************************************************************************
192.168.87.149             : ok=1    changed=0    unreachable=0    failed=0   
linux1                     : ok=2    changed=1    unreachable=0    failed=0   

Ansible playbook中的handlers

  • 执行task之后,服务器发生变化之后要执行的一些操作,比如我们修改了配置文件后,需要重启一下服务
  • 说明,只有copy模块真正执行后,才会去调用下面的handlers相关的操作。也就是说如果1.txt和2.txt内容是一样的,并不会去执行handlers里面的shell相关命令。 这种比较适合配置文件发生更改后,重启服务的操作。
<root@linux0 /etc/ansible>$ vim handler.yml
<root@linux0 /etc/ansible>$ cat !$
cat handler.yml
---
- hosts: linux1
  user: root
  gather_facts: false
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/aaa.txt
      notify: test handlers   #上边命令执成成功后,执行指定的handlers;
  handlers:
    - name: test handlers
      shell: echo "111111" >> /tmp/aaa.txt

<root@linux0 /etc/ansible>$ ansible-playbook handler.yml 

PLAY [linux1] ********************************************************************************************

TASK [copy file] *****************************************************************************************
changed: [linux1]

RUNNING HANDLER [test handlers] **************************************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=2    changed=2    unreachable=0    failed=0 
<root@linux0 /etc/ansible>$ ansible linux1 -m command -a "tail -2  /tmp/aaa.txt"
linux1 | SUCCESS | rc=0 >>
saslauth:x:993:76:Saslauthd user:/run/saslauthd:/sbin/nologin
111111
  • 测试handler只有在之前命令成功后才会执行
<root@linux0 /etc/ansible>$ vim handler.yml
<root@linux0 /etc/ansible>$ cat handler.yml   #对比playbook;
---
- hosts: linux1
  user: root
  gather_facts: false
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/passwd.txt   #复制文件,第一次会改变,再运行不会changed;
      notify: test handlers
  handlers:
    - name: test handlers
      shell: echo "111111" >> /tmp/aaa.txt
<root@linux0 /etc/ansible>$ ansible-playbook handler.yml  #第一次运行;

PLAY [linux1] ********************************************************************************************

TASK [copy file] *****************************************************************************************
changed: [linux1]

RUNNING HANDLER [test handlers] **************************************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=2    changed=2    unreachable=0    failed=0   

<root@linux0 /etc/ansible>$ ansible-playbook handler.yml  #第二次运行时,文件内容一样,没有实施copy,handler也不执行;

PLAY [linux1] ********************************************************************************************

TASK [copy file] *****************************************************************************************
ok: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=1    changed=0    unreachable=0    failed=0   

  • 测试notify使用
<root@linux0 /etc/ansible>$ vim handler.yml
<root@linux0 /etc/ansible>$ cat !$
cat handler.yml
---
- hosts: linux1
  user: root
  gather_facts: false
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/aaa.txt  #复制文件,handler1会改变这个文件,所以每次运行都会changed=2;
      notify: handler1  
  handlers:
    - name: handler1
      shell: echo "111111" >> /tmp/aaa.txt
    - name: handler2
      shell: echo "222222" >> /tmp/bbb.txt
<root@linux0 /etc/ansible>$ ansible-playbook handler.yml 

PLAY [linux1] ********************************************************************************************

TASK [copy file] *****************************************************************************************
changed: [linux1]

RUNNING HANDLER [handler1] *******************************************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=2    changed=2    unreachable=0    failed=0   

<root@linux0 /etc/ansible>$ ansible linux1 -m command -a "tail -2 /tmp/aaa.txt"
linux1 | SUCCESS | rc=0 >>
saslauth:x:993:76:Saslauthd user:/run/saslauthd:/sbin/nologin
111111

<root@linux0 /etc/ansible>$ ansible-playbook handler.yml #第二次运行,changed=2;

PLAY [linux1] ********************************************************************************************

TASK [copy file] *****************************************************************************************
changed: [linux1]

RUNNING HANDLER [handler1] *******************************************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=2    changed=2    unreachable=0    failed=0   

<root@linux0 /etc/ansible>$ ansible linux1 -m command -a "ls -l /tmp/aaa.txt"   #文件是最新创建的,跟下面的时间一致;
linux1 | SUCCESS | rc=0 >>
-rw-r--r-- 1 root root 1666 12月 31 15:34 /tmp/aaa.txt

<root@linux0 /etc/ansible>$ date
2019年 12月 31日 星期二 15:34:54 CST

再次修改playbook

<root@linux0 /etc/ansible>$ vim handler.yml 
<root@linux0 /etc/ansible>$ cat handler.yml 
---  
- hosts: linux1
  user: root
  gather_facts: false
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/aaa.txt
      notify: handler2    #copy文件后转到handler2, 对此文件没有改变,第二次运行就没有changed;
  handlers:
    - name: handler1
      shell: echo "111111" >> /tmp/aaa.txt
    - name: handler2
      shell: echo "222222" >> /tmp/bbb.txt
<root@linux0 /etc/ansible>$ ansible-playbook handler.yml

PLAY [linux1] ********************************************************************************************

TASK [copy file] *****************************************************************************************
changed: [linux1]

RUNNING HANDLER [handler2] *******************************************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=2    changed=2    unreachable=0    failed=0   

<root@linux0 /etc/ansible>$ ansible linux1 -m command -a "ls -l /tmp/aaa.txt"  #最新copy文件;
linux1 | SUCCESS | rc=0 >>
-rw-r--r-- 1 root root 1659 12月 31 15:36 /tmp/aaa.txt

<root@linux0 /etc/ansible>$ date
2019年 12月 31日 星期二 15:36:15 CST
<root@linux0 /etc/ansible>$ ansible linux1 -m command -a "cat /tmp/bbb.txt"  #最新生成的文件;
linux1 | SUCCESS | rc=0 >>
222222

<root@linux0 /etc/ansible>$ ansible-playbook handler.yml    #第二次运行;文件一致,复制不实施,handler也不实施,changed=0;

PLAY [linux1] ********************************************************************************************

TASK [copy file] *****************************************************************************************
ok: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=1    changed=0    unreachable=0    failed=0   

使用templates功能

<root@linux0 /etc/ansible>$ mkdir templates   
<root@linux0 /etc/ansible>$ touch templates/move.txt
<root@linux0 /etc/ansible>$ vim temp.yml
<root@linux0 /etc/ansible>$ cat temp.yml 
---
- hosts: linux1
  remote_user: root
  gather_facts: false
  vars: 
    - move_dir: /data
  tasks:
    - name: use template
      template: src=move.txt dest={{ move_dir }}/mysql/ owner=root group=root mode=0644  #使用template模块,从templates目录中复制文件;ansible自动查找当前ansible目录下的文件和目录下的templates目录下的文件,再有子目录查找不到;
<root@linux0 /etc/ansible>$ ansible-playbook temp.yml   #运行成功;

PLAY [linux1] ********************************************************************************************

TASK [use template] **************************************************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=1    changed=1    unreachable=0    failed=0   

<root@linux0 /etc/ansible>$ ansible linux1 -m command -a "ls /data/mysql/move.txt"
linux1 | SUCCESS | rc=0 >>
/data/mysql/move.txt

playbook实战 - 从编译好的机器里复制nginx到其他机器

  • 编译安装好nginx
  • 打包nginx,安装路径/usr/nginx
<root@linux0 /usr>$ tar czvf nginx.tar.gz nginx/ --exclude "nginx.conf"   #去除配置文件的打包,虚拟主机文件也不打包,会使用后面的功能更新;
<root@linux0 /etc/ansible>$ ls files templates   #其他文件放置;
files:   #copy模块会检查当前目录和其下的files目录;
nginx.tar.gz

templates:   #template模块会检查当前目录和其下的templates目录;
123  move.txt  nginx.conf  nginx.service
<root@linux0 /etc/ansible>$ cat templates/nginx.service   #使用标准脚本修改;启动脚本;
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/usr/nginx/logs/nginx.pid   #修改pid目录;
ExecStart=/usr/nginx/sbin/nginx -c /usr/nginx/conf/nginx.conf    #只是修改目录;
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target
<root@linux0 /etc/ansible>$ cat nginx.yml   #比较复杂的剧本;注意格式;
---         
- hosts: linux1
  remote_user: root
  gather_facts: True
  vars:
    - nginx_user: www       
      nginx_port: 80    #备用;
      nginx_basedir: /usr/nginx
  tasks:
    - name: Install initializtion require software   
      yum: name={{ item }} state=installed   
      with_items:
        - zlib-devel
        - pcre-devel
    - name: Copy Nginx Software     
      copy: src=nginx.tar.gz dest=/tmp/nginx.tar.gz owner=root group=root 
    - name: Uncompression Nginx Software
      unarchive: src=/tmp/nginx.tar.gz dest=/usr remote_src=yes  #新用到的模块,解压时会形成nginx目录,指定上级目录/usr即可;
    - name: Copy Nginx Config
      template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644   #编译的程序属主一般都是root:root, 目录755, 文件644;
    - name: Copy Nginx startup script
      template: src=nginx.service dest=/usr/lib/systemd/system/ owner=root group=root mode=0644  #复制启动脚本;
    - name: reload systemctl
      shell: systemctl daemon-reload   #service模块没有这个功能,只能直接使用命令;必须先reload再enable再启动,如果之前有脚本,不reload就没有更新;会以之前的脚本启动;
    - name: Create Nginx User     
      user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin    #创建user;
    - name: Startup when boot
      shell: systemctl enable nginx    #service模块也没有这个功能;在target加入指向启动脚本的软链接;
    - name: Start Nginx Service
      service: name=nginx state=started   
#    - name: Add Boot Start Nginx Service
#      shell: chkconfig --level 345 nginx on  #使用chkconfig启动服务;
    - name: Delete Nginx compression files
      file: path=/tmp/nginx.tar.gz state=absent
<root@linux0 /etc/ansible>$ ansible-playbook nginx.yml 

PLAY [linux1] ********************************************************************************************

TASK [Gathering Facts] ***********************************************************************************
ok: [linux1]

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

TASK [Copy Nginx Software] *******************************************************************************
changed: [linux1]

TASK [Uncompression Nginx Software] **********************************************************************
changed: [linux1]

TASK [Copy Nginx Config] *********************************************************************************
ok: [linux1]

TASK [Copy Nginx startup script] *************************************************************************
changed: [linux1]

TASK [reload systemctl] **********************************************************************************
changed: [linux1]

TASK [Create Nginx User] *********************************************************************************
ok: [linux1]

TASK [Startup when boot] *********************************************************************************
changed: [linux1]

TASK [Start Nginx Service] *******************************************************************************
changed: [linux1]

TASK [Delete Nginx compression files] ********************************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=11   changed=7    unreachable=0    failed=0   
<root@linux0 /etc/ansible>$ ansible linux1 -m command -a "systemctl status nginx"
linux1 | SUCCESS | rc=0 >>
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since 四 2020-01-02 18:01:53 CST; 4min 34s ago
     Docs: http://nginx.org/en/docs/
  Process: 86238 ExecStart=/usr/nginx/sbin/nginx -c /usr/nginx/conf/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 86239 (nginx)
   CGroup: /system.slice/nginx.service
           ├─86239 nginx: master process /usr/nginx/sbin/nginx -c /usr/nginx/conf/nginx.con
           └─86240 nginx: worker process                              

1月 02 18:01:53 linux1 systemd[1]: Starting nginx - high performance web server...
1月 02 18:01:53 linux1 systemd[1]: New main PID 69833 does not exist or is a zombie.
1月 02 18:01:53 linux1 systemd[1]: Started nginx - high performance web server.

使用roles功能来实现上面的playbook

  • 每个目录的一般使用方法
    说明:roles目录下有两个角色,common为一些准备操作,install为安装nginx的操作。每个角色下面又有几个目录,handlers下面是当发生改变时要执行的操作,通常用在配置文件发生改变,重启服务。files为安装时用到的一些文件,meta为说明信息,说明角色依赖等信息,tasks里面是核心的配置文件,templates通常存一些配置文件,启动脚本等模板文件,vars下为定义的变量
<root@linux0 /etc/ansible/nginx_install>$ tree   #请查看文件结构;tar文件和两个template文件还是上一个示例中的文件;
.
├── install.yml
└── roles
    ├── common
    │   ├── files
    │   ├── handlers
    │   ├── meta
    │   ├── tasks
    │   │   └── main.yml
    │   ├── templates
    │   └── vars
    └── install
        ├── files
        │   └── nginx.tar.gz
        ├── handlers
        ├── meta
        ├── tasks
        │   ├── copy.yml
        │   ├── install.yml
        │   └── main.yml
        ├── templates
        │   ├── move.txt
        │   ├── nginx.conf
        │   └── nginx.service
        └── vars
            └── main.yml

15 directories, 10 files
<root@linux0 /etc/ansible/nginx_install>$ cat install.yml  #入口文件,此功能的根目录;实施后会查找两个role目录下的各个目录的main.yml(名字是固定的);各子文件,内容是顶格;分段不需要var: tasks:;
---
- hosts: linux1
  remote_user: root
  gather_facts: True
  roles:
    - common   #先实施common role;
    - install
<root@linux0 /etc/ansible/nginx_install>$ cat  roles/install/vars/main.yml  #此变量用于install role;
nginx_user: www       
nginx_port: 80
nginx_basedir: /usr/nginx
<root@linux0 /etc/ansible/nginx_install>$ cat roles/common/tasks/main.yml   #common用于支持安装,通过目录实现功能可灵活的分块定义;
- name: Install initializtion require software   #layer2 role common tasks main.yml; 
  yum: name={{ item }} state=installed
  with_items:
    - zlib-devel
    - pcre-devel
<root@linux0 /etc/ansible/nginx_install>$ cat  roles/install/tasks/main.yml  #自动查找到main.yml, 文件引导到当前目录的其他yml文件;
- include_tasks: copy.yml
- include_tasks: install.yml

<root@linux0 /etc/ansible/nginx_install>$ cat 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
  unarchive: src=/tmp/nginx.tar.gz dest=/usr remote_src=yes  
- name: Copy Nginx Config
  template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644   
- name: Copy Nginx startup script
  template: src=nginx.service dest=/usr/lib/systemd/system/ owner=root group=root mode=0644  
- name: reload systemctl
  shell: systemctl daemon-reload  
<root@linux0 /etc/ansible/nginx_install>$ cat  roles/install/tasks/install.yml 
- name: Create Nginx User     
  user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin    
- name: Startup when boot
  shell: systemctl enable nginx    
- name: Start Nginx Service
  service: name=nginx state=started   
- name: Delete Nginx compression files
  file: path=/tmp/nginx.tar.gz state=absent
<root@linux0 /etc/ansible/nginx_install>$ ansible-playbook install.yml 

PLAY [linux1] ********************************************************************************************

TASK [Gathering Facts] ***********************************************************************************
ok: [linux1]

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

TASK [install : include_tasks] ***************************************************************************
included: /etc/ansible/nginx_install/roles/install/tasks/copy.yml for linux1

TASK [install : Copy Nginx Software] *********************************************************************
changed: [linux1]

TASK [install : Uncompression Nginx Software] ************************************************************
changed: [linux1]

TASK [install : Copy Nginx Config] ***********************************************************************
ok: [linux1]

TASK [install : Copy Nginx startup script] ***************************************************************
ok: [linux1]

TASK [install : reload systemctl] ************************************************************************
changed: [linux1]

TASK [install : include_tasks] ***************************************************************************
included: /etc/ansible/nginx_install/roles/install/tasks/install.yml for linux1

TASK [install : Create Nginx User] ***********************************************************************
ok: [linux1]

TASK [install : Startup when boot] ***********************************************************************
changed: [linux1]

TASK [install : Start Nginx Service] *********************************************************************
changed: [linux1]

TASK [install : Delete Nginx compression files] **********************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=13   changed=6    unreachable=0    failed=0   

playbook管理配置文件

  • 需要的文件设置架构
<root@linux0 /etc/ansible/nginx_config>$ tree
.
├── roles
│   ├── new
│   │   ├── files
│   │   │   ├── nginx.conf
│   │   │   └── vhosts
│   │   │       └── 1.conf
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── vars
│   │       └── main.yml
│   └── old
│       ├── files
│       │   ├── nginx.conf
│       │   └── vhosts
│       │       └── 1.conf
│       ├── handlers
│       │   └── main.yml    #内容与new一样,因为都是复制内容,启动服务;
│       ├── tasks
│       │   └── main.yml    #内容与new一样,因为都是复制内容,启动服务;
│       └── vars
│           └── main.yml    #内容与new一样,因为都是复制内容,启动服务;
├── rollback.yml
└── update.yml
  • 文件内容
<root@linux0 /etc/ansible/nginx_config>$ cat update.yml 
---
- hosts: linux1
  user: root
  roles:
  - new

<root@linux0 /etc/ansible/nginx_config>$ cat roles/new/vars/main.yml 
nginx_basedir: /usr/nginx
<root@linux0 /etc/ansible/nginx_config>$ cat 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 }   #意思是两个item, 一个item里面是一对对应的值;src:dest;
    - { src: vhosts, dest: conf/ }
  notify: restart nginx

<root@linux0 /etc/ansible/nginx_config>$ cat roles/new/handlers/main.yml 
- name: restart nginx
  service: name=nginx state=reloaded

<root@linux0 /etc/ansible/nginx_config>$ cat rollback.yml 
---
- hosts: linux1
  user: root
  roles:
  - old
  • 更新配置之前先备份文件
<root@linux0 /etc/ansible/nginx_config>$ rsync -av roles/new/files/* roles/old/files/
sending incremental file list
nginx.conf
vhosts/
vhosts/1.conf

sent 3,109 bytes  received 62 bytes  6,342.00 bytes/sec
total size is 2,905  speedup is 0.92
  • 更新配置文件
<root@linux0 /etc/ansible/nginx_config>$ ansible-playbook update.yml 

PLAY [linux1] ********************************************************************************************

TASK [Gathering Facts] ***********************************************************************************
ok: [linux1]

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

RUNNING HANDLER [new : restart nginx] ********************************************************************
changed: [linux1]

PLAY RECAP ***********************************************************************************************
linux1                     : ok=3    changed=2    unreachable=0    failed=0   
<root@linux1 /tmp>$ !ps
ps aux |grep nginx
root      93689  0.0  0.1  45960  1948 ?        Ss   18:50   0:00 nginx: master process /usr/nginx/sbinnginx -c /usr/nginx/conf/nginx.conf
nobody   119096  0.0  0.1  46416  1916 ?        S    22:16   0:00 nginx: worker process   #时间变化了;
root     119185  0.0  0.0 112728   968 pts/1    R+   22:16   0:00 grep --color=auto nginx
<root@linux1 /tmp>$ date
2020年 01月 02日 星期四 22:16:49 CST
<root@linux1 /tmp>$ cat /usr/nginx/conf/vhosts/1.conf
    server {
        listen       80;
    #    server_name  localhost;   #注意#号;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
	  }
  • 发现错误后退回来原来的设置
<root@linux0 /etc/ansible/nginx_config>$ ansible-playbook rollback.yml 

PLAY [linux1] ********************************************************************************************

TASK [Gathering Facts] ***********************************************************************************
ok: [linux1]

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

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

PLAY RECAP ***********************************************************************************************
linux1                     : ok=3    changed=2    unreachable=0    failed=0   
<root@linux1 /tmp>$ ps aux |grep nginx
root      93689  0.0  0.1  45960  1948 ?        Ss   18:50   0:00 nginx: master process /usr/nginx/sbinnginx -c /usr/nginx/conf/nginx.conf
nobody   119678  0.0  0.2  46416  2008 ?        S    22:18   0:00 nginx: worker process   #时间变化了;
root     119701  0.0  0.0 112728   972 pts/1    R+   22:18   0:00 grep --color=auto nginx
<root@linux1 /tmp>$ date
2020年 01月 02日 星期四 22:18:32 CST
<root@linux1 /tmp>$ cat /usr/nginx/conf/vhosts/1.conf
    server {
        listen       80;
        server_name  localhost;    # #号消失了;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
	  }
发布了125 篇原创文章 · 获赞 5 · 访问量 4604

猜你喜欢

转载自blog.csdn.net/tanyyinyu/article/details/103773573