Home > Net >  Replace items in a list ansible playbook
Replace items in a list ansible playbook

Time:02-10

I have the following dictionary:

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

I would execute a replacement over the items of the above lists and tried this:

- 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

With the values of the list:

  • If the value ends with m, I want to remove it and divide the value per 1000.
  • If the value is only a number, multiply per 1000

I get the following error:

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

Could anyone help me?

CodePudding user response:

For example, given the data

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

the task below does the job

    - 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 %}

gives

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

If you change the data

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

the result will be (ansible [core 2.12.1])

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

Use select if you want to silently omit empty items. For example, change the line

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

The result will be

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

CodePudding user response:

If you literally want to replace an 'm' with '000' when the 'm' is preceded by a digit and succeeded by a " you could do:

  • enter image description here

    As far as the other part of the statement:

    I want to remove the "m" and divide per 1000 where occurres the "m" at last of the string, and moltiplicate per 1000 in the other cases.

    I'm sorry but I don't understand, so if you could please clarify I could update the answer.

  • Related