替换列表中的项目ansible playbook

Replace items in a list ansible playbook

我有以下词典:

{
  "test1": ["300m","","0","4","1050m"],
  "test2": ["600m","","","0","2"]
}

我将对上述列表中的项目执行替换并尝试这样做:

- set_fact:
    result: "{{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}"
  with_items: "{{dict_ns_cpu | dict2items}}"
  ignore_errors: true

使用列表的值:

我收到以下错误:

"msg": "Unexpected templating type error occurred on ({{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}): unhashable type: 'slice'"

谁能帮帮我?

如果当 'm' 前面有一个数字并且后面有 " 时,如果你真的想用 '000' 替换 'm' 你可以这样做:

例如给定数据

    dict_ns_cpu:
      test1: ["300m","50m","0","4","1050m"]
      test2: ["600m","400m","10m","0","2"]

下面的任务可以完成工作

    - set_fact:
        result: "{{ result|d({})|combine({item.key: _list|from_yaml}) }}"
      loop: "{{ dict_ns_cpu|dict2items }}"
      vars:
        _list: |-
          {% for i in item.value %}
          {% if i is match('.*m') %}
          - {{ i[:-1]|int / 1000 }}
          {% else %}
          - {{ i|int * 1000 }}
          {% endif %}
          {% endfor %}

给予

  result:
    test1: [0.3, 0.05, 0, 4000, 1.05]
    test2: [0.6, 0.4, 0.01, 0, 2000]

如果更改数据

    dict_ns_cpu:
      test1: ["300m","","0","4","1050m"]
      test2: ["600m","","","0","2"]

结果将是 (ansible [core 2.12.1])

  result:
    test1: [0.3, 0, 0, 4000, 1.05]
    test2: [0.6, 0, 0, 0, 2000]

如果您想静默省略空项目,请使用 select。例如,更改行

          {% for i in item.value|select %}

结果会是

  result:
    test1: [0.3, 0, 4000, 1.05]
    test2: [0.6, 0, 2000]