• ansible 批量更新 nginx 配置,以及失败时的自动回滚样例


    作者:   https://blog.csdn.net/weixin_34092455/article/details/89733396

    本文基于 ansible 2.3.0.0 编写

    我们目前有 8 个大区共 24 台 nginx 服务器,每个区除了 upstream 地址不同,其它配置参数都一样。自从使用了 ansible 来维护更新后,工作变得非常轻松,几分钟内就可以更新所有 24 台服务器的 nginx 配置。并且实现了检查配置有误后,自动恢复上一次配置的机制。

    以下就以此为例,展示如何利用 ansible 在自动化部署 nginx 时,如何规避错误的配置。

    首先看看我的 nginx role 目录结构

    1.  
      deploy.Nginx/
    2.  
      ├── files
    3.  
      │ └── nginx.conf
    4.  
      ├── handlers
    5.  
      │ └── main.yml
    6.  
      ├── tasks
    7.  
      │ ├── Debian.yml
    8.  
      │ ├── main.yml
    9.  
      │ └── sites_conf_test.yml
    10.  
      └── templates
    11.  
      ├── cms_console_newtouch_com.j2
    12.  
      └── console_newtouch_com.j2

    roles/deploy.Nginx/tasks/main.yml 里 include sites_conf_test.yml 的代码片段:

    1.  
      - include: sites_conf_test.yml
    2.  
      vars:
    3.  
      - file: '{{ item }}'
    4.  
      with_items:
    5.  
      - 'console_newtouch_com'

    这里传递了变量 file 的值给 sites_conf_test.yml,这样我们可以扩展配置多个站点配置文件。


    roles/deploy.Nginx/tasks/sites_conf_test.yml 的代码:

    1.  
      - name: Create ~/'{{ file }}.conf'
    2.  
      template:
    3.  
      src: '../templates/{{ file }}.j2'
    4.  
      dest: '~/{{ file }}.conf'
    5.  
      register: createResult
    6.  
       
    7.  
      - block:
    8.  
      - name: Copy '~/{{ file }}.conf'
    9.  
      copy:
    10.  
      src: '~/{{ file }}.conf'
    11.  
      dest: '/etc/nginx/sites-enabled/{{ file }}.conf'
    12.  
      backup: yes
    13.  
      remote_src: yes
    14.  
      register: copyResult
    15.  
      when: createResult.changed
    16.  
      - name: 'Test {{ file }}.conf config'
    17.  
      command: nginx -t
    18.  
      notify: Reload nginx service
    19.  
      when: copyResult.changed
    20.  
      rescue:
    21.  
      - name: '{{ file }}.conf test failed, rolling backup file.'
    22.  
      copy:
    23.  
      src: '{{ copyResult.backup_file }}'
    24.  
      dest: '/etc/nginx/sites-enabled/{{ file }}.conf'
    25.  
      remote_src: yes

    代码解析:

    1. 首先使用 template 模块,在服务器上生成 nginx 站点的配置文件。
    2. 2.3.0.0 有个问题还没解决,就是 template 模块的 backup 参数,并不会返回备份文件的名称,所以只能曲线救国,先创建一个临时的文件。
    3. 然后,重点就在这个 block 编排里。第一个 task 是把生成的 console_newtouch_com.conf 文件拷贝到 /etc/nginx/sites-enabled/ 目录下,因为启用了 backup 参数,所以 copyResult 会包含 backup_file 的绝对路径地址名称。这个就用在配置回滚操作中。
    4. 第二个 task 就是执行 nginx -t 来确认新配置文件是否正确了。如果失败了,就会触发 rescue 里的任务。我们只需要把备份文件恢复,保证服务器上的配置是好的。

    同理可以用在更新 nginx.conf 的操作里。

  • 相关阅读:
    jQuery EasyUI介绍
    CodeMirror:基于JavaScript的代码编辑器
    概述:分布式文件系统+分布式存储+分布式处理
    HTML学习笔记——标准网页设计+使用CSS、Javascript
    HTML学习笔记——常用元素及其属性(二)
    HTML学习笔记——常用元素及其属性(一)
    Remmarguts' Date(k短路问题)
    K短路问题模板(spfa+A*)
    树状数组求逆序对模板
    桐桐的糖果计划(tarjan求桥+双连通分量)
  • 原文地址:https://www.cnblogs.com/cheyunhua/p/14627140.html
Copyright © 2020-2023  润新知