替换列表和可选行动手册中的项目 [英] Replace items in a list ansible playbook

查看:17
本文介绍了替换列表和可选行动手册中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下词典:

{
  "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

使用列表的值:

  • 如果该值以m结尾,我希望将其删除并将该值除以每1000。
  • 如果值只是一个数字,则每1000乘一次

我收到以下错误:

";msg";:";模板类型错误出现在({{result|default({})|Combine({item.key:item.value|map((Item is Match(‘.*m’))|三元(Item[:-1]|int/1000,Item|int*1000)|List})}})):不可散列类型:‘Slice’&qot;

有人能帮我吗?

推荐答案

例如,给定数据

    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]

如果要静默省略空项目,请使用选择。例如,更改行

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

结果将是

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

这篇关于替换列表和可选行动手册中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆