将 puppet hash 用于 epp 模板

Using puppet hash for epp templates

我在 erb 模板中有下一个代码:

<% if @proxy_cache_path.is_a?(Hash) -%>
<% @proxy_cache_path.sort_by{|k,v| k}.each do |key,value| -%>
  proxy_cache_path        <%= key %> keys_zone=<%= value %> levels=<%= @proxy_cache_levels %> max_size=<%= @proxy_cache_max_size %> inactive=<%= @proxy_cache_inactive -%>
<% end -%>

如何移植到epp模板?我发现它的信息很少。请帮忙。

你可以这样做:

显示示例 class 以及如何声明 ERB 和 EPP 模板以进行比较:

# manifests/init.pp
class foo () {
  $proxy_cache_path = {
    'apples'  => 1,
    'bananas' => 2,
  }
  $proxy_cache_levels = 2
  $proxy_cache_max_size = 2
  $proxy_cache_inactive = 2

  # Showing use of ERB:
  file { '/foo':
    ensure  => file,
    content => template('foo/mytemplate.erb')
  }

  # Showing use of EPP, which requires an explicit parameters hash:
  file { '/bar':
    ensure  => file,
    content => epp('foo/mytemplate.epp', {
      'proxy_cache_path'     => $proxy_cache_path,
      'proxy_cache_levels'   => $proxy_cache_levels,
      'proxy_cache_max_size' => $proxy_cache_max_size,
      'proxy_cache_inactive' => $proxy_cache_inactive,
    }),
  }
}

更正*用于比较的 ERB 文件内容:

# templates/mytemplate.erb     
<% if @proxy_cache_path.is_a?(Hash) -%>
<% @proxy_cache_path.sort_by{|k,v| k}.each do |key,value| -%>
  proxy_cache_path        <%= key %> keys_zone=<%= value %> levels=<%= @proxy_cache_levels %> max_size=<%= @proxy_cache_max_size %> inactive=<%= @proxy_cache_inactive -%>
<% end -%>
<% end -%>

(*问题中的代码缺少结尾 end。)

EPP 文件的内容:

# templates/mytemplate.epp 
<%- | Hash[String, Integer] $proxy_cache_path, Integer $proxy_cache_levels, Integer $proxy_cache_max_size, Integer $proxy_cache_inactive | -%>
<% include stdlib -%>
<% $proxy_cache_path.keys.sort.each |$key| { -%>
  proxy_cache_path        <%= $key %> keys_zone=<%= $proxy_cache_path[$key] %> levels=<%= $proxy_cache_levels %> max_size=<%= $proxy_cache_max_size %> inactive=<%= $proxy_cache_inactive -%>
<% } -%>

EPP模板文件内容注意事项:

1) 参数及其类型定义在模板的第一行。此行的使用是可选的,但这是一种很好的做法。

2) 由于我们在第一行声明了类型,因此测试 $proxy_cache_path 是否为哈希是不必要且多余的。

3) 我们需要包含 stdlib 才能访问函数 keyssort。这与 Ruby (ERB) 不同,其中这些方法内置于语言中。

4) 我简化了相对于 Ruby (ERB) 的代码,因为 Puppet (EPP) 没有 sort_by 函数——实际上也没有必要在 ERB 中使用它,可以重写为:

<% if @proxy_cache_path.is_a?(Hash) -%>
<%   @proxy_cache_path.sort.each do |key,value| -%>
  proxy_cache_path        <%= key %> keys_zone=<%= value %> levels=<%= @proxy_cache_levels %> max_size=<%= @proxy_cache_max_size %> inactive=<%= @proxy_cache_inactive -%>
<%   end -%>
<% end -%>

最后一些测试:

# spec/classes/test_spec.rb:
require 'spec_helper'

describe 'foo', :type => :class do
  it 'content in foo should be the same as in bar' do
    foo = catalogue.resource('file', '/foo').send(:parameters)[:content]
    bar = catalogue.resource('file', '/bar').send(:parameters)[:content]
    expect(foo).to eq bar
  end
end

测试通过。

查看文档 here