Home > Blockchain >  Ansible - Remove items from a dict if condition is met
Ansible - Remove items from a dict if condition is met

Time:10-08

I have a dict1 from which I want to remove all items where b is null, that means not just the property b, but the whole dictionary.

- hosts: localhost
  gather_facts: false

  vars:
    dict1: [{a:1,b:2,c:3},{a:1,b:"null",c:3},{a:1,b:2,c:3}]

  tasks: 
  - set_fact:
      dict2: "{{item | reject(item.b, 'eq', 'null')}}"
    loop: "{{dict1}}"

The output should look like this:

dict2: [{a:1,b:2,c:3},{a:1,b:2,c:3}]

Note: there can be N items in the dictionary and/or N key-value pairs in the same dictionary. Also, there can be N number of b's in the dictionary that have null values, so it has to remove of all them.

CodePudding user response:

You can use the selectattr filter to filter a list of dictionaries.

Given the task:

- debug:
    var: dict1 | selectattr('b', '!=', 'null')

This would yield:

dict1 | selectattr('b', '!=', 'null'):
  - a: 1
    b: 2
    c: 3
  - a: 1
    b: 2
    c: 3

CodePudding user response:

A solution with a simple loop and test:

- name: "tips2"
  hosts: localhost
  gather_facts: false

  vars:
    dict1: [{"a": 1, "b": 2, "c": 3}, {"a": 1, "b": "null", "c": 3},{"a": 1, "b": 2, "c": 3}]

  tasks: 
    - set_fact:
        dict2: "{{dict2 | default([])    [item] }}"
      loop: "{{dict1}}"
      when: item.b != "null"

    - name: debug users      
      debug:
        msg: "{{dict2}}"
 

result:

ok: [localhost] => {
    "msg": [
        {
            "a": 1,
            "b": 2,
            "c": 3
        },
        {
            "a": 1,
            "b": 2,
            "c": 3
        }
    ]
}

CodePudding user response:

Given the dictionary with null value instead of the string "null"

dict1:
  - {a: 1, b: 2, c: 3}
  - {a: 1, b: null, c: 3}
  - {a: 1, b: 2, c: 3}

Use selectattr without a test

    - debug:
        var: dict1|selectattr('b')

gives

dict1|selectattr('b'):
  - {a: 1, b: 2, c: 3}
  - {a: 1, b: 2, c: 3}

Quoting:

If no test is specified, the attribute’s value will be evaluated as a boolean.

  • Related