0

如何转换files_copy_to_guest为 Ruby 哈希?

.kitchen.yml

  'my_cookbook': 
      'files_copy_to_guest':
       - 
          'home/kevin/bin/script.sh'      : '/vagrant/unix_scripts/script.sh'
          'home/kevin/script2.sh'       : '/vagrant/unix_scripts/script2.sh'

食谱/my_cookbook/attributes/default.rb

default['kevin']['files_copy_to_guest']     = [] 

食谱/my_cookbook/recipes/default.rb

files = node['kevin']['files_copy_to_guest']   # how to read attribute as Hash?

if files.nil? | files.empty? then
    Chef::Log.warn("node['kevin']['files_copy_to_guest'] is nil or empty!")
end

files.each do |_, value|                
    value.each do |vm_dest, host_src|   
        file vm_dest do 
            owner user
            group user
            mode 0755
            content ::File.open(host_src).read # <<< error on 'value'
        end
    end 
end

我试过了:

files = YAML.load(node['kevin']['files_copy_to_guest'],

但这没有用。我也读过files.to_hash也行不通。

4

1 回答 1

2
'my_cookbook': 
  'files_copy_to_guest':
   - 
    'home/kevin/bin/script.sh'      : '/vagrant/unix_scripts/script.sh'
    'home/kevin/script2.sh'       : '/vagrant/unix_scripts/script2.sh'

It looks to me like the problem is with your YAML. You have a - line which denotes the beginning of an array, so your object is coming out looking like this:

{
  'my_cookbook' => {
    'files_copy_to_guest' => [
      {
        'home/kevin/bin/script.sh' => '/vagrant/unix_scripts/script.sh',
        'home/kevin/script2.sh' => '/vagrant/unix_scripts/script2.sh'
      }
    ]
  }
}

I think if you ditch the - it should work. You can test the output of your YAML with a tool like this: http://yaml-online-parser.appspot.com/

于 2014-04-30T14:29:48.847 回答