我有一个shell命令,其中stdout行是一个YAML数组,看起来如下:
success: 1
message:
system:
version: X.Y
tier: STABLE
data:
destinations:
0:
_id: 5f7de84eab8cee6deb0795a2
type: SSH
name: backup1
engine_name:
rating:
rating: 6.324084213116
issues:
jobs_count: 0
owner: root
...
1:
_id: 5f7de850e4ef1d17520fee82
type: SSH
name: backup2
engine_name:
rating:
rating: 6.3627132233357
issues:
jobs_count: 0
owner: root
...
total: 2
(清理了很多不需要的行,但结构是一样的(我想处理data: destinations: array number:
、_id:
和name:
值中的数组,并将其存储在值中(使用set fact是最好的(,但我根本不知道如何开始。剧本应该是这样的:
- name: list backup destinations
command: 'mycommand'
register: result
- name: process the result but I don't know how to do that
set_fact:
destinationX_name: ...
destinationX_id: ...
从上面的输出中,结果应该是这样的:
destination0_name: backup1
destination0_id: 5f7de84eab8cee6deb0795a2
destination1_name: backup2
destination1_id: 5f7de850e4ef1d17520fee82
等等
下面的任务
- set_fact:
my_vars: "{{ my_vars|default({})|
combine({my_key: my_val}) }}"
with_nested:
- "{{ data.destinations.keys()|list }}"
- [_id, name]
vars:
my_key: "{{ 'destination' ~ item.0 ~ '_' ~ item.1 }}"
my_val: "{{ data.destinations[item.0][item.1] }}"
- debug:
var: my_vars
给出
my_vars:
destination0__id: 5f7de84eab8cee6deb0795a2
destination0_name: backup1
destination1__id: 5f7de850e4ef1d17520fee82
destination1_name: backup2
好吧,我想我想通了。正确而简单的方法是:
- name: list backup destinations
command: 'mycommand'
register: result
- name: process the result
set_fact:
destination0_name: "{{ (result.stdout | from_yaml).data.destinations.0.name }}"
destination1_name: "{{ (result.stdout | from_yaml).data.destinations.1.name }}"
destination0_id: "{{ (result.stdout | from_yaml).data.destinations.0._id }}"
destination1_id: "{{ (result.stdout | from_yaml).data.destinations.1._id }}"
...
然后我可以从事实中处理变量。