How to use databag in template


#1

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.

Thanks

M


#2

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
https://docs.chef.io/data_bags.html
or better, chef-vault
https://docs.chef.io/chef_vault.html

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
https://docs.chef.io/attributes.html#blacklist-attributes
or better try using variable option in the templates resource and read the databag directly into the variable.

Hopes this help


#3

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


#4

Thanks

This helps!

M