我有一个数组
a1:
- channelId: test1
- channelId: test2
我正在尝试向数组添加新的密钥对值
a2:
- channelId: test1
- channelId: test2
- channelId: test3
Ansible Playbook:我尝试将新键值对添加到现有 JSON 数组的部分代码
- name: Setting Channel id
set_fact:
channelarray: "{{ newrelic_alertpolicyresult | json_query('json.data.actor.account.aiWorkflows.workflows.entities[*].destinationConfigurations[*]')}}"
workflowid: "{{ newrelic_alertpolicyresult | json_query('json.data.actor.account.aiWorkflows.workflows.entities[*].id') }}"
- name: PrintChannel ID
debug:
msg: "Channel ID - {{ channelarray }} & Workflow ID - {{ workflowid }}"
- name: PrintChannel ID in loop
debug:
msg: "{{ item }}"
loop: "{{ channelarray }}"
- name: Convert JSON to dictionary
set_fact:
updated_channel_array: "{{ channelarray + [{ 'channelId': 'test3' }] | json_query('[*]') }}"
- name: Print updated channel array
debug:
msg: "{{ updated_channel_array }}"
输出:
TASK [Setting Channel id]
ok: [localhost]
TASK [PrintChannel ID]
ok: [localhost] => {
"msg": "Channel ID - [[{'channelId': 'f35ead0f-8252-4975-9055-5d050161da01'}, {'channelId': 'be33c326-08d4-494c-b544-6c86beb0dd5e'}]] & Workflow ID - ['d7d1db30-918e-4202-a7ba-1613cf9600a1']"
}
TASK [PrintChannel ID in loop]
ok: [localhost] => (item=[{'channelId': 'f35ead0f-8252-4975-9055-5d050161da01'}, {'channelId': 'be33c326-08d4-494c-b544-6c86beb0dd5e'}]) => {
"msg": [
{
"channelId": "f35ead0f-8252-4975-9055-5d050161da01"
},
{
"channelId": "be33c326-08d4-494c-b544-6c86beb0dd5e"
}
]
}
TASK [Convert JSON to dictionary] *********************************************************************************************************************************************************************************
ok: [localhost]
ok: [localhost] => {
"msg": [
[
{
"channelId": "f35ead0f-8252-4975-9055-5d050161da01"
},
{
"channelId": "be33c326-08d4-494c-b544-6c86beb0dd5e"
}
],
{
"channelId": "test3"
}
]
}
最后一个密钥对值应添加到destinationConfigurations数组中
下面的表情
a2: "{{ a1 + [{ 'channelId': 'test3' }] }}"
给你想要的
a2:
- channelId: test1
- channelId: test2
- channelId: test3
如果您出于某种原因必须使用set_fact,下面的任务会给出相同的结果
- set_fact:
a2: "{{ a1 + [{ 'channelId': 'test3' }] }}"
用于测试的完整剧本示例
- hosts: localhost
vars:
a1:
- channelId: test1
- channelId: test2
a2: "{{ a1 + [{ 'channelId': 'test3' }] }}"
tasks:
- debug:
var: a2
- set_fact:
a3: "{{ a1 + [{ 'channelId': 'test3' }] }}"
- debug:
var: a3