Created
April 22, 2013 01:18
-
-
Save SFEley/5431844 to your computer and use it in GitHub Desktop.
Open an encrypted data bag item in one's usual editor, decrypted. Adapted from Aaron Jensen's excellent script: https://gist.github.com/aaronjensen/4123044
This file contains 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
namespace :secret do | |
desc "Edit an encrypted data bag item in EDITOR" | |
task :edit, :item do |t, args| | |
unless ENV['EDITOR'] | |
puts "No EDITOR found. Try:" | |
puts "export EDITOR=vim" | |
exit 1 | |
end | |
abort 'usage: rake "secret:edit[<item name>]"' unless args.item | |
require 'chef/encrypted_data_bag_item' | |
require 'json' | |
require 'tempfile' | |
data_bag = 'secret' | |
item_name = args.item | |
keyfile = File.join(Dir.pwd, 'config', 'secret_key.txt') | |
encrypted_path = "data_bags/#{data_bag}/#{item_name}.json" | |
abort "Cannot find #{File.join(Dir.pwd, encrypted_path)}" unless File.exists? encrypted_path | |
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
Thanks! I hacked this to create the file if it doesn't exist or it can copy over an example file if that exists.
Ex.
rake 'secret:edit[foo,bar]'
would usefoo/bar-sample.json
as a template.