Score:0

Ansible select elements that are blanks from a list

cn flag
raw

I need a variable with all the blank elements present in the _names list. I tried this :

blanks: "{{ _names|select('search', '') | list }}"

But it dosent seem to work

here is the list:

    "_names":
    [
        "",
        "ABC",
        "",
        ""
    ]

To give some context, I need this variable to count the blank elements and compare it.

Score:0
fr flag

The easy intuitive way is to select the elements equal to an empty string. An other one a bit counter intuitive but more compact to write is to simply reject elements (which by default will reject all non empty values). The following playbook demonstrate both solutions which give the same result.

Note: the reject method here will only work as long as other non-empty elements in the list do not evaluate to false. If you ever false boolean values, they will be retained as well

- hosts: localhost
  gather_facts: false

  vars:
      _names:  ["","ABC","",""]
      blanks_select: "{{ _names | select('==', '') | list }}"
      blanks_reject: "{{ _names | reject | list }}"

  tasks:
    - debug:
        var: "{{ item }}"
      loop:
        - blanks_select
        - blanks_reject

Which gives:

PLAY [localhost] *********************************************************************

TASK [debug] *********************************************************************
ok: [localhost] => (item=blanks_select) => {
    "ansible_loop_var": "item",
    "blanks_select": [
        "",
        "",
        ""
    ],
    "item": "blanks_select"
}
ok: [localhost] => (item=blanks_reject) => {
    "ansible_loop_var": "item",
    "blanks_reject": [
        "",
        "",
        ""
    ],
    "item": "blanks_reject"
}

PLAY RECAP *********************************************************************
localhost : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
br flag
The *reject* variant works if there is no item in the list that evaluates to *False*. You can convert the items to strings first if you want to, e.g. ``blanks: "{{ _names|map('string')|reject|length }}"``.
Zeitounator avatar
fr flag
@VladimirBotka absolutely correct, hence why I gave the two approach in case the current input example evolves. I added that precision in the answer though. Thanks.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.