我正在尝试为不同的环境构buildnginx文件。 我的食谱有这样的hashmap:
domain = { production: { public: 'example.com', internal: 'example.dev' }, staging: { public: 'examplestage.com', internal: 'examplestage.dev' } } template '/etc/nginx/conf.d/example.conf' do source 'example.conf.erb' variables( :domain => domain, ) end
在我的模板中,我想要做这样的事情:
... server <%= @domain[node.chef_environment][:public] %> <%= @domain[node.chef_environment][:public] %>; ...
我试图得到这个评估是这样的,这取决于节点属于staging
或production
的环境:
server example.com example.dev;
问题是, node.chef_environment
部分不能被内插。 我如何解决这个问题?
我怀疑你的代码失败,因为“node.chef_environment”是一个string,而你的散列键是符号。 如果是这种情况,可以使用@domain[node.chef_environment.to_sym][:public]
。
但是:通常最好避免将这种逻辑放入模板中,而是在配方中进行:
template '/etc/nginx/conf.d/example.conf' do source 'example.conf.erb' variables( :domains => domain[node.chef_environment.to_sym], ) end
然后,在模板中:
... server <%= @domains[:public] %> <%= @domains[:internal] %>; ...
在阅读这个配方代码的时候,显然这个模板不会使用所有的域,只是那些和它的环境有关的域。 阅读模板时,variables更短,更容易阅读。