Search code examples
chef-infralwrp

Is attr_accessor required in resource definition of chef lwrp?


I created an LWRP using chefdk and following the documentation and a few blog posts to the letter.

resource

actions :install
default_action :install

provides :foo

attribute :name, :kind_of => String, :name_attribute => true

provider

provides :foo

def whyrun_supported?
  true
end

use_inline_resources

action :install do
  converge_by("install: #{@new_resource}") do
    execute "installation of: #{@new_resource.name}" do
      command "foo install #{@new_resource.name}"
    end
  end
end

def load_current_resource
  @current_resource = Chef::Resource::Foo.new @new_resource.name
  @current_resource.name = @new_resource.name
end

When using this LWRP in a cookbook, I would get the following error:

undefined method `name=' for Chef::Resource::Foo

The only way I could fix it was by adding attr_accessor :name to the resource definition. But I never saw this as a requirement in any documentation. From the documentation, I was assuming that Chef took care of setting attr_accessor on any attributes during resource/provider compilation. Can anyone confirm what I found or explain what was really happening?

Thanks.


Solution

  • def load_current_resource
      @current_resource = Chef::Resource::Foo.new @new_resource.name
      @current_resource.name = @new_resource.name
    end
    

    Your problem is here, name is supposed to be invariable (for current and new resource to match) as it identify the resource, you should not try to set @current_resource.name.

    Remove this line and it should be ok without the accessor.