[SOLVED] Encrypted data bag in recipe key not found


#1

I’m trying to use an encrypted data bag in a recipe. I first push the key out, then use the key on the data bag. When I run the recipe it throws an error that the key cannot be found. If I touch a file on the remote node called /tmp/databag_key, the recipe works.

Any help here would be greatly appreciated.

keyfile = ‘/tmp/databag_key’

cookbook_file keyfile do
source keyfile
owner node[‘install_user’]
group node[‘install_group’]
mode '0600’
end

secret = Chef::EncryptedDataBagItem.load_secret(keyfile)
db_keys = Chef::EncryptedDataBagItem.load(node[‘esp_init’][‘database’], ‘items’, secret)

template node[‘esp_init’][‘install_loc’] do
variables(myusername: db_keys[‘username’],
mypassword: db_keys[‘password’],
mydatabase: db_keys[‘database’])
source 'esp_init.erb’
owner node[‘install_user’]
group node[‘install_group’]
mode '0600’
only_if { ::File.exist?(keyfile) }
end
file keyfile do
only_if { ::File.exist?(keyfile) }
action :delete
ignore_failure true
end


#2

With some help from the folks on Slack, I’ve got this figured out.

Changing the end on my cookbook_file to end.run_action(:create) took care of the issue.


#3

Yes, the issue here being the key itself was being written by the Chef run so other values depending on it were getting Nil as they were being run at Compile time. The workaround suggested moves the creation of the cookbook_file into compile time.