Skip to content

Instantly share code, notes, and snippets.

@eddywashere
Forked from SFEley/secret.rake
Last active December 17, 2015 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eddywashere/5608229 to your computer and use it in GitHub Desktop.
Save eddywashere/5608229 to your computer and use it in GitHub Desktop.
Open an encrypted data bag item or create it if it doesn't exist. Takes two arguments, databag and item name.
namespace :secret do
desc "Edit an encrypted data bag item in EDITOR"
task :edit, :data_bag, :bag_item do |t, args|
unless ENV['EDITOR']
puts "No EDITOR found. Try:"
puts "export EDITOR=vim"
puts "or"
puts "export EDITOR='subl -w'"
exit 1
end
abort "usage: rake 'secret:edit[<folder>,<filename>]'" unless args.to_hash.size == 2
require 'chef/encrypted_data_bag_item'
require 'json'
require 'tempfile'
data_bag = args[:data_bag]
item_name = args[:bag_item]
keyfile = File.join(Dir.pwd, 'config', 'secret_key.txt')
encrypted_path = "data_bags/#{data_bag}/#{item_name}.json"
encrypted_path_sample = "data_bags/#{data_bag}/#{item_name}-sample.json"
unless File.exists? encrypted_path
if File.exists? encrypted_path_sample
FileUtils.copy(encrypted_path_sample, File.join(encrypted_path))
end
end
unless File.exists? encrypted_path
File.open(encrypted_path, 'w') do |f|
f.write("{\n")
f.write('"id":"')
f.write(item_name)
f.write('"')
f.write("}\n")
end
end
abort "The secret key must be located in #{keyfile}" unless File.exists? keyfile
secret = Chef::EncryptedDataBagItem.load_secret(keyfile)
decrypted_file = Tempfile.new ["#{data_bag}_#{item_name}",".json"]
at_exit { decrypted_file.delete }
encrypted_data = JSON.parse(File.read(encrypted_path))
plain_data = Chef::EncryptedDataBagItem.new(encrypted_data, secret).to_hash
decrypted_file.puts JSON.pretty_generate(plain_data)
decrypted_file.close
system "#{ENV['EDITOR']} #{decrypted_file.path}"
plain_data = JSON.parse(File.read(decrypted_file.path))
encrypted_data = Chef::EncryptedDataBagItem.encrypt_data_bag_item(plain_data, secret)
File.write encrypted_path, JSON.pretty_generate(encrypted_data)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment