ansible根据when条件限制角色执行



在为角色添加when条件时,ansible语法出现错误。我正在为这个剧本使用动态库存。下面是动态库存输出的例子:

{
"_meta": {
"hostvars": {
"host1": {
"Id": "1234567890",
"enable_patching": "ENABLED"
},
"host2": {
"Id": "123654290",
"enable_patching": "DISABLED"
}
}
}

以下是易于理解的策略:

---
# This playbook will execute the inventory for applications account
- hosts: nonprod
connection: local
gather_facts: false
serial: 1
vars:
tf_project: "nonprod"
roles:
- { role: patching, tags: [ 'patching' ], when:  "{{ hostvars[inventory_hostname]['enable_patching'] }}" = 'ENABLED'    }

我在运行易出错的剧本时出现以下错误

The offending line appears to be:

- { role: patching, tags: [ 'patching' ], when:  "{{ hostvars[inventory_hostname]['enable_patching'] }}" = 'ENABLED'    }
                                       ^ here

我怎样才能在剧本中使用hostvars?不希望在角色内部使用when条件。

这里发生了一些事情。我认为,如果您首先修改语法,其中一些问题会变得更加明显:

- hosts: nonprod
connection: local
gather_facts: false
vars:
tf_project: "nonprod"
roles:
- role: patching
tags: [ 'patching' ]
when:  "{{ hostvars[inventory_hostname]['enable_patching'] }}" = 'ENABLED'    }

这里的直接问题是,如果你用引号开始一个值,则整个值必须位于带引号的字符串内。也就是说,你不会写:

when: "some value" followed by something else

你只能写:

when: "some value followed by something else"

解决这个问题的一个简单方法是使用YAML的一个引号运算符,如>:

when:  >-
hostvars[inventory_hostname]['enable_patching'] == 'ENABLED'

你的第二个问题是when条件不接受jinja模板标记({{...}}(。

最后,使用==而不是=来比较相等性。

- hosts: nonprod
connection: local
gather_facts: false
vars:
tf_project: "nonprod"
roles:
- role: patching
tags: [ 'patching' ]
when:  >-
hostvars[inventory_hostname]['enable_patching'] == 'ENABLED'

最新更新