gpt4 book ai didi

ansible - 使用 "bracket notation"索引变量并不总是在 ansible 中工作

转载 作者:行者123 更新时间:2023-12-04 08:28:19 25 4
gpt4 key购买 nike

我是新来的 ansible并按照说明 here它给出了两个用于引用键值字典的符号。

foo['field1']
foo.field1
并说“括号表示法始终有效”。我试试
  vars: 
- london:
- nodename : music0
- card: Headphone
- mixer: Hardware


- debug:
msg: nodename "{{ london[0] }} "
- debug:
msg: nodename "{{ london['nodename'] }} "
第一个冬季引用 [0] 似乎没问题:
TASK [debug] *******************************************************************
ok: [127.0.0.1] => {
"msg": "nodename \"{u'nodename': u'music0'} \""
}
但不是括号符号:
fatal: [127.0.0.1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'nodename'\n\nThe error appears to be in '/home/frank/Data/ansibleHost/testVars.yml': line 29, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - debug:\n      ^ here\n"}
与已发布的示例有何不同?我承认我不明白错误信息... list object应该是 london其中有一个 attribute - 还是我误解了变量声明?
我将不胜感激推荐一个全面的教程!

最佳答案

对我来说,您的问题似乎是您正在混合 listsdictionaries .

  • 这是一个字典,您可以使用 london.nodename 访问其中的元素或 london['nodename']
    london: 
    nodename: music0
    card: Headphone
    mixer: Hardware
  • 虽然您拥有的是包含其他字典列表的字典列表:
    foo:
    - london:
    - nodename: music0
    - card: Headphone
    - mixer: Hardware
    您可以使用基于 0 的索引语法访问它:foo.0.london.0.nodename但我非常怀疑这不是您正在寻找的数据结构。以与上述相同的方式,foo[0]['london'][0]['nodename']也会工作
  • 有关列表更像的进一步示例:
    fruits:
    - banana
    - apple
    - orange
    - lemon
    然后对于基于 0 的索引的进一步解释,例如,您可以访问 orange通过 fruits.2fruits[2]

  • 如果您不想更改数据结构:
    - hosts: all
    gather_facts: no

    tasks:
    - debug:
    msg: "{{ london.0.nodename }}"
    vars:
    - london:
    - nodename: music0
    - card: Headphone
    - mixer: Hardware
    给出:
    PLAY [all] *******************************************************************************************************

    TASK [debug] *****************************************************************************************************
    ok: [localhost] => {
    "msg": "music0"
    }

    PLAY RECAP *******************************************************************************************************
    localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
    现在为什么不用说 0.london.0.nodename ,你会问?
    这是因为 vars不期望一个列表而是一个字典,而 Ansible 对你太客气了,把它当作字典。

    关于ansible - 使用 "bracket notation"索引变量并不总是在 ansible 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65148619/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com