问题
motivation: the node will try to fetch a key from the data bag, if the key does not exist, it will generate one. this is handy when there you scale your cluster and have to share a password for it.
note that there won't be any node creation in parallel, so race condition will be avoided.
there is a part in chef documentation that relates to create and edit data bag item from a recipe, though there is nothing there that relates to creating a new encrypted data bag item.
can anyone please shed the light on how it can be done?
回答1:
Apologies in advance for the surmon that follows. Could you perhaps explain what you're trying to do? Perhaps there is a better way to accomplish it. Encrypted data bags are far from a complete security solution. Their weakness lies in the lack of key management.
So the answer is that the Ruby source code is fully documented by it's gems. Encrypted data bag items are described here:
- http://www.rubydoc.info/github/opscode/chef/Chef/EncryptedDataBagItem
But......
From the documentation link you gave:
Creating and editing the contents of a data bag or a data bag item from a recipe is not recommended. The recommended method of updating a data bag or a data bag item is to use knife and the knife data bag subcommand.
If this action must be done from a recipe, please note the following:
- If two operations concurrently attempt to update the contents of a data bag, the last-written attempt will be the operation to update the contents of the data bag. This situation can lead to data loss, so organizations should take steps to ensure that only one chef-client is making updates to a data bag at a time.
- Altering data bags from the node when using the open source Chef server requires the node’s API client to be granted admin privileges. In most cases, this is not advisable.
Updates to the Chef server are not transactional, so it's a really bad idea to be updating something from a chef client, where potentially more than one node could be performing the same action.
The second warning is about privileges... Again you are best advised to operate your chef clients with the least amount of super powers. Reserve these for the chef admin or scripts that run on a Chef workstation.
回答2:
Try this:
secret = Chef::EncryptedDataBagItem.load_secret(Chef::Config[:encrypted_data_bag_secret])
data = { "id" => "mysecret", "secret" => "stuff" }
encrypted_data_hash = Chef::EncryptedDataBagItem.encrypt_data_bag_item(data, secret)
databag_item = Chef::DataBagItem.new
databag_item.data_bag("secrets")
databag_item.raw_data = encrypted_data_hash
databag_item.save
See also Chef Decryption of Data Bags and Retrieval of Key
来源:https://stackoverflow.com/questions/37359763/how-to-create-edit-encrypted-data-bag-item-from-a-chef-recipe