Bootstrap

ansible进阶(四)-Block-任务的逻辑分组和错误处理

概述

ansible的Block主要用处在于:

  1. 对任务进行逻辑分组。另外,原本针对task配置的参数,可以应用于block上(循环除外)。这样block下的所有task都会应用一样的配置参数。
  2. 使用块处理错误。

用块分组任务

 tasks:
   - name: Install, configure, and start Apache
     block:
       - name: Install httpd and memcached
         ansible.builtin.yum:
           name:
           - httpd
           - memcached
           state: present

       - name: Apply the foo config template
         ansible.builtin.template:
           src: templates/src.j2
           dest: /etc/foo.conf

       - name: Start service bar and enable it
         ansible.builtin.service:
           name: bar
           state: started
           enabled: True
     when: ansible_facts['distribution'] == 'CentOS'
     become: true
     become_user: root
     ignore_errors: yes

条件语句when、become以root身份运行、忽略错误,都将应用于块中的每个任务上。

使用块处理错误

关键字:

rescue        当block中出现错误时,执行相应任务模块。

always        无论block中是否出现错误,最终都执行相应任务模块。

rescue故障处理示例

首先备份配置文件,执行一次对nginx.conf文件的修改,修改完配置文件会执行nginx -t。如果验证配置文件有问题,则将目前有问题的配置文件打上-failed标签,且回滚之前备份的配置文件。

---
- name: test nginx config
  hosts: liqitest2
  gather_facts: False
  tasks:
  - name: modify config and test
    block:
      - name: backup config file
        command: cp /etc/nginx/nginx.conf /etc/nginx/conf-backup/nginx.conf

      - name: nginx config file add "include"
        lineinfile:
          path: /etc/nginx/nginx.conf
          insertafter: 'include /etc/nginx/conf.d/'
          line: 'include /etc/nginx/site-enabled/*.conf bad config'

      - name: nginx config test
        command: nginx -t
    rescue:
      - name: move failed config file
        command: mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf-failed
      - name: copy backup file
        command: mv /etc/nginx/conf-backup/nginx.conf /etc/nginx/

always示例

无论block和rescue中是否发生错误,通过always,都会记录操作日志。

---
- name: test nginx config
  hosts: liqitest2
  gather_facts: False
  tasks:
  - name: modify config and test
    block:
      - name: backup config file
        command: cp /etc/nginx/nginx.conf /etc/nginx/conf-backup/nginx.conf

      - name: nginx config file add "include"
        lineinfile:
          path: /etc/nginx/nginx.conf
          insertafter: 'include /etc/nginx/conf.d/'
          line: 'include /etc/nginx/site-enabled/*.conf;'

      - name: nginx config test
        command: nginx -t
    rescue:
      - name: move failed config file
        command: mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf-failed
      - name: copy backup file
        command: mv /etc/nginx/conf-backup/nginx.conf /etc/nginx/
    always:
      - name: add operation recode
        shell: echo `date` modify config >> /etc/nginx/conf-backup/modify-config.log

;