用于从返回的 json 数据中获取属性的 Ansible 剧本
Ansible playbook for getting an attribute from returned json data
我是 Ansible 的新手,这是我的第一次尝试。我的任务是从 consul nodes
端点检索属性 Address
。我的玩法如下所示
- hosts: localhost
connection: local
tasks:
- name: "Get the addresses"
block:
- name: 'Fetching addresses from consul.'
uri:
url: http://consul-server/v1/catalog/nodes
status_code: 200
body_format: json
return_content: yes
register: nodes
- set_fact:
frontend_ips: "{{ item.Address }}"
when: item.Node == "*hero_node*"
loop: "{{ nodes }}"
这里我试图从 consul 获取所有节点,然后过滤掉节点名称中包含 hero_node
的节点的 Addresses
,但我得到一个异常
fatal: [localhost]: FAILIED! => {}.
MSG: Unexpected failure in finding the lookup name '{{ nodes }} in the available lookup plugin'
nodes json
return从终点看是这样的:
[
{
"Address": "111.111.11.1",
"Node": "hero-node-1",
"Metadata": ...
...
},
{
...
...
}
]
任何帮助将不胜感激。
下面的过滤器为您提供匹配 "hero-node*"
的节点地址列表
- debug:
msg: "{{ nodes|selectattr('Node', 'match', 'hero-node*')|map(attribute='Address')|list}}"
我使用 json_query
来解析 JSON 响应(查询语法取决于您的 JSON,语法 here):
- name: set facts
set_fact:
frontendip: "{{item.ip}}"
loop: "{{facts_var | json_query(fquery)}}"
vars:
fquery: "Nodes[*].{ip: Address, Nodename: Node}"
when: "'hero-node' in item.Nodename"
我是 Ansible 的新手,这是我的第一次尝试。我的任务是从 consul nodes
端点检索属性 Address
。我的玩法如下所示
- hosts: localhost
connection: local
tasks:
- name: "Get the addresses"
block:
- name: 'Fetching addresses from consul.'
uri:
url: http://consul-server/v1/catalog/nodes
status_code: 200
body_format: json
return_content: yes
register: nodes
- set_fact:
frontend_ips: "{{ item.Address }}"
when: item.Node == "*hero_node*"
loop: "{{ nodes }}"
这里我试图从 consul 获取所有节点,然后过滤掉节点名称中包含 hero_node
的节点的 Addresses
,但我得到一个异常
fatal: [localhost]: FAILIED! => {}.
MSG: Unexpected failure in finding the lookup name '{{ nodes }} in the available lookup plugin'
nodes json
return从终点看是这样的:
[
{
"Address": "111.111.11.1",
"Node": "hero-node-1",
"Metadata": ...
...
},
{
...
...
}
]
任何帮助将不胜感激。
下面的过滤器为您提供匹配 "hero-node*"
的节点地址列表- debug:
msg: "{{ nodes|selectattr('Node', 'match', 'hero-node*')|map(attribute='Address')|list}}"
我使用 json_query
来解析 JSON 响应(查询语法取决于您的 JSON,语法 here):
- name: set facts
set_fact:
frontendip: "{{item.ip}}"
loop: "{{facts_var | json_query(fquery)}}"
vars:
fquery: "Nodes[*].{ip: Address, Nodename: Node}"
when: "'hero-node' in item.Nodename"