How to use databag in template

I have a generic recipe which just loops over templates The recipe do not and can not pass any variables to template, and currently template is getting everything directly from node attributes.

Now, I need to use databag as some of these node attributes are sensitive and must be moved to a databag.

How can I achieve this by still keeping my recipe generic? any code code sample to access data bag from template(erb) will be appreciated.



Hi @Marathiboy,

The databag was designed to store global attributes that are accessable by all nodes bootsrapped to the chef-server and by anyone who has the necessary pem files to authenticate to the chef-server.
If you really want to keep secrets that are sensitive data you should atleast use encrypted databags
or better, chef-vault

But back to the original question...
You can overwrite the corresponding attributes in the recipe through the node object before starting the iteration over the templates:
node.default[your_attribute] = data_bag_item('bag_name', 'item')

The problem with this solution that the node object now contains the sensitive data and it will be stored in plaintext on the chef-server at the end of the chef-cilent run.
To avoid this you can blacklist the sensitive attributes
or better try using variable option in the templates resource and read the databag directly into the variable.

Hopes this help

Here's an example of how I loop through an encrypted databag in an .erb template.


This helps!


When I try to do this, I end up getting and error:

uninitialized constant Chef::Databag

Is there something I need to do at the recipe level or somewhere else in order for this syntax to work properly?


Just noticed I have "Databag" instead of "DataBag"

I've gotten past the error after fixing the stupid syntax issue using lowercase. Now, I'm trying to figure out how to actually get to the data. I haven't been able to find how to drill down into the data bag and get the information I need.

So, my data bag is structured like this:

$ knife data bag show ldapservers corp-domain

dnsserver1:  dnsserver1
dnsserver2: dnsserver1
id:         corp-domain

In my template, I have:

<% ldapservers = Chef::DataBag.load( 'ldapservers' ) %>
<% ldapservers.each do |dc| %>
<% adserver = Chef::DataBagItem.load( 'ldapservers', dc[0] ) %>
adserver:<%= adserver %>
<% end %>

When I run the recipe, the 'adserver' gets resolved to:

adserver: data_bag_item(corp-domain)

So, how do I reference the data bag to get the server names out so that I can populate templates for /etc/ntp.conf, /etc/resolv.conf and /etc/ldap.conf files?

Sorry...this stuff is very new to me. Thanks for any help!