'Refer to method from containing scope in resource in chef recipe

In a chef recipe I define a helper method like:

def my_service_config(description, args="")
  {
    Unit: {
      Description: description,
    },
    Service: {
      Type: 'simple',
      ExecStart: "/usr/sbin/my-service-script #{args}",
      Restart: 'on-failure',
    }
  }
end

systemd_unit "my-service.service" do
  content my_service_config("my description", "--some-flag")
  action :create
end

But when I run chef I get an error like:

NoMethodError
-------------
undefined method `my_service_config' for Chef::Resource::SystemdUnit

How can I properly refer to the my_service_config method from inside the systemd_unit resource block?



Solution 1:[1]

I think you should use Chef libraries to write pure Ruby code. You can extend the functionality of a Chef recipe using methods such as my_service_config in a library. This method can be put into a "helper" file in libraries/ directory.

For example in libraries/helper.rb:

class Chef::Recipe
  def my_service_config(description, args="")
    {
      Unit: {
        Description: description,
      },
      Service: {
        Type: 'simple',
        ExecStart: "/usr/sbin/my-service-script #{args}",
        Restart: 'on-failure',
      }
    }
  end
end

Then in recipe:

service_content = my_service_config("my description", "--some-flag")

systemd_unit "my-service.service" do
  content service_content
  action :create
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 seshadri_c