Created
March 4, 2017 00:06
-
-
Save Brantone/6a95ba78fd10161665ebbb1615267177 to your computer and use it in GitHub Desktop.
Chef Knife script for encrypting a file into a data bag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/knife exec | |
# Knife exec script to put the contents of a file into a data bag, then encrypt it. | |
# Care of : https://www.coveros.com/chef-knife-script-for-encrypting-a-file-a-data-bag/ | |
########### USAGE ############ | |
this_file = File.basename(__FILE__) | |
usage = <<-EOS | |
#{this_file}: Encrypts and stores the contents of a file into a data bag item. This | |
is typically used to encrypt and store the contents of a PEM file. | |
usage: | |
knife exec #{this_file} {filename} {databag} {databag_item} {secret_key_file} | |
example: | |
knife exec #{this_file} foo.pem foo_bag foo_item my_secret.pem | |
Use 'knife data bag show foo_bag foo_item --secret-file my_secret.pem' to verify. | |
EOS | |
############ USAGE ############ | |
filename = ARGV[2] | |
data_bag_name = ARGV[3] | |
data_bag_item_name = ARGV[4] | |
encryption_key_file = ARGV[5] | |
abort usage if (encryption_key_file.nil? || (encryption_key_file == "")) | |
# See if the data bag exists yet | |
begin | |
data_bag = data_bag(data_bag_name) | |
puts "Data bag #{data_bag_name} already exists." | |
rescue | |
puts "Creating new data bag #{data_bag_name}" | |
bag = Chef::DataBag.new | |
bag.name(data_bag_name) | |
bag.create | |
end | |
puts "Storing contents of #{filename} in item #{data_bag_item_name}" | |
content = File.read(filename) | |
# Set up the un-encrypted contents of the data bag | |
bag_item = Chef::DataBagItem.new | |
bag_item.data_bag(data_bag_name) | |
bag_item[:comment] = "Data bag automatically generated from file #{filename} by databag_encrypt_file.krb" | |
bag_item[:filename] = File.basename(filename) | |
bag_item[:content] = content | |
bag_item[:id] = data_bag_item_name | |
puts "Encrypting with key #{encryption_key_file}" | |
# Now, encrypt the data bag contents into a new data bag | |
bag_hash = bag_item.to_hash | |
secret = Chef::EncryptedDataBagItem.load_secret(encryption_key_file) | |
enc_hash = Chef::EncryptedDataBagItem.encrypt_data_bag_item(bag_hash, secret) | |
ebag_item = Chef::DataBagItem.from_hash(enc_hash) | |
ebag_item.data_bag(data_bag_name) | |
ebag_item.save | |
puts "Success. Use command to verify contents:" | |
puts " knife data bag show #{data_bag_name} #{data_bag_item_name} --secret-file #{encryption_key_file}" | |
# Need this, or knife exec attempts to execute your parameters as new scripts | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment