侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 742 篇文章
  • 累计创建 64 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

ansible的fail模块

zze
zze
2020-03-28 / 0 评论 / 0 点赞 / 420 阅读 / 3125 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

此文章为「ansible笔记(2)之常用模块」的子文章。

我们知道,在执行 playbook 时,如果 playbook 中的任何一个任务执行失败,playbook 都会停止运行,除非这个任务设置了 ignore_errors: true,在任务没有设置 ignore_errors: yes 的情况下,任务执行失败后,playbook 就会自动终止。
而 fail 模块天生就是一个用来执行失败的模块,当 fail 模块执行后,playbook 就会认为有任务失败了,从而终止运行,实现我们想要的中断效果,来看一个小示例:

---
- hosts: B
  gather_facts: no
  tasks:
  - debug:
      msg: "1"
  - fail:
  - debug:
      msg: "2"

如上例所示,上例 playbook 中一共有 2 个 debug 任务,在第 1 个 debug 任务之后,我们调用了 fail 模块,那么我们来运行一下上例 playbook,执行后输出信息如下:

$ ansible-playbook test.yml 

PLAY [B] ******************************************************************************************************************************

TASK [debug] **************************************************************************************************************************
ok: [B] => {
    "msg": "1"
}

TASK [fail] ***************************************************************************************************************************
fatal: [B]: FAILED! => {"changed": false, "msg": "Failed as requested from task"}

PLAY RECAP ****************************************************************************************************************************
B                          : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0 

从上图可以看出,当前两个 debug 模块输出了对应的信息后,playbook 报错了,之后的 debug 模块并未被调用,实现了中断剧本运行的效果,当执行 fail 模块时,fail 模块默认的输出信息为 Failed as requested from task,我们可以通过 fail 模块的 msg 参数自定义报错的信息,示例如下:

---
- hosts: B
  gather_facts: no
  tasks:
  - debug:
      msg: "1"
  - fail:
      msg: "Interrupt running playbook"
  - debug:
      msg: "2"

执行效果如下:

$ ansible-playbook test.yml 

PLAY [B] ******************************************************************************************************************************

TASK [debug] **************************************************************************************************************************
ok: [B] => {
    "msg": "1"
}

TASK [fail] ***************************************************************************************************************************
fatal: [B]: FAILED! => {"changed": false, "msg": "Interrupt running playbook"}

PLAY RECAP ****************************************************************************************************************************
B                          : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0  

当然,上述示例只是为了介绍 fail 模块的用法,我们通常并不会毫无理由的想要去中断 playbook,通常需要对某些条件进行判断,如果条件满足,则中断剧本,所以,fail 模块通常与 when 结合使用,比如,如果之前模块执行后的标准输出信息中包含字符串 error,则认为中断剧本的条件成立,就立即调用 fail 模块,以中断 playbook 的执行。

0

评论区