Using library functions in chef resources

1.6k views Asked by At

I have created a chef cookbook "lcd_web_source" with the following directory structure.

enter image description here

The content of my helpers.rb is shown below

module Lcd_web_source
  module Helpers

def platform_package_httpd
  case node['platform']
  when 'centos' then 'httpd'
  when 'ubuntu' then 'apache2'
  end
end
def platform_service_httpd
  case node['platform']
  when 'centos' then 'httpd'
  when 'ubuntu' then 'apache2'
  end
end

end
end

Chef::Recipe.include(Lcd_web_source::Helpers)
Chef::Resource.include(Lcd_web_source::Helpers)

the content of the resource file "hello.rb" is as follow

include Lcd_web_source::Helpers
resource_name :hello_httpd
property :greeting, :kind_of => String

default_action :create
action :create do

  package platform_package_httpd

  service platform_service_httpd do
    action [:enable, :start]
  end

  template '/var/www/html/index.html' do
    source 'index.html.erb'
    owner 'apache'
    group 'apache'
    variables(
      greeting_scope: node['greeting_scope'],
      greeting: new_resource.greeting,
      fqdn: node['fqdn']
    )
  end
end

and my recipe default.rb looks as

package platform_package_httpd
hello_httpd 'greet world' do
    greeting "Hello"
    action :create
end

When this recipe runs, the first statement

package platform_package_httpd

runs fine, which means the recipe is able to find library functions.

But the second statement fails with the following error

NameError: undefined local variable or method `platform_package_httpd' for #<#<Class:0x0000000004326f00>:0x0000000004244268>

In short custom, the resource is not able to locate the functions defined in the library. Help me understand as to why this is happening.

2

There are 2 answers

0
osexp2000 On

I'd like to leave a memo for those have another similar issue.

If you implement custom resource in providers/.rb (the definition is in resources/.rb in a different way, see https://docs-archive.chef.io/release/12-3/custom_resources.html),

in that case, action_class becomes an invalid syntax, I could not find document for this in provider mode, but inspired by @Paul B, I find the solution is put this statement in the provider/*.rb:

include ::YourModule::YourSubModule
0
Paul B On

This example looks to be from a Linux Academy course. I had to use the action_class within the Custom Resource DSL. Using the action_class block I was able to use the method i created within the libraries/helper.rb

Change your hello.rb to include the action_class block

action_class do
  include Lcd_web_source::Helpers
end

resource_name :hello_httpd
property :greeting, :kind_of => String

default_action :create
action :create do

  package platform_package_httpd

Reference: https://docs.chef.io/custom_resources.html#custom-resource-dsl