我正在尝试“打印/显示”现有的变量。变量名称是动态的。问题是Ansible没有在when:
语句中评估varibale名称。因此,我无法使when: (item.1 + '_wwn_' + item.0) is defined
正常工作。
播放
---
- hosts: 127.0.0.1
vars:
host_name: ['COM01ESX07', 'COM01ESX88']
COM01ESX07_wwn_2: "This exist"
tasks:
- debug:
var: "{{item.1}}_wwn_{{item.0}}"
when: (item.1 + '_wwn_' + item.0) is defined
with_nested:
- ['1', '2']
- "{{host_name}}"
不幸的是,尽管未定义
,但这会消除所有变量。TASK [debug] *******************************************************************************************************************************************************************
ok: [127.0.0.1] => (item=[u'1', u'COM01ESX07']) => {
"COM01ESX07_wwn_1": "VARIABLE IS NOT DEFINED!",
"item": [
"1",
"COM01ESX07"
]
}
ok: [127.0.0.1] => (item=[u'1', u'COM01ESX88']) => {
"COM01ESX88_wwn_1": "VARIABLE IS NOT DEFINED!",
"item": [
"1",
"COM01ESX88"
]
}
ok: [127.0.0.1] => (item=[u'2', u'COM01ESX07']) => {
"COM01ESX07_wwn_2": "This exist",
"item": [
"2",
"COM01ESX07"
]
}
ok: [127.0.0.1] => (item=[u'2', u'COM01ESX88']) => {
"COM01ESX88_wwn_2": "VARIABLE IS NOT DEFINED!",
"item": [
"2",
"COM01ESX88"
]
}
但是,如果我将替换为与when: ({{item.1 + '_wwn_' + item.0}}) is defined
它会起作用,虽然我会收到令人担忧的消息:
TASK [debug] *******************************************************************************************************************************************************************
[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: ({{item.1 + '_wwn_' + item.0}}) is defined
skipping: [127.0.0.1] => (item=[u'1', u'COM01ESX07'])
skipping: [127.0.0.1] => (item=[u'1', u'COM01ESX88'])
ok: [127.0.0.1] => (item=[u'2', u'COM01ESX07']) => {
"COM01ESX07_wwn_2": "This exist",
"item": [
"2",
"COM01ESX07"
]
}
skipping: [127.0.0.1] => (item=[u'2', u'COM01ESX88'])
问题: 我怎样才能避免这个令人烦恼的消息,仍然只处理现有的变量。
答案 0 :(得分:0)
问题在于您的when
条件。当你写...
when: (item.1 + '_wwn_' + item.0) is defined
...括号中的部分只是字符串连接,它全部计算为字符串。这跟你写的完全一样:
when: "something" is defined
也就是说,总是是真的。您正在尝试使用动态变量名称,这很棘手。在ansible网站上有关于此主题的FAQ。基本上,您必须显式引用hostvars
顶级变量(因此您可以使用您构造为字典键的字符串),因此您的任务将类似于:
---
- hosts: localhost
gather_facts: false
vars:
host_name: foo
tasks:
- set_fact:
foo_wwn_1: wwn1
- debug:
var: "{{item.1}}_wwn_{{item.0}}"
when: hostvars[inventory_hostname][item.1 + '_wwn_' + item.0] is defined
with_nested:
- ['1', '2']
- "{{host_name}}"