Ansible - Perform a lookup on a dictionary mapped to a list, but treat values in list as strings

Viewed 513

In the dictionary MyDict, the second dictionary in the nested list has the name key set to an integer value (101). Hence, the lookup in the debug statement is returning false. Is there a way to make the lookup convert the values in the list to strings, so that true will be returned in this example? Thanks!

---
 - hosts: localhost
  
   vars:
     MyDict:
       - name: Bob
       - name: 101      <-- This is a value entered by a user, which happens to be an integer

     findname: "101"    <-- This is a string i wish to find in the dictionary

   tasks:
    - debug: msg="{{ findname in MyDict | map(attribute='name') | list }}"   <-- I want the lookup to return true

1 Answers

Convert all items of the list to strings. For example

- debug:
    msg: "{{ findname in MyDict|
             map(attribute='name')|
             map('string')|
             list }}"

Convert also the variable findname to make sure you compare always stings

- debug:
    msg: "{{ findname|string in MyDict|
             map(attribute='name')|
             map('string')|
             list }}"

Test it in the loop. For example

    - debug:
        msg: "{{ item|string in MyList }}"
      loop:
        - Bob
        - 101
        - "101"
        - Joe
      vars:
        MyList: "{{ MyDict|
                    map(attribute='name')|
                    map('string')|
                    list }}"

gives

ok: [localhost] => (item=Bob) => {
    "msg": true
}
ok: [localhost] => (item=101) => {
    "msg": true
}
ok: [localhost] => (item=101) => {
    "msg": true
}
ok: [localhost] => (item=Joe) => {
    "msg": false
}
Related