ansible - Ansible 中的关联数组更新
问题描述
我在ansible中有这样的变量:
var:
param:
key.something: value
我想更新“key.something”。我怎样才能做到这一点?
这(如我所料)不起作用:
- name: Update param
set_fact:
var.param['key.something']: "value2"
解决方案
Ansible 无法“更新”变量。您只能创建新变量。在许多情况下,您可以通过使用set_fact和combine过滤器将目标变量替换为新变量来获得所需的内容。
例如,如果我有:
- hosts: localhost
gather_facts: false
vars:
target:
somekey: somevalue
我可以编写一个任务来“更新”这样的值somekey
:
tasks:
- name: update somekey in target
set_fact:
target: "{{ target | combine({'somekey': 'newvalue'}) }}"
在您的问题中,您正在尝试更改深度嵌套的键而不是顶级键。combine
过滤器有一个选项recursive
可以在这种情况下提供帮助:
- hosts: localhost
gather_facts: false
vars:
target:
key1: value1
param:
key2: value2
key3: value3
tasks:
- name: update nested key in target
set_fact:
target: "{{ target | combine({'param': {'key3': 'anothervalue'}}, recursive=true) }}"
- debug:
var: target
如果我们运行这个剧本,我们会得到:
PLAY [localhost] *************************************************************************************************************************************************************
TASK [set_fact] **************************************************************************************************************************************************************
ok: [localhost]
TASK [debug] *****************************************************************************************************************************************************************
ok: [localhost] => {
"target": {
"key1": "value1",
"param": {
"key2": "value2",
"key3": "anothervalue"
}
}
}
PLAY RECAP *******************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
推荐阅读
- kubernetes - Istio 速率限制错误(未配置请求的配额“requestcount”)
- c# - Selenium Firefox 驱动程序 - 由于“DirectoryNotFoundException”而无法加载 FirefoxProfile
- c++ - 从 C++ 中的数组中选择一个随机元素
- mysql - SQL查询查找出场次数最多的球队名称
- openstack - Openstack LBaaS 高可用性
- postgresql - 是否可以将 Postgresql 数据库从 Amazon RDS 复制到另一个 Amazon RDS?
- android - ListView ArrayAdapter 没有从 SQLite 获得任何数据
- python - 在电子表格上添加行超过 100 秒的用户配额
- xamarin - Xamarin Forms + MvvmCross 平台渲染器问题
- python - 在 python 3 中的选择查询上使用 fetchone,语法混乱