Chef data bag creation from a recipe
Asked Answered
A

1

6

How to create a data bag from a recipe and avoid the exception when that data bag already exists?

The documentation shows that creating a data bag is done like this:

new_databag = Chef::DataBag.new
new_databag.name('unique_name')
new_databag.save

This works when the databag does not exist yet, but how to make it work if the databag already exists so it will not break the chef run?

Anyplace answered 15/7, 2012 at 7:32 Comment(0)
P
12

Try using the list method of Chef::DataBag and check whether your databag's name is present:

require 'chef/data_bag'

unless Chef::DataBag.list.key?('unique_name')
  new_databag = Chef::DataBag.new
  new_databag.name('unique_name')
  new_databag.save
end

I use this to make my recipes more robust, or throw a more friendly error if an expected databag cannot be found on a Chef server.

Platysma answered 15/7, 2012 at 9:15 Comment(1)
I think the "if Chef::DataBag.list.key?" test should be an unless. In that case you only make the new databag if it already exist to pass that test. Correct? Thanks for pointing out the pattern though :DPhotochronograph

© 2022 - 2024 — McMap. All rights reserved.