ansible - Ansible 仅通过过滤器更改所有 dict 键值
问题描述
我有一个像
ports:
webui: 7200
webadmin: 7209
core_api: 7201
stock_api: 7204
import_export: 7207
我想转换其中的所有键,比如
ports:
staging-webui: 7200
staging-webadmin: 7209
staging-core_api: 7201
staging-stock_api: 7204
staging-import_export: 7207
我在'vars'部分这样做,所以我不能使用'set_fact'和'with_items'来迭代dict。只能通过过滤器来实现吗?
我找到了有效的答案,
env: staging # comes from outside
regex_env: "\"key\": \"{{ env }}-\\1\""
app_upstreams: "{{ ports | dict2items | map('to_json') | map('regex_replace', '\"key\":\\s\"(.*)\"', lookup('vars', 'regex_env')) | map('from_json') }}"
但是看起来真的很丑,有没有更好看的解决方案?
解决方案
使用简单的过滤器
shell> cat filter_plugins/dict_utils.py
def prefix_key(d, prefix='prefix'):
for key in d.keys():
d[prefix + key] = d.pop(key)
return d
class FilterModule(object):
''' utility filters for operating on dictionary '''
def filters(self):
return {
'prefix_key' : prefix_key
}
下面的任务
- debug:
var: staging_ports
vars:
staging_ports: "{{ ports|prefix_key(prefix='staging_') }}"
给
"staging_ports": {
"staging_core_api": 7201,
"staging_import_export": 7207,
"staging_stock_api": 7204,
"staging_webadmin": 7209,
"staging_webui": 7200
}
推荐阅读
- python - url {% url employees:check_matricule %} 没有在 forms.py 中运行
- javascript - 响应式顶部导航仅适用于手机
- python - Jupyter 笔记本感叹号参数
- reactjs - 使用 NextJS 在 Reactjs 中导入 jpg 图像 一些图像导入返回长字符串
- c# - C# EnumerateDirectories 不应使用本地化路径
- angular - 角拉伸垫卡
- apache-kafka - Kafka - 控制器代理
- python - TypeError:尝试训练 MASK_RCNN 实现时,字符串索引必须是整数
- python - 抓取没有属性的纯html
- vb.net - VB.net XmlDocument .selectNodes