我正在尝试使用
set_fact
模块根据另一个变量的数据创建一个新变量。我尝试过 groupby
和 lists_mergeby
过滤器,但没有成功。
我怎样才能从这个列表中:
"myVms": [
{
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c",
"VirtualMachine": "K606WS625"
},
{
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c",
"VirtualMachine": "K606WS626"
},
{
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c",
"VirtualMachine": "K606WS812"
},
{
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c",
"VirtualMachine": "K606WS817"
}
]
将其变成一个新的列表,其结构如下?
"myVmsModified": [
{
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c",
"MyBeautifulVms": [
"K606WS817",
"K606WS812",
"K606WS626",
"K606WS625"
]
}
]
Ansible 不擅长数据操作。虽然可以使用 Ansible 过滤器的组合来完成您想要的操作,但几乎在所有情况下,用 Python 编写自定义过滤器都更容易。将以下内容放入
filter_plugins/myfilters.py
:
import itertools
def pivot_on_subscriptionid(v):
return [
{"SubscriptionId": key, "MyBeautifulVms": [vm["VirtualMachine"] for vm in grp]}
for key, grp in itertools.groupby(
sorted(v, key=lambda x: x["SubscriptionId"]),
key=lambda x: x["SubscriptionId"],
)
]
class FilterModule:
def filters(self):
return {
"pivot_on_subscriptionid": pivot_on_subscriptionid,
}
现在你可以编写这样的剧本:
- hosts: localhost
gather_facts: false
vars:
maxuid: 500
myVms: [
{
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c",
"VirtualMachine": "K606WS625"
},
{
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c",
"VirtualMachine": "K606WS626"
},
{
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c",
"VirtualMachine": "K606WS812"
},
{
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c",
"VirtualMachine": "K606WS817"
}
]
tasks:
- set_fact:
new_vm_list: "{{ myVms | pivot_on_subscriptionid }}"
- debug:
var: new_vm_list
并得到这个输出:
PLAY [localhost] ***************************************************************
TASK [set_fact] ****************************************************************
ok: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"new_vm_list": [
{
"MyBeautifulVms": [
"K606WS625",
"K606WS626",
"K606WS812",
"K606WS817"
],
"SubscriptionId": "564aba40-77683-4426-84ac-d195769c826c"
}
]
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0