Creating an encrypted Databag in Chef


Create a random encryption key:
openssl rand -base64 512 | tr -d '\r\n' > secret_key 

Use this to encrypt a data bag item named “passwords” located in a data bag named “production”:
knife data bag create −−editor /usr/bin/vi −−secret-file ./secret_key production passwords

This will open an text editor, example JSON data would be:
{
  "id": "passwords",
  "mysql": "yourmysqlpassword",
  "ssh": "yoursshpassword"
}

Save and exit.

Show the encrypted contents of your databag:
knife data bag show production passwords

Show the decrypted contents of your databag:
knife data bag show −−secret-file=./secret_key production passwords

For your chef clients to be able to decrypt the databag when needed, just copy over the secret key (replace client-node with your IP/node name):
scp ./secret_key client-node:/etc/chef/encrypted_data_bag_secret

Given you have a recipe mysql, that will be run on your client, your .rb file (for example recipes/default.rb) could contain the following:
passwords = Chef::EncryptedDataBagItem.load("production", "passwords")
mysql = passwords[“mysql”]
Chef::Log.info("The mysql password is: '#{mysql}'")

This will log the password in cleartext. You can use the variable #{mysql} which contains the cleartext password in whatever action in your recipe.

You can find more detailed information about the whole procedure here.