Ansible 如何解析变量内部的变量?
考虑到这项艰巨的任务:Ansible 如何解析变量内部的变量?,ansible,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: ye
- 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 }}"
我正在尝试在组[节点]中的所有主机上循环。
对于每个节点,我想从facts中获取一个IP,并使用该IP
作为lineinfle 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
您正在尝试使用字符串
{{item}
引用hostvars
中的键
您应该使用变量名项
:
line: \1"{{hostvars[item]['ansible_eth0']['ipv4']['address']}}"\2
您似乎还对术语感到困惑:您试图引用Jinja2表达式中的变量值(即
{{}}
中包含的内容)。这样一个问题的答案是:通过使用变量名,plain。为了爱Cthulhu,这是一个很好的例子,说明了lineinfle
是多么可怕。即使它能工作,也应该用模板来代替。是的,我不需要困惑。谢谢你的澄清。