首页 > 解决方案 > 两个Ansible when 条件下应该检查注册变量的什么属性

问题描述

如果两个条件中只有一个为真且具有相同的注册变量,我们如何检查注册变量?

下面是我的剧本,它只执行两个 shell 模块之一。

- name: Check file
    shell: cat /tmp/front.txt
    register: myresult
  when: Layer == 'front'

- name: Check file
    shell: cat /tmp/back.txt
    register: myresult
  when: Layer == 'back'

- debug:
    msg: data was read from back.txt and print whatever
  when: Layer == 'back' and myresult.rc != 0

- debug:
    msg: data was read from front.txt and print whatever
  when: Layer == 'front' and myresult.rc != 0

运行上面的剧本

ansible-playbook test.yml -e Layer="front"

我确实收到错误说 myresult 没有属性rc。根据满足的条件打印调试一语句的最佳方法是什么?

我试过myresult is changed了,但这也无济于事。你能建议一下吗?

标签: ansibleattributesruntimeexception.when

解决方案


使用ignore_errors: true和更改任务顺序。尝试如下。

  - name: Check file
    shell: cat /tmp/front.txt
    register: myresult
    when: Layer == 'front'
  - debug:
     msg: data was read from front.txt and print whatever
    when: not myresult.rc
    ignore_errors: true


  - name: Check file
    shell: cat /tmp/back.txt
    register: myresult
    when: Layer == 'back'
  - debug:
     msg: data was read from back.txt and print whatever
    when: not myresult.rc
    ignore_errors: true

推荐阅读