# \[SOLVED\] Encrypted data bag in recipe key not found

**URL:** <https://discourse.chef.io/t/solved-encrypted-data-bag-in-recipe-key-not-found/12386>\
**Category:** Chef Infra (archive)\
**Created:** [January 3, 2018, 4:53pm UTC](https://discourse.chef.io/t/solved-encrypted-data-bag-in-recipe-key-not-found/12386 "2018-01-03T16:53:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bucm01](https://avatars.discourse-cdn.com/v4/letter/b/bc8723/32.png) [@bucm01](https://discourse.chef.io/u/bucm01)\
**Post date:** [January 3, 2018, 4:53pm UTC](https://discourse.chef.io/t/solved-encrypted-data-bag-in-recipe-key-not-found/12386/1 "2018-01-03T16:53:27Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![bucm01](https://avatars.discourse-cdn.com/v4/letter/b/bc8723/32.png) [@bucm01](https://discourse.chef.io/u/bucm01)\
**Post date:** [January 3, 2018, 5:51pm UTC](https://discourse.chef.io/t/solved-encrypted-data-bag-in-recipe-key-not-found/12386/2 "2018-01-03T17:51:13Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![cheeseplus](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.chef.io/cheeseplus/32/960_2.png) [@cheeseplus](https://discourse.chef.io/u/cheeseplus)\
**Post date:** [January 5, 2018, 2:28pm UTC](https://discourse.chef.io/t/solved-encrypted-data-bag-in-recipe-key-not-found/12386/3 "2018-01-05T14:28:23Z")

</div>

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.
