您可以按照以下方法执行此操作:
显示示例类以及如何声明 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才能访问函数keys
and sort
。这与 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.