ruby 模板中的深层 hiera 查找 returns 仅最后结果

Deep hiera lookup in a ruby template returns last result only

我有以下等级:

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

我尝试在 erb 模板中按以下方式调用它:

<% @example = scope().call_function('hiera',['profile::example::firewalls']) -%>
show me the array!
<%= @example %>

奇怪的是 return 如下:

+show me the array!
+[{"serverclass1"=>nil, "label"=>"https", "port"=>443}, {"serverclass2"=>nil, "label"=>"telnet", "port"=>21}]

一旦我有了一个完整的数组,我最终会在 ruby 内的 for/each 循环中使用它,但目前这似乎 return 只是最终结果,而不是一切如我所愿。

问题始于您的 YAML 数据结构,其中包含重复的 "label" 键。这就是为什么您的某些数据在输出中丢失的原因。

(有关详细信息,请参阅 this 相关的 Stack Overflow 答案。)

虽然还不完全清楚您要做什么,但在我看来,使用这样的 YAML 数据结构会更好:

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

然后您可以使用如下代码在 ERB 模板中迭代它:

<% scope().call_function('lookup',['profile::example::firewalls']).each do |server_class, data| -%>
Server class: <%= server_class %>
  <%- data.each do |key, value| -%>
  <%= key %> --- <%= value %>
  <%- end -%>
<% end -%>

另请注意,我删除了已弃用的 hiera() 函数并将其替换为 lookup()