Skip to content

Instantly share code, notes, and snippets.

@SFEley
Created April 22, 2013 01:18
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save SFEley/5431844 to your computer and use it in GitHub Desktop.
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
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
@eddywashere
Copy link

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 use foo/bar-sample.json as a template.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment