6

Looking at this official documentation: https://docs.chef.io/resource_template.html I see examples of passing variables to the Template resource that use either "{", "({" or "(" to scope the variables.

I cannot find a place explaining the difference or why I would use one form over the other. Is there really any practical difference when running the recipe?

Example 1:

template '/tmp/config.conf' do
  source 'config.conf.erb'
  variables(
  :config_var => node['configs']['config_var']
)
end

Example 2:

template '/tmp/config.conf' do
  source 'config.conf.erb'
  variables{
  :config_var => node['configs']['config_var']
}
end

Example 3:

template '/tmp/config.conf' do
  source 'config.conf.erb'
  variables({
  :config_var => node['configs']['config_var']
})
end
Mike Fiedler
  • 2,152
  • 1
  • 17
  • 33
cb2
  • 163
  • 1
  • 1
  • 5

1 Answers1

8

This is a ruby thing, not a chef thing.

When you use ( :key => value ) you are passing in an implied hash. Ruby decides that what it sees inside the parens is hash-like, and converts to a hash automatically.

When you use { }, you are actually passing a block. Ruby then executes the block, and passes the results of the block back as arguments. I have found this notation to be, by far, the most likely to cause you trouble.

When you use ({ :key => value }) you are explicitly passing a hash to the method. The parens explicitly define the method arguments, and the brackets are the standard notation for defining a hash (no ruby magic to auto-detect the hash-ness of the arguments).

I would say there is no definitive best/right way, but the ruby style guides seem to prefer the first version.

Tejay Cardon
  • 379
  • 1
  • 4