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?

1 Answer 1

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.

2
  • 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 :) Sep 25, 2017 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, 2017 at 17:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .