【问题标题】:Ansible variable interpolationAnsible 变量插值
【发布时间】:2022-01-09 21:00:49
【问题描述】:

显然我在这里遗漏了一些东西(很明显?):-( 字典在调试中被正确解析为 var,但我无法将其放入消息(msg)中。在这种情况下如何正确触发插值? (实际用例不是调试,但这是我可以构建的最简单的示例)。

---
- name: Setup based on subnet
  hosts: 
    - localhost
  vars:
    siteVars:
      10.128.0.0:
        ServerName:  "AServ"
      10.0.0.0:
        ServerName:  "BServ"
 
  tasks:
  - name: Do we get the right Network
    debug: 
      msg: "{{ ansible_default_ipv4.network }}"

  - name: Var works
    debug: 
      var: siteVars[ {{ 'ansible_default_ipv4.network' }} ].ServerName

  - name: Msg does not work interpolate
    debug:
       msg: "siteVars[ {{ 'ansible_default_ipv4.network' }} ].ServerName"   

给予:

TASK [Do we get the right Network] ******************************************************************************************ok: [localhost] => {
    "msg": "10.0.0.0"
}

TASK [Var works] ******************************************************************************************ok: [localhost] => {
    "siteVars[ ansible_default_ipv4.network ].ServerName": "BServ"
}

TASK [Msg does not work interpolate] ******************************************************************************************ok: [localhost] => {
    "msg": "siteVars[ ansible_default_ipv4.network ].ServerName"
}

【问题讨论】:

    标签: dictionary ansible interpolation


    【解决方案1】:

    在这种情况下如何正确触发插值?

    由于siteVarsServerName 也是数据结构(变量)的一部分,因此大括号也需要将它们包围起来。

    - name: Msg work interpolate too
      debug:
        msg: "{{ siteVars[ansible_default_ipv4.network].ServerName }}"
    

    导致输出

    TASK [Msg work interpolate too] ***
    ok: [localhost] =>
      msg: BServ
    

    这里有其他相关问题

    文档

    【讨论】:

    • 请注意,虽然对于初学者来说有点混乱,但debug 的以下选项有效:var: siteVars["{{ ansible_default_ipv4.network }}"].ServerName
    • 非常感谢您让我走上正轨。非常感谢。
    猜你喜欢
    • 2016-08-05
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-06-10
    相关资源
    最近更新 更多