Search code examples
rubychef-infrachef-recipelwrp

Iterating over an array attribute in Chef


I am using Chef provisioning to create machines in AWS. When creating the machine, I add an attribute to it that is an array of JSON files. In the recipes I run, I want to iterate over this array and create a template file on the machine. The machine gets provisioned but when iterating over the array attribute, I get an error that says:

undefined method `each' for nil:NilClass

I tried looking at the node file that got created on my server and guess what? The array of JSON files was added to the node file! I'm not sure why then it keeps throwing that error. Any ideas?

The code sample is as follows:

machines.rb

    def get_cluster_json(domain_number)
      clusters = []
      @@environment_template['domains'][domain_number]['clusters'].each do |cls|
        clusters << JSON.parse(::File::read(new_resource.template_path + cls))
      end

      return clusters
    end

provisioning_xyz_machine "test-admin" do
            tag "usage:keep"
            attribute "clusters_json", get_cluster_json(domain_counter)
            recipe admin_role
            machine_options get_machine_options()
            ohai_hints ohai_hints
            action $provisioningAction
          end

admin_role.rb

managed_details = []

  node["clusters_json"].each do |cls|
      managed_details << "#{cls['cluster']['name']}" 
  end

Log

* template[/tools/appsw/appsautm/config/INTFIN_config] action create[2015-05-12T10:24:13-07:00] INFO: Processing template[/tools/appsw/appsautm/config/INTFIN_config] action create (xyz-environment-cookbook::build_admin line 32)

================================================================================
Error executing action `create` on resource 'template[/tools/appsw/appsautm/config/INTFIN_config]'
================================================================================

Chef::Mixin::Template::TemplateError
------------------------------------
undefined method 'each' for `nil:NilClass`

Resource Declaration:
---------------------
# In /var/chef/cache/cookbooks/xyz-environment-cookbook/recipes/build_admin.rb

  32: template "/tools/appsw/appsautm/config/#{env_name}_config" do
  33:   source "#{env_name}_config.conf.erb"
  34:   cookbook "appsautm-template"
  35:   owner node['xyz-dir-library']['user']
  36:   mode "0755"
  37:        
  38:   variables({     
  39:     :admin_servers=> admin_details,     
  40:     :managed_servers=> managed_details     
  41:   })     
  42: end     
  43:     

Compiled Resource:
------------------
# Declared in /var/chef/cache/cookbooks/xyz-environment-cookbook/recipes/build_admin.rb:32:in `from_file'

Solution

  • The error appears to be in your template, not your cookbook. In fact, it appears completely unrelated to the files you posted. I'd need to see the #{env_name}_config.conf.erb file and the build_admin.rb file in order to be more help than that.