0

I'm trying to build nginx files for different environments. My recipe has a hashmap like so:

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

In my template, I want to do something like this:

...
server <%= @domain[node.chef_environment][:public] %> <%= @domain[node.chef_environment][:public] %>;
...

I'm trying to get this to evaluate to something like this, depending on the environment the node belongs to staging or production:

server example.com example.dev;

The problem is that, the node.chef_environment part does not get interpolated. How do I solve this?

3

I suspect your code fails because 'node.chef_environment' is a string, while your hash keys are symbols. If that is the case, @domain[node.chef_environment.to_sym][:public] may work.

However: it's usually best to avoid putting that kind of logic into your template - do it in the recipe instead:

template '/etc/nginx/conf.d/example.conf' do
  source 'example.conf.erb'
  variables(
    :domains => domain[node.chef_environment.to_sym],
  )
end

Then, in the template:

...
server <%= @domains[:public] %> <%= @domains[:internal] %>;
...

When reading this recipe code, it is clear that the template will not be using all the domains - just those related to its environment. When reading the template, the variables are shorter and easier to read.

  • Chef converts symbols to strings, I think. I tried different combinations and the only time it fails is if I try to do interpolation in the template. Doing the logic in the recipe works whether I convert it to a symbol or not. Thanks for the help :) – eternaltyro Sep 25 '17 at 8:20
  • 1
    @eternaltyro Chef attributes are a special datastructure called a Mash, which does indeed normalise keys by converting symbols to strings. However, your example showed a plain old ruby Hash - Chef doesn't affect how those work. So I'm not sure how that would work, but glad to hear it did! – zts Sep 26 '17 at 17:31

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.