不依靠刀子从红宝石内部加密数据包

时间:2014-11-17 17:50:38

标签: ruby encryption chef knife databags

目前要加密数据包,我必须这样做: system "knife data bag from file TemporaryEncrypting \"#{enc_file_path}\" --secret-file #{Secret_Key_Path}"

并且这不起作用,因为刀无法找到配置文件,我似乎无法读取C:\chef中的那个。

我如何在ruby中执行此操作?

1 个答案:

答案 0 :(得分:3)

我研究了如何加密ruby内部,只需使用以下代码:

require 'chef/knife'
#require 'chef/encrypted_data_bag_item' #you need to do this in chef version 12, they've moved it out of knife and into it's own section
require 'json'

secret = Chef::EncryptedDataBagItem.load_secret Secret_Key_Path

to_encrypt = JSON.parse(json_to_encrypt)

encrypted_data = Chef::EncryptedDataBagItem.encrypt_data_bag_item to_encrypt, secret

使用此answer中的信息获得的答案,以下是相关代码:

namespace 'databag' do
  desc 'Edit encrypted databag item.'
  task :edit, [:databag, :item, :secret_file] do |t, args|
    args.with_defaults :secret_file => "#{ENV['HOME']}/.chef/encrypted_data_bag_secret"
    secret = Chef::EncryptedDataBagItem.load_secret args.secret_file
    item_file = "data_bags/#{args.databag}/#{args.item}.json"
    tmp_item_file = "/tmp/#{args.databag}_#{args.item}.json"
    begin
      #decrypt data bag into tmp file
      raw_hash = Chef::JSONCompat.from_json IO.read item_file
      databag_item = Chef::EncryptedDataBagItem.new raw_hash, secret
      IO.write tmp_item_file, Chef::JSONCompat.to_json_pretty( databag_item.to_hash )
      #edit tmp file
      sh "#{ENV['EDITOR']} #{tmp_item_file}"
      #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 item_file, Chef::JSONCompat.to_json_pretty( databag_item )
    ensure
      ::File.delete tmp_item_file #ensure tmp file deleted.
    end
  end
end