Skip to content

Instantly share code, notes, and snippets.

@freiden
Forked from eddywashere/secret.rake
Created June 4, 2013 20:57
Show Gist options
  • Save freiden/5709537 to your computer and use it in GitHub Desktop.
Save freiden/5709537 to your computer and use it in GitHub Desktop.
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