具有 For Each 语句和属性数组的多个 Chef 模板

Multiple Chef Templates with a For Each statement and an attribute array

我正在尝试使用 Chef 11.10 为我的网络服务器上的虚拟主机数组创建多个单独的 .conf 文件。我希望每个虚拟主机的这些文件的内容略有不同。

当前的实现创建了不同的文件名(数组中的每个文件名 1 个。)但是模板每次只包含数组中的最后一项。

例如,数组中有 3 个虚拟主机 - example1.com、example2.com、example3.com。在我的 /var/www/conf.d/ 目录中,在食谱 运行

之后我有 3 个文件
> example1.com.conf 
> example2.com.conf 
> example3.com.conf

这是一个好的开始,但是,这些文件的内容与正在使用的数组中的最后一个变量完全相同。他们都以 "example3.com" 作为主持人,例如。

server {
  listen   80;
  server_name  example3.com;
  return 301 https://$host$request_uri;
}

我的食谱包含这个

vhosts = node['nginx']['vhosts']

vhosts.each do |vhost|
  node.default['nginx']['hostname'] = vhost

  template "#{node[:nginx][:conf_dir]}/#{vhost}.conf" do
    source "#{node[:nginx][:vhost_template]}"
    owner "root"
    group "root"
    mode 0644
    notifies :restart, resources(:service => "nginx")
  end
end

在我的模板中有以下代码

  server {
  listen   443;
  server_name  <%= node[:nginx][:hostname] %>;
  return 301 http://$host$request_uri;
}

在我的 attributes/default.rb 文件中,我有以下数组。

default[:nginx][:vhosts] = [ "example1.com", "example2.com", "example3.com" ]

在循环中设置单个节点属性没有意义。由于 Chef 的执行,只有最后一个值在实际创建模板资源时保留。尝试删除此行:

node.default['nginx']['hostname'] = vhost

然后 pass vhost in the template variables 属性并在 .erb 文件中使用它。

(另外,作为参考,您通常不想在配方中设置默认节点属性,这是使用 node.default[...] 所做的,但这不是这里的根本问题。)