首页 > 解决方案 > 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') }}"

但是看起来真的很丑,有没有更好看的解决方案?

标签: ansiblejinja2

解决方案


使用简单的过滤器

    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
    }

推荐阅读