Iterating over EncryptedDataBagItem in Chef Recipe

733 views Asked by At

I would like to decrypt a chef data bag item (named passwords) and store all of its attributes in a temporary JSON file which is read (and then deleted) by a node.js app. Is there a way to iterate over attributes of a data bag ITEM and get their values?

plain_data = Chef::EncryptedDataBagItem.load("/home/me/data_bags/secrets/passwords.json", secret_key)

Since the EncryptedDataBagItem class does not have an each method, is there any workaround? I don't want to store each password in a separate json file (data bag item).

2

There are 2 answers

0
Roland On BEST ANSWER

why not something like:

decrypted_item = data_bag_item('secrets', 
                               'passwords', 
                                node['my_repo_name']['secret_key_file_path'])

file '/opt/me/passwords.json' do
  content decrypted_item.to_hash.to_json
  mode 600
end
0
Javad On

Apparently there is no easy way to do this only using the Chef API/DSL. You can still do this in Ruby. The good news is that you can run any arbitrary Ruby code in a Chef recipe. Here is how I did it:

# Load my secret key from a path specified in a Chef attribute
secret_key = Chef::EncryptedDataBagItem.load_secret("#{node[:my_repo_name][:secret_key_file_path]}")

# Use the ruby_block statement to run arbitrary Ruby code in the Chef DSL
ruby_block "decrypt passwords" do
  block do
    encrypted_path = "/home/me/data_bags/secrets/passwords.json"
    encrypted_data = JSON.parse(File.read(encrypted_path))
    plain_data = Chef::EncryptedDataBagItem.new(encrypted_data, secret_key).to_hash
    File.open('/opt/me/passwords.json', 'w') { |f|
      f.write(JSON.pretty_generate(plain_data))
    }
  end
end