【1.4】自动化运维 playbook

本文详细介绍了如何使用Ansible Playbook进行自动化运维,包括playbook中的条件判断、handlers管理、安装Nginx以及配置文件管理。通过实例演示了如何创建、执行和管理playbook,确保服务的稳定运行。
摘要由CSDN通过智能技术生成

24.25 playbook里的条件判断

1、编辑 when.yml

[root@arslinux-01 ansible]# vim when.yml
---
- hosts: testhost
  user: root
  gather_facts: True
  tasks:
    - name: use when
      shell: touch /tmp/when.txt
      when: ansible_ens33.ipv4.address == "192.168.194.132"

2、执行

[root@arslinux-01 ansible]# ansible-playbook when.yml 

PLAY [testhost] ****************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************
ok: [192.168.194.132]
ok: [127.0.0.1]

TASK [use when] ****************************************************************************************************************
skipping: [127.0.0.1]
 [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: [192.168.194.132]

PLAY RECAP *********************************************************************************************************************
127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.194.132            : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

3、查看

[root@arslinux-02 ~]# ll /tmp/when.txt 
-rw-r--r-- 1 root root 0 1月   3 22:06 /tmp/when.txt
[root@arslinux-02 ~]# date
2020年 01月 03日 星期五 22:07:11 CST

24.26 playbook中的handlers

1、编辑 handler.yml

[root@arslinux-01 ansible]# vim handler.yml
---
- name: handlers test
  hosts: 192.168.194.132
  user: root
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/aaabbbccc.txt
      notify: test handlers
  handlers:
    - name: test handlers
      shell: echo "111111" >> /tmp/aaabbbccc.txt

2、执行

[root@arslinux-01 ansible]# ansible-playbook handler.yml 

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

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

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

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

PLAY RECAP *********************************************************************************************************************
192.168.194.132            : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

3、查看

[root@arslinux-02 ~]# tail !$
tail /tmp/aaabbbccc.txt
mysql:x:1009:1009::/home/mysql:/bin/bash
php-fpm:x:1010:1011::/home/php-fpm:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin
virftp:x:1011:1012::/home/virftp:/sbin/nologin
pure-ftp:x:1020:1020::/home/pure-ftp:/bin/bash
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
zabbix:x:997:994:Zabbix Monitoring System:/var/lib/zabbix:/sbin/nologin
111111

说明: 只有 copy 模块真正执行后,才会去调用下面的 handlers 相关的操作。也就是说如果 1.txt 和 2.txt 内容是一样的,并不会去执行 handlers 里面的 shell 相关命令。 这种比较适合配置文件发生更改后,重启服务的操作

24.27/24.28 playbook安装nginx

思路:先在一台机器上编译安装好nginx、打包,然后再用ansible去下发
1、创建各级目录,方便管理

[root@arslinux-01 ansible]# mkdir nginx_install
[root@arslinux-01 ansible]# cd nginx_install
[root@arslinux-01 nginx_install]# mkdir -p roles/{common,install}/{handlers,files,meta,tasks,templates,vars}
[root@arslinux-01 nginx_install]# ls roles/
common/  install/ 
[root@arslinux-01 nginx_install]# ls roles/common/
files/     handlers/  meta/      tasks/     templates/ vars/      
[root@arslinux-01 nginx_install]# ls roles/install/
files/     handlers/  meta/      tasks/     templates/ vars/

说明: roles 目录下有两个角色,common 为一些准备操作,install 为安装nginx的操作。每个角色下面又有几个目录,handlers 下面是当发生改变时要执行的操作,通常用在配置文件发生改变,重启服务。files 为安装时用到的一些文件,meta 为说明信息,说明角色依赖等信息,tasks 里面是核心的配置文件,templates 通常存一些配置文件,启动脚本等模板文件,vars 下为定义的变量

2、打包 nginx 目录,不打包配置文件,例如 nginx.conf,vhost 下的配置文件

[root@arslinux-01 local]# tar czvf nginx.tar.gz --exclude "nginx.conf" --exclude "vhost" nginx/
nginx/
nginx/sbin/
nginx/sbin/nginx.old
nginx/sbin/nginx
nginx/conf/
nginx/conf/koi-win
nginx/conf/koi-utf
nginx/conf/win-utf
nginx/conf/mime.types
nginx/conf/mime.types.default
nginx/conf/fastcgi_params
nginx/conf/fastcgi_params.default
nginx/conf/fastcgi.conf
nginx/conf/fastcgi.conf.default
nginx/conf/uwsgi_params
nginx/conf/uwsgi_params.default
nginx/conf/scgi_params
nginx/conf/scgi_params.default
nginx/conf/nginx.conf.default
nginx/conf/nginx.conf.bak
nginx/conf/htpasswd
nginx/conf/aminglinux.key
nginx/conf/aminglinux.csr
nginx/conf/aminglinux.crt
nginx/logs/
nginx/logs/error.log
nginx/logs/access.log
nginx/logs/nginx_error.log
nginx/html/
nginx/html/50x.html
nginx/html/index.html
nginx/html/1.php
nginx/client_body_temp/
nginx/proxy_temp/
nginx/fastcgi_temp/
nginx/uwsgi_temp/
nginx/scgi_temp/

3、将 nginx 各部分拷贝到 ansible 下的对应目录下

[root@arslinux-01 local]# cp nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
[root@arslinux-01 local]# cp nginx/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/
[root@arslinux-01 local]# cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/templates/

4、定义 common 的 tasks,nginx 是需要一些依赖包的

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

这里也可以写成 yum: name=“pcre-devel,zlib-devel” state=installed

5、定义变量

[root@arslinux-01 common]# cd ../install/
[root@arslinux-01 install]# vim vars/main.yml
nginx_user: www
nginx_port: 80
nginx_basedir: /usr/local/nginx

6、首先要把所有用到的文档拷贝到目标机器

[root@arslinux-01 install]# vim 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

说明: src 不用写绝对路径,因为会自动在 files 下去找;templates,它是一个模块功能,与 copy 不同的是他的文本文件采用了 jinga2 语法,copy 模块会到 files 下去找,而 template 模块会到 template 目录下去找,不需要单独定义

7、创建用户,启动服务,删除压缩包

[root@arslinux-01 install]# vim 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

说明: 变量 nginx_user 在 var 下的 main.yml 中定义;用 chkconfig 来启动 nginx 而不是 systemctl

8、再创建 main.yml 并且把 copy 和 install 调用

[root@arslinux-01 install]# vim tasks/main.yml
- include: copy.yml
- include: install.yml

说明: 可以将 tasks 目录下的 copy.yml 和 install.yml 和在一个 yml 文件下,不过分开更便于查看
到此两个 roles:common 和 install 就定义完成了,接下来要定义一个入口配置文件

9、定义入口配置文件

[root@arslinux-01 install]# vim  /etc/ansible/nginx_install/install.yml
---
- hosts: 192.168.194.132
  remote_user: root
  gather_facts: True
  roles:
    - common
    - install

10、执行操作

[root@arslinux-01 install]# ansible-playbook /etc/ansible/nginx_install/install.yml

PLAY [192.168.194.132] *********************************************************************************************************

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

TASK [common : Install initializtion require software] *************************************************************************
[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: [192.168.194.132] => (item=[u'zlib-devel', u'pcre-devel'])

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

TASK [install : Uncompression Nginx Software] **********************************************************************************
 [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: [192.168.194.132]

TASK [install : Copy Nginx Start Script] ***************************************************************************************
changed: [192.168.194.132]

TASK [install : Copy Nginx Config] *********************************************************************************************
changed: [192.168.194.132]

TASK [install : Create Nginx User] *********************************************************************************************
changed: [192.168.194.132]

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

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

TASK [install : Delete Nginx compression files] ********************************************************************************
 [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: [192.168.194.132]

PLAY RECAP *********************************************************************************************************************
192.168.194.132            : ok=10   changed=8    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
  • 运行流程参考图:
    在这里插入图片描述
    在这里插入图片描述
    11、查看
[root@arslinux-02 ~]# ps aux|grep nginx
root      10679  0.0  0.1  45840  1100 ?        Ss   22:57   0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nobody    10681  0.0  0.3  48328  3740 ?        S    22:57   0:00 nginx: worker process
nobody    10682  0.0  0.3  48328  3740 ?        S    22:57   0:00 nginx: worker process
root      10815  0.0  0.0 112724   988 pts/0    R+   22:57   0:00 grep --color=auto nginx
[root@arslinux-02 ~]# netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd           
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      6730/sshd           
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      7056/master         
tcp        0      0 0.0.0.0:10050           0.0.0.0:*               LISTEN      6741/zabbix_agentd  
tcp6       0      0 :::3306                 :::*                    LISTEN      6971/mysqld         
tcp6       0      0 :::111                  :::*                    LISTEN      1/systemd           
tcp6       0      0 :::22                   :::*                    LISTEN      6730/sshd           
tcp6       0      0 ::1:25                  :::*                    LISTEN      7056/master         
tcp6       0      0 :::10050                :::*                    LISTEN      6741/zabbix_agentd 

因为没有 nginx.conf 未配置虚拟主机,80 端口也就不存在,
总结说明: 总入口文件 install.yml 定义对哪台机器进行操作,可以定义 role 也就是子目录、子 playbook 脚本;common 里面会去找 tasks,tasks 会去找其中的 main.yml,操作都会先去找 tasks;install 里一样会去找 tasks,tasks 会去找 main.yml,而 main.yml 又包含两个同目录下的 copy.yml 和 install.yml,他们会分别执行

24.29/24.30 playbook管理配置文件

管理 nginx 配置文件的 playbook
1、创建目录

[root@arslinux-01 ~]# mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
[root@arslinux-01 ~]# cd /etc/ansible/nginx_config/
[root@arslinux-01 nginx_config]# ls roles/
new/ old/

说明: 其中 new 为更新时用到的,old 为回滚时用到的,files 下面为 nginx.conf 和 vhosts 目录,handlers 为重启 nginx 服务的命令
关于回滚,需要在执行 playbook 之前先备份一下旧的配置,所以对于老配置文件的管理一定要严格,千万不能随便去修改线上机器的配置,并且要保证 new/files 下面的配置和线上的配置一致

2、把 nginx.conf 和 vhosts 目录放到 files 目录下面

[root@arslinux-01 nginx_config]# cd /usr/local/nginx/conf/
[root@arslinux-01 conf]# cp -r nginx.conf vhost/ /etc/ansible/nginx_config/roles/new/files/

3、定义变量

[root@arslinux-01 conf]# vim /etc/ansible/nginx_config/roles/new/vars/main.yml
nginx_basedir: /usr/local/nginx

4、定义重新加载 nginx 服务

[root@arslinux-01 conf]# vim /etc/ansible/nginx_config/roles/new/handlers/main.yml
- name: restart nginx
  shell: /etc/init.d/nginx reload

5、定义核心任务(拷贝配置、加载 handlers)

[root@arslinux-01 conf]# 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: vhost, dest: conf/ }
  notify: restart nginx

6、定义总入口配置文件

[root@arslinux-01 conf]# vim /etc/ansible/nginx_config/update.yml
---
- hosts: 192.168.194.132
  user: root
  roles:
  - new

7、执行

[root@arslinux-01 conf]# ansible-playbook /etc/ansible/nginx_config/update.yml 

PLAY [192.168.194.132] *********************************************************************************************************

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

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

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

PLAY RECAP *********************************************************************************************************************
192.168.194.132            : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[root@arslinux-02 ~]# ps aux|grep nginx
root       6776  0.0  0.2  46112  2944 ?        Ss   20:05   0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nobody     8409  0.0  0.4  48600  4020 ?        S    20:52   0:00 nginx: worker process
nobody     8410  0.0  0.4  48600  4020 ?        S    20:52   0:00 nginx: worker process
root       8437  0.0  0.0 112724   988 pts/0    R+   20:54   0:00 grep --color=auto nginx
[root@arslinux-02 ~]# date
2020年 01月 03日 星期五 20:53:05 CST

8、更改 vhost 参数,更新后查看

[root@arslinux-01 conf]# echo 1111 >> /etc/ansible/nginx_config/roles/new/files/nginx.conf
[root@arslinux-01 conf]# ansible-playbook /etc/ansible/nginx_config/update.yml 

PLAY [192.168.194.132] *********************************************************************************************************

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

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

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

PLAY RECAP *********************************************************************************************************************
192.168.194.132            : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[root@arslinux-02 ~]# tail -3 /usr/local/nginx/conf/nginx.conf
    include vhost/*.conf;
}
1111

9、回滚操作
回滚操作就是把旧的配置覆盖,然后重新加载 nginx 服务, 每次改动 nginx 配置文件之前先备份到 old 里,对应目录为 /etc/ansible/nginx_config/roles/old/files,回滚的 backup.yml 对应的 roles 为 old
1)备份

[root@arslinux-01 conf]# rsync -av /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/

2)定义回滚操作的总入口

[root@arslinux-01 nginx_config]# cp update.yml rollback.yml
[root@arslinux-01 nginx_config]# vim rollback.yml
---
- hosts: 192.168.194.132
  user: root
  roles:
  - old

3)模拟更改配置内容

[root@arslinux-01 nginx_config]# echo 21232332 >> /etc/ansible/nginx_config/roles/new/files/nginx.conf
[root@arslinux-01 nginx_config]# ansible-playbook update.yml
[root@arslinux-02 ~]# tail -3 /usr/local/nginx/conf/nginx.conf
}
1111
21232332

4)回滚执行操作

[root@arslinux-01 nginx_config]# ansible-playbook rollback.yml
[root@arslinux-02 ~]# tail -3 /usr/local/nginx/conf/nginx.conf
    include vhost/*.conf;
}
1111

总结: 每次变更,update 之前先将配置文件备份再更改,改完在 playbook update,有问题可以回滚

以下是几个示例,帮助你巩固playbook的用法
示例: https://blog.51cto.com/215687833/1888534
示例:https://www.cnblogs.com/xuyingzhong/p/8466976.html
示例:http://www.yfshare.vip/2017/03/16/Ansible-Playbooks%E4%B

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值