簡體   English   中英

Ansible - 對映射到列表的字典執行查找,但將列表中的值視為字符串

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

在字典 MyDict 中,嵌套列表中的第二個字典的名稱鍵設置為整數值 (101)。 因此,調試語句中的查找返回 false。 有沒有辦法讓查找將列表中的值轉換為字符串,以便在此示例中返回 true? 謝謝!

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

將列表的所有項目轉換為字符串。 例如

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

還轉換變量findname以確保您比較總是刺痛

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

在循環中測試它。 例如

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM