条件语句

有时候一个 playbook 的结果取决于一个变量,或者取决于上一个任务(task)的执行结果值,在某些情况下,一个变量的值可以依赖于其他变量的值,当然也会影响 Ansible 的执行过程。

下面主要介绍 When 声明。

有时候我们想跳过某些主机的执行步骤,比如符合特定版本的操作系统将不安装某个软件包,或者磁盘空间爆满了将进行清理的步骤。在 Ansible 中很容易做到这一点,通过 When 子句实现,其中将引用 Jinja2 表达式。下面是一个简单的示例:

tasks:
      - name: "shutdown Debian flavored systems"
        command: /sbin/shutdown -t now
        when: ansible_os_family == "Debian"

通过定义任务的 Facts 本地变量 ansible_os_family(操作系统版本名称)是否为 Debian,结果将返回 BOOL 类型值,为 True 时将执行上一条语句 command: /sbin/shutdown -t now,为 False 时该条语句都不会触发。我们再看一个示例,通过判断一条命令执行结果做不同分支的二级处理。

tasks:
      - command: /bin/false
        register: result
        ignore_errors: True
      - command: /bin/something
        when: result|failed
      - command: /bin/something_else
        when: result|success
      - command: /bin/still/something_else
        when: result|skipped

when: result|success 的意思为当变量 result 执行结果为成功状态时,将执行 /bin/something_else 命令,其他同理,其中 success 为 Ansible 内部过滤器方法,返回 Ture 代表命令运行成功。