可以打印有另一个变量的变量值

发布于 2025-02-13 07:51:20 字数 641 浏览 5 评论 0原文

在a.yml文件中,我在xyz.yml playbook中存储了如下以下数据

---
 Server:
   "Node1" : ["Node1", "Owner1", "ID1"]
   "Node2" : ["Node2", "Owner2", "ID2"]

,我试图在下面进行调试,然后在commandline中传递node_name(ansible -playbook xyz.yz.yml -e“ node_name = node = node1” )

---
 - name: "Print Variable value"
   hosts: all
   gather_facts: no
   vars:
     Node_Name: Node
     ID_Name: "{{ Server.{{ Node_Name }}[2] }}"
   tasks:
   - name: "Print the id"
     debug:
       msg:
         - "The id is {{ ID_Name }}"

但是,这是错误的失败 - 模板字符串时的模板错误:预期名称或号码

有人可以帮助解决此问题,并让我知道如何将ID打印为输出。这里预期的输出是ID1

In a.yml file, I have stored data like below

---
 Server:
   "Node1" : ["Node1", "Owner1", "ID1"]
   "Node2" : ["Node2", "Owner2", "ID2"]

Now, in xyz.yml playbook, I tried to debug a variable as below and I am passing the Node_Name in commandline (ansible-playbook xyz.yml -e "Node_Name=Node1")

---
 - name: "Print Variable value"
   hosts: all
   gather_facts: no
   vars:
     Node_Name: Node
     ID_Name: "{{ Server.{{ Node_Name }}[2] }}"
   tasks:
   - name: "Print the id"
     debug:
       msg:
         - "The id is {{ ID_Name }}"

But this is failing with error - Template error while templating string :expected name or number

Can someone please help to fix this and let me know how can I get the ID printed as output. Here expected output is ID1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

靑春怀旧 2025-02-20 07:51:20

您永远不会嵌套{{...}}标记。

回想一下,访问嵌套变量。语法server.node1完全等于server [“ node1”]。第二种语法使我们能够在密钥上使用变量(和字符串插值),因此我们可以写:

Server[Node_Name]

换句话说:

- name: "Print Variable value"
  hosts: all
  gather_facts: no
  vars:
    Node_Name: Node
    ID_Name: "{{ Server[Node_Name][2] }}"
  tasks:
  - name: "Print the id"
    debug:
      msg:
        - "The id is {{ ID_Name }}"

You never nest {{...}} markers.

Recall that to access a nested variable. the syntax Server.Node1 is exactly equivalent to Server["Node1"]. The second syntax allows us to make use of variables (and string interpolation) on the key, so we can write:

Server[Node_Name]

In other words:

- name: "Print Variable value"
  hosts: all
  gather_facts: no
  vars:
    Node_Name: Node
    ID_Name: "{{ Server[Node_Name][2] }}"
  tasks:
  - name: "Print the id"
    debug:
      msg:
        - "The id is {{ ID_Name }}"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文