Riccardo Califano
Riccardo Califano

Reputation: 1847

Replace items in a list ansible playbook

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:

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?

Upvotes: 0

Views: 3050

Answers (2)

David542
David542

Reputation: 110482

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

Upvotes: 1

Vladimir Botka
Vladimir Botka

Reputation: 68254

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]

Upvotes: 1

Related Questions