Ansible-----条件判断与错误处理

时间:2021-05-19 22:55:44

when

在ansible中,条件判断的关键词是when

---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "System release is centos"
when: ansible_distribution == "CentOS"

Ansible-----条件判断与错误处理

ansible_distribution就是facts信息中的一个key,之前如果我们需要引用变量一般是通过"{{ key }}"这样的方式获取,但是在when关键词中,不需要添加"{{  }}"。

---
- hosts: all
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{ item }}"
with_items:
- 1
- 2
- 3
when: item > 1

Ansible-----条件判断与错误处理

Ansible-----条件判断与错误处理

下面是一个逻辑运算实例

---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "System release is centos7"
when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"

逻辑与除了and 也可以使用列表的方式表示。

---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "System release is centos7"
when:
- ansible_distribution == "CentOS"
- ansible_distribution_major_version == "7"

  这个列表中的每一项都是一个条件,当所有条件同时成立时,任务才会执行。

fail模块

想要playbook按照我们的意愿中断任务,可以借助fail模块。

在任务没有设置ignore_errors:true情况下,如果有任务执行失败,playbook会自动停止执行,当fail模块执行后,playbook会认为任务执行失败了,会主动中止任务。

---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "1"
- debug:
msg: "2"
- fail:
- debug:
msg: "3"
- debug:
msg: "4"
 

Ansible-----条件判断与错误处理

我们也可以通过fail模块自带的msg,自定义报错信息,

---
- hosts: test70
remote_user: root
tasks:
- debug:
msg: "1"
- fail:
msg: "Interrupt running playbook"
- debug:
msg: "2"

Ansible-----条件判断与错误处理

fail+when

fail模块通常与when模块结合,如果中断剧本的条件成立,则执行fail模块,中断剧本。

---
- hosts: all
remote_user: root
tasks:
- shell: "echo 'This is a string for testing--error'"
register: return_value
- fail:
msg: "Conditions established,Interrupt running playbook"
when: "'error' in return_value.stdout"
- debug:
msg: "I never execute,Because the playbook has stopped"

Ansible-----条件判断与错误处理

failed_when也可以完成类似的功能,当条件成立时将对应任务的状态设置为失败,中止剧本。

---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "I execute normally"
- shell: "echo 'This is a string for testing error'"
register: return_value
failed_when: ' "error" in return_value.stdout'
- debug:
msg: "I never execute,Because the playbook has stopped"

Ansible-----条件判断与错误处理

changed_when

failed_when关键词的作用是在条件成立时将任务状态改为失败。

changed_when关键词的作用是在条件成立时,将任务状态改为changed。

---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "test message"
changed_when: 2 > 1

Ansible-----条件判断与错误处理

当changed_when状态被设置为false时,不管原任务状态为啥,最终都会被设置为ok状态

---
- hosts: all
remote_user: root
tasks:
- shell: "ls /opt"
changed_when: True

Ansible-----条件判断与错误处理