You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby模板中Hiera深度查找仅返回最后结果的问题排查

问题原因与解决方案

你的问题根源出在YAML哈希的重复键处理规则上——YAML规范明确规定,当同一个哈希里出现重复的键时,后面的键值对会直接覆盖前面的。你原来的Hiera数据中,每个serverclass下面都重复定义了label和port键,所以解析后只会保留每组的最后一项。

修正Hiera数据结构

要保留所有服务条目,你需要把每个服务做成数组的元素,而不是重复使用相同的哈希键。调整后的Hiera数据应该是这样:

profile::example::firewalls:
  - serverclass1:
      - label: http
        port: 80
      - label: https
        port: 443
  - serverclass2:
      - label: ssh
        port: 22
      - label: telnet
        port: 21

或者用更紧凑的行内哈希格式也可以:

profile::example::firewalls:
  - serverclass1: [{ label: http, port: 80 }, { label: https, port: 443 }]
  - serverclass2: [{ label: ssh, port: 22 }, { label: telnet, port: 21 }]

调整ERB模板的遍历逻辑

修正数据结构后,你可以在ERB里通过嵌套循环来处理每个服务器组和对应的服务:

<% @firewalls = scope().call_function('hiera',['profile::example::firewalls']) -%>
<% @firewalls.each do |server_group| %>
  <% server_group.each do |class_name, services| %>
    ### 服务器组: <%= class_name %>
    <% services.each do |service| %>
      - 服务标签: <%= service['label'] %>,端口: <%= service['port'] %>
    <% end %>
  <% end %>
<% end %>

这样就能完整遍历所有的服务条目,不会再出现被覆盖的情况了。

内容的提问来源于stack exchange,提问作者user486670

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:47:19