我希望将项目值替换为存储名称 storageA。1.文件 vvsets.yml。
vvsets: [{'key': 'lun.101', 'value': ['server001']}, {'key': 'lun.101', 'value': ['server001']}, {'key': 'lun.201', 'value': ['server002']}, {'key': 'lun.301', 'value': ['server003']}]
2.文件main.yml。
tasks:
- name: A
include_vars: vvsets.yml
- set_fact:
vvsets: "{{ vvsets | combine(new_item, recursive=true) }}"
vars:
new_item: { 'value': 'storageA' }
loop: "{{ vvsets }}"
- 输出。
TASK [set_fact]
ok: [localhost] => (item={'key': 'lun.101', 'value': ['server001']}) => {
"ansible_facts": {
"vvsets": {
"key": "lun.301",
"value": "storageA"
}
},
"ansible_loop_var": "item",
"changed": false,
"item": {
"key": "lun.101",
"value": [
"server001"
]
}
}
ok: [localhost] => (item={'key': 'lun.101', 'value': ['server001']}) => {
"ansible_facts": {
"vvsets": {
"key": "lun.301",
"value": "storageA"
}
},
"ansible_loop_var": "item",
"changed": false,
"item": {
"key": "lun.101",
"value": [
"server001"
]
}
}
ok: [localhost] => (item={'key': 'lun.201', 'value': ['server002']}) => {
"ansible_facts": {
"vvsets": {
"key": "lun.301",
"value": "storageA"
}
},
"ansible_loop_var": "item",
"changed": false,
"item": {
"key": "lun.201",
"value": [
"server002"
]
}
}
ok: [localhost] => (item={'key': 'lun.301', 'value': ['server003']}) => {
"ansible_facts": {
"vvsets": {
"key": "lun.301",
"value": "storageA"
}
},
"ansible_loop_var": "item",
"changed": false,
"item": {
"key": "lun.301",
"value": [
"server003"
]
}
}
- 根据输出,只有最后一个有变化。看起来前 3 个被绕过了。以下是预期的新列表。
vvsets:
- 'key': 'lun.101'
'value': ['storageA']
- 'key': 'lun.101'
'value': ['storageA']
- 'key': 'lun.201'
'value': ['storageA']
- 'key': 'lun.301'
'value': ['storageA']
答案1
你的剧本中的问题是:
vvsets: "{{ vvsets | combine(new_item, recursive=true) }}"
这将仅返回最后修改的元素。
下面的 Playbook 将为您完成这项工作。
---
- name: "Playing with Ansible and Git"
hosts: localhost
connection: local
tasks:
- name: A
include_vars: vvsets.yml
- set_fact:
vvsets_new: []
- set_fact:
vvsets_new: "{{ vvsets_new + [new_value] }}"
vars:
new_item: { 'value': 'storageA'}
new_value: "{{ item | combine(new_item) }}"
loop: "{{ vvsets }}"
- debug:
msg: "{{ vvsets_new | list }}"
输出:
TASK [debug] **********************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": [
{
"key": "lun.101",
"value": "storageA"
},
{
"key": "lun.101",
"value": "storageA"
},
{
"key": "lun.201",
"value": "storageA"
},
{
"key": "lun.301",
"value": "storageA"
}
]
}