从红宝石内部加密数据袋,而无需依靠刀 [英] Encrypt data bag from inside of ruby without relying on knife

查看:105
本文介绍了从红宝石内部加密数据袋,而无需依靠刀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻,我需要加密一个数据包: system "knife data bag from file TemporaryEncrypting \"#{enc_file_path}\" --secret-file #{Secret_Key_Path}"

At the moment to encrypt a data bag, I have to do : system "knife data bag from file TemporaryEncrypting \"#{enc_file_path}\" --secret-file #{Secret_Key_Path}"

那是行不通的,因为刀子找不到配置文件,而且我似乎无法读取C:\chef中的配置文件.

and that doesn't work because knife can't find a config file and I can't seem to get it read the one in C:\chef.

我如何从红宝石内部做到这一点?

How do I do this from within ruby?

推荐答案

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

I worked out how to encrypt inside of ruby, just use this code:

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 中的信息获得的答案是有问题的代码

Answer achieved with information from this answer, here is the code in question:

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

这篇关于从红宝石内部加密数据袋,而无需依靠刀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆