IT袋

当前位置:主页 > 经验教程 > 系统教程 >

Ansible的条件判断介绍和使用方式详解

Ansible的条件判断介绍和使用方式详解!(5)

时间:2023-09-17 20:48:10 来源:IT袋 作者:苏晓敏
导读:Ansible的条件判断介绍和使用方式详解,always 当block执行失败时,rescue中的任务才会被执行;而无论block执行成功还是失败,always中的任务都会被执行: - hosts: dbsrvs tasks: - block: - shell: 'ls /bunianS

Ansible的条件判断介绍和使用方式详解

always

当block执行失败时,rescue中的任务才会被执行;而无论block执行成功还是失败,always中的任务都会被执行:

- hosts: dbsrvs
  tasks:
    - block:
        - shell: 'ls /bunianSky'
      rescue:
        - debug:
            msg: '/bunianSky is not exists'
      always:
        - debug:
            msg: 'This task always executes'

条件判断与错误处理

fail模块

在shell中,可能会有这样的需求:当脚本执行至某个阶段时,需要对某个条件进行判断,如果条件成立,则立即终止脚本的运行。在shell中,可以直接调用”exit”即可执行退出。事实上,在playbook中也有类似的模块可以做这件事。即fail模块。

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

fail模块只有一个参数,即 msg:终止前打印出信息

# 使用fail模块中断playbook输出
- hosts: dbsrvs
  tasks:
    - shell: echo "Just a test--error" 
      register: result
    
    - fail:
        msg: "Conditions established,Interrupt running playbook"
      when: "'error' in result.stdout"
    
    - debug:
        msg: "Inever execute,Because the playbook has stopped"

failed_when

当fail和when组合使用的时候,还有一个更简单的写法,即failed_when,当满足某个条件时,ansible主动触发失败。

如果在command_result存在错误输出,且错误输出中,包含了FAILED字串,即返回失败状态:

- name: this command prints FAILED when it fails
  command: /usr/bin/example-command -x -y -z
  register: command_result
  failed_when: "'FAILED' in command_result.stderr"

直接通过fail模块和when条件语句:

- name: this command prints FAILED when it fails
  command: /usr/bin/example-command -x -y -z
  register: command_result
  ignore_errors: True
- name: fail the play if the previous command did not succeed
  fail: msg="the command failed"
  when: " command_result.stderr and 'FAILED' in command_result.stderr"
  • ansible一旦执行返回失败,后续操作就会中止,所以failed_when通常可以用于满足某种条件时主动中止playbook运行的一种方式。
  • ansible默认处理错误的机制是遇到错误就停止执行。但有些时候,有些错误是计划之中的。我们希望忽略这些错误,以让playbook继续往下执行。此时可以使用ignore_errors忽略错误,从而让playbook继续往下执行。

changed_when

当我们控制一些远程主机执行某些任务时,当任务在远程主机上成功执行,状态发生更改时,会返回changed状态响应,状态未发生更改时,会返回OK状态响应,当任务被跳过时,会返回skipped状态响应。我们可以通过changed_when来手动更改changed响应状态

相关阅读