philant
philant

Reputation: 35806

How to access Chef metadata from a template

I can get the metadata via the run_context object and for instance, write them to a file:

file '/etc/motd' do
  content "setup by [#{cookbook_name}] v#{run_context.cookbook_collection[cookbook_name].metadata.version}"
end

When I try to do the same in a template:

template 'etc/motd' do
  source 'default/motd.erb'
end

The motd.erb template file is as follows:

generated by <%= run_context.cookbook_collection['cookbook_name'].metadata.version %>

I've got a error because the run_context is not a method of TemplateContext:

Chef::Mixin::Template::TemplateError (undefined local variable or method `run_context' for #<Chef::Mixin::Template::TemplateContext:0x00000002c70c20>) on line #2:

TemplateContext does not seem to offer any way to retrieve the metadata. Is there a way to access to run_context from there ?

Upvotes: 0

Views: 394

Answers (1)

coderanger
coderanger

Reputation: 54181

Technically you can access it via @node.run_context but I really wouldn't do this. You are hitting about 5 different internal APIs, we make no promises this won't break on Chef upgrades.

Upvotes: 3

Related Questions