【问题标题】:Ansible escaping dots to use with map function as attributesAnsible 转义点与 map 函数一起用作属性
【发布时间】:2019-04-06 13:45:28
【问题描述】:

我有一个对象变量的键,我无法在 Ansible playbook 中转义,可能是因为包含点,

这是variable的数据结构:

"results":[
  {
    //snip//

    "changed": false,
    "hostvars[item].commandResult.stdout": "abc",

    //snip//
  },
  {
    //snip//

    "changed": true,
    "hostvars[item].commandResult.stdout": "xyz",

    //snip//
  }
]

我无法使用此剧本提取其中的"hostvars[item].commandResult.stdout"

  - debug:
       msg: "{{variable.results | map(attribute='hostvars[item].commandResult.stdout') }}"

虽然我可以得到其他价值就好了,

      - debug:
          msg: "{{variable.results | map(attribute='changed') }}"

我尝试使用\'.'{{...}} 来逃避.(点),但仍然没有运气。 我怀疑它是.,因为这个错误消息:

  msg: |-
The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'hostvars[item]'

当运行ansible-playbook -vvv 命令时

如何映射"hostvars[item].commandResult.stdout"

【问题讨论】:

  • 请发布一个完整的独立示例。我无法以 sn-p 形式关注您的问题。
  • @GeorgeShuklin,对不起,我希望现在更清楚...
  • 呃...我会说你有一把非常不寻常的钥匙。你能在你拯救他们的地方让它变得不那么奇怪吗?这确实是某种奇怪的错误,但我在实践中从未见过这样的键。
  • 我必须使用该密钥来引用 Ansible 的 hostvars 以将多个主机的结果组合到 commandResult 中。是的,我在其他地方读到的也仍未解决。 ://

标签: ansible escaping yaml jinja2


【解决方案1】:

要使用点来寻址键,请使用带单引号的数组表示法而不是点表示法,即:

- debug:
    msg: "{{variable.results | map(attribute=['hostvars[item].commandResult.stdout']) }}"

这会返回值。

cf.:Ansible 常见问题解答

【讨论】:

    【解决方案2】:

    结果我首先将其包裹在 Ansible set_fact 中:

      - set_fact:
        variable: "{{hostvars[item].commandResult.stdout_lines}}"
        with_items: "{{ groups['servers'] }}"
        register: all_result
    
      - debug:
            msg: "{{all_result.results |  map(attribute='ansible_facts') | list  | to_nice_json }}
    

    不过,转义点的原始问题仍未得到解答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-03
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多