考虑这个Ansible任务:
- name: Set some kernel parameters
lineinfile:
dest: "/home/cloud-user/{{item}}.hostsubnet.json"
regexp: '^(.*hostIP\".*)\"10.*\"(.*)$'
line: \1"{{hostvars['{{item}}']['ansible_eth0']['ipv4']['address']}}"\2
backrefs: yes
with_items: "{{ groups.nodes }}"
我正在尝试遍历组[nodes]中的所有主机。 对于每个节点,我想从事实中获取IP,并使用该IP 作为lineinfile regexp的替代字符串。
但这不起作用。看起来嵌套变量是不可能的。 是否可以解析嵌套变量?
我使用代码收到此错误:
fatal: [master-0.ocp-36-2.teco.dev.a.tecdomain.net]: FAILED! => {
"failed": true
}
MSG:
the field 'args' has an invalid value, which appears to include a
variable that is undefined. The error was:
'ansible.vars.hostvars.HostVars object' has no attribute '{{item}}'
The error appears to have been in
'/var/lib/ansible/playbooks/hostsubnet.yml': line 27, column 7, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: Set some kernel parameters
^ here
答案 0 :(得分:2)
您正尝试使用字符串hostvars
引用{{item}}
中的密钥。
您应该使用变量名item
代替:
line: \1"{{hostvars[item]['ansible_eth0']['ipv4']['address']}}"\2
您似乎也会对术语感到困惑:您尝试在Jinja2表达式中引用变量值(即{{ }}
中包含的内容)。这个问题的答案是:使用变量名称,简单。