-
-
Save taylormonacelli/cb332513e9787ee945491e5f075f6a62 to your computer and use it in GitHub Desktop.
Rakefile task to edit and create Chef encrypted data bags for test fixtures.
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
| require 'tempfile' | |
| require 'chef/json_compat' | |
| require 'chef/data_bag_item' | |
| require 'chef/encrypted_data_bag_item' | |
| require 'chef/encrypted_data_bag_item/check_encrypted' | |
| include Chef::EncryptedDataBagItem::CheckEncrypted | |
| # Usage Example: | |
| # eval "$(chef shell-init bash)" | |
| # rake databag:edit[path/to/some/test/fixture/data_bag/item.json,path/to/some/test/fixture/encrypted_data_bag_secret] | |
| namespace 'databag' do | |
| desc 'Edit encrypted databag item.' | |
| task :edit, [:item_file, :secret_file] do |t, args| | |
| unless ENV['EDITOR'] | |
| puts "No EDITOR found. Try:" | |
| puts "export EDITOR=vim" | |
| exit 1 | |
| end | |
| args.with_defaults :secret_file => "#{ENV['HOME']}/.chef/encrypted_data_bag_secret" | |
| args.with_defaults :item_file => "data_bags/#{args.item}.json" | |
| secret = Chef::EncryptedDataBagItem.load_secret args.secret_file | |
| tmp_item_file = Tempfile.open(File.basename(args.item_file)) | |
| begin | |
| #decrypt data bag into tmp file | |
| raw_hash = Chef::JSONCompat.from_json(IO.read(args.item_file)) | |
| databag_item = encrypted?(raw_hash) ? Chef::EncryptedDataBagItem.new(raw_hash, secret) : raw_hash | |
| formatted_tmp_file = Chef::JSONCompat.to_json_pretty( databag_item.to_hash ) | |
| tmp_item_file.write(formatted_tmp_file) | |
| tmp_item_file.close | |
| #edit tmp file | |
| sh "#{ENV['EDITOR']}", "#{tmp_item_file.path}" | |
| #encrypt tmp file data bag into original file | |
| raw_hash = Chef::JSONCompat.from_json(IO.read(tmp_item_file)) | |
| databag_item = Chef::EncryptedDataBagItem.encrypt_data_bag_item(raw_hash, secret) | |
| IO.write(args.item_file, Chef::JSONCompat.to_json_pretty( databag_item )) | |
| ensure | |
| #ensure tmp file deleted. | |
| tmp_item_file.close | |
| tmp_item_file.unlink | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment