Write by lyc at 2019-11-8
参考博文:
ansible笔记(29):条件判断与错误处理

1.fail 模块

用于终止当前playbook的执行,通常与条件语句组合使用,当满足条件时,终止当前play的运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
---
# check nginx is running
- name: check nginx process status
shell: >
ps aux | grep nginx | egrep -v "grep|php-fpm" | wc -l
register: nginx_process_count

- name: check nginx 80 http port status
shell: >
netstat -lntup | grep nginx | grep 80 | wc -l
register: nginx_port_count

- name: check nginx is running
fail:
msg: "WARNNING: nginx is running."
when: nginx_process_count.stdout|int > 1 and nginx_port_count.stdout == "1"

fail 判断192.168

使用in, not in判断字符串是否存在于变量结果当中。

1
2
3
4
5
6
7
8
9
---
- debug: var=ansible_default_ipv4.address
tags: always

- name: fail+when
fail:
msg: "Remote host is INNER."
when: "'192.168' in ansible_default_ipv4.address"
tags: always

2.failed_when 判断192.168

  • 与fail + when 实现的效果一致,组合了fail块的功能
  • 当failed_when条件成立时,执行fail终止playbook运行
  • 注意以下shell的模块确实是执行了,只不过是判断shell的执行结果ret.stdout变量
1
2
3
4
5
6
7
8
9
# 当网络是192.168时执行fail终止playbook
- name: fail+failed_when
shell: "echo {{ ansible_default_ipv4.address }}"
register: ret
failed_when: "'192.168' in ret.stdout"
tags: always

- debug: var=ret.stdout
tags: always

3.ignore_errors 忽略错误

ignore_errors 的对象是task

1
2
3
4
5
6
7
8
9
10
--- # copy test
- hosts: webserver
vars:
src_dir: /root
src_file: a.txt
tasks:
- name: exec command
command: /bin/true
register: result # 把结果/bin/true的结果注册到变量result
ignore_errors: True # 忽略报错,不影响下面的代码执行