我有一个像下面的json
{
"nodes":[
{
"node_values":[
"[test1]",
"10.33.11.189",
"10.33.11.185"
]
},
{
"node_values":[
"[test2]",
"10.33.11.189",
"10.33.11.185"
]
}
]
}
我试图只读取节点值并将其放在文本文件中。我使用下面的ansible代码
hosts: localhost
vars:
tmpdata1: "{{ lookup('file','test.json')|from_json }}"
tasks:
- name: Add mappings to /etc/hosts
blockinfile:
path: /home/s57232/Ansible-Install/Install_Inventory.txt
content: item
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.node_values[0] }}"
loop: "{{ tmpdata1 |json_query('nodes[*].node_values[*]') }}"
我正在低于错误
**TASK [Add mappings to /etc/hosts] **********************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'node_values'\n\nThe error appears to have been in '/home/s57232/Ansible-Install/prepare_inventory.yml': line 14, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: Add mappings to /etc/hosts\n ^ here\n"}**
当我尝试使用带有blockinfile的项目和文件格式进行读取时,如果多个位置存在相同的IP,则不会写入,因为它正在查找唯一值。我无法继续下去。谁能帮帮我吗?
当我在使用
- name: Add mappings to /etc/hosts
blockinfile:
path: /home/s57232/Ansible-Install/Install_Inventory.txt
content: "{{ item.node_values }}"
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.node_values[0] }}"
loop: "{{ tmpdata1 |json_query('nodes[*]') }}"
我正进入(状态
# BEGIN ANSIBLE MANAGED BLOCK [test1]
['[test1]', '10.33.11.189', '10.33.11.185']
# END ANSIBLE MANAGED BLOCK [test1]
# BEGIN ANSIBLE MANAGED BLOCK [test2]
['[test2]', '10.33.11.189', '10.33.11.185']
# END ANSIBLE MANAGED BLOCK [test2]
我的期望是
# BEGIN ANSIBLE MANAGED BLOCK [test1]
[test1]
10.33.11.189
10.33.11.185
# END ANSIBLE MANAGED BLOCK [test1]
# BEGIN ANSIBLE MANAGED BLOCK [test2]
[test2]
10.33.11.189
10.33.11.185
# END ANSIBLE MANAGED BLOCK [test2]
这个给你:
- name: Add mappings to /etc/hosts
blockinfile:
path: /home/s57232/Ansible-Install/Install_Inventory.txt
content: "{{ item.node_values | join('\n') }}"
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.node_values.0 }}"
loop: "{{ tmpdata1.nodes }}"
除非您想过滤某些值,否则不需要使用JMESPath。除此之外,您有两个列表:一个用于循环,另一个用换行符加入元素。