ansible-playbook-处理程序成功或失败

处理程序

处理程序是非活动任务,只有notify语句调用时候才会运行handlers中的任务,而notify只有template任务通知发生改变的时候才会触发,也就是报告changed状态,否则会直接跳过notify

tasks:
        - name: copy demo.example.conf configuration template

        template:
            src: /var/lib/templates/demo . example.conf.template

            dest:/etc/httpd/conf.d/demo.example.conf
        notify:
           - restart mysql

handlers:
        - name: restart mysql

        service:
            name: mariadb

            state: restarted

处理任务失败

通常情况,当任务失败时,ansible将立即在主机上终止play的其余部分并且跳过后续所有任务

但我们也可以忽略任务失败

忽略任务失败

可以使用ignore_errors关键字来实现此目的,将其设定为yes,yum执行失败,也会继续执行后续内容

yum:

        name: http

        state: latest

ignore_errors: yes

任务失败后执行处理程序

通常情况任务失败play会从主机终止,并且任务通知中的处理程序也不会运行。但是可以设置force_handlers: yes关键字,即使play失败而终止,也会调用处理程序

---

- hosts: all
  force_handlers: yes

  tasks:
       - name: a task which always notifies its handler
         command:/bin/true
         notify: restart the database


      - name: a task which fails because the package doesn't exist

        yum:

           name: notapkg

           state: latest
handlers:
    - name: restart the database

      service:
          name: mariadb

          state:restarted

指定任务失败条件

你可以在任务中使用failed_when关键字来指定表示任务已失败的条件。

tasks:
        - name: Run user creation script
        shell:/usr/local/bin/create_users.sh

        register: command_result
        failed_when: "'Password missing' in command_result.stdout"

只有当'Password missing'存在于command_result中时才会任务失败

指定何时任务报告changed结果

changed_when关键字可用于控制任务在何时报告他已进行了更改。

changed_when=false时那他只报告ok或者failed

也可以使用条件来进行输出报告

changed_when="'RadHat'== ansible_distribution"

Ansible块和错误处理

块是对任务进行逻辑分组的子句,可用于控制任务的执行方式。

块可以借个rescue和always语句来处理错误

block:定义要运行的主要任务。在block的when条件也会应用在其rescue和always语句中

rescue:定义要在block子句中定义的任务失败时运行的任务。

always:定义始终都独立运行的任务,不论block和rescue子句中定义的任务是成功还是失败。
 

tasks:
        -name: Upgrade DB

        block:
                -name: upgrade the database
                  shell:
                        cmd: /usr/local/lib/upgrade-database
        rescue:
                - name: revert the database upgrade
                  shell:
                        cmd: /usr/local/lib/revert-database
        always:
               - name: always restart the database

                service:
                        name: mariadb

                        state: restarted

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值