《Ansible Playbook扩展:block块》

一、用块分组任务

block任务块就是一组逻辑的tasks。使用block可以将多个任务合并为一个组。

示例如下:

- block:
  - name: 检查{{ service }}服务{{ role }}节点端口
    shell: nc -vz {{ MYSQL_MASTER_HOST }} {{ MYSQL_MASTER_PORT }} && echo "Found" || echo "Notfound"
    register: check_port_status

  - name: 输出{{ service }}服务{{ role }}节点状态结果
    assert:
      that:
        - "'Found' in check_port_status.stdout"
      fail_msg: "The {{ service }} service {{ role }} node is abnormal"
      success_msg: "The {{ service }} service {{ role }} node is running normal"
      
  tags: check
  ignore_errors: False

说明:tags和ignore_errors,都将应用于块中的每个任务上。


二、使用块处理错误

playbook中会定义三种块,三种块的作用方式分别如下:

# block:block里的tasks,如果运行正确,则不会运行rescue;
# rescue:block里的tasks,如果运行失败,才会运行rescue里的tasks
# always:block和rescue里的tasks无论是否运行成功,都会运行always里的tasks

示例如下:

  - name: modify config and test
    # block中的任务是首先要执行的
    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
    # block执行失败会执行rescue
    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/
    # 无论block执行成功还是失败,都会执行always
    always:
      - name: add operation recode
        shell: echo `date` modify config >> /etc/nginx/conf-backup/modify-config.log

说明:block中的任务是首先要执行的,block执行失败会执行rescue,无论block执行成功还是失败,都会执行always。


总结:整理不易,如果对你有帮助,可否点赞关注一下?

更多详细内容请参考:《Linux运维篇:Linux系统运维指南》

你可能感兴趣的:(《Linux运维实战总结》,ansible,block)