rdcp
rdcp

Reputation: 31

Ruby code on Chef as a "ruby_block" not working

I have a question for the Ruby and Chef hackers.

I have very limited knowledge of Chef and even less on Ruby programming language, however, I need to implement on Chef (chef-solo) something similar to "augeas" (which works with Puppet, but here I need a solution for Chef).

I got the example code below but it's not working and I am now for a few days trying to figure out what is wrong.

Basically I need to be able to select specific strings in a text file and modify these values. I could use sed but perhaps I can do it in a more elegant way using the ruby_block from Chef.

Please let me know what can be possibly wrong with the code below. Why is my /etc/hosts not being updated with new values?

Always when I re-run chef-solo, I get the following error:

NoMethodError
-------------
undefined method `chef' for Chef::Resource::RubyBlock

Thanks for your help.

Follows my default.rb file:

ruby_block "edit etc hosts" do
  block do
    rc = Chef::Util::FileEdit.new("/etc/hosts")
    rc.search_file_replace_line(
      /^127\.0\.0\.1 localhost$/,
      "127.0.0.1 #{new_fqdn} #{new_hostname} localhost"
    )
    rc.write_file
  end
end

Upvotes: 3

Views: 2044

Answers (2)

raphink
raphink

Reputation: 3665

It shouldn't be too hard to get Augeas to work with Chef. Augeas is a C library, and Puppet simply uses its Ruby bindings. You just need to make use of these bindings in Chef.

There is a PoC Augeas resource provider for Chef here: https://github.com/craigtracey/augeas.

Note: http://lists.opscode.com/sympa/arc/chef/2013-02/msg00337.html mentions Augeas integration into Chef, but apparently the participants misunderstand Augeas as they mention idempotency issues and deltas. Most uses of Augeas don't lead to managing deltas, but desired states.

Upvotes: 0

shawnzhu
shawnzhu

Reputation: 7585

Add this line as the first line of your ruby block:

require 'chef/util/file_edit'

According to your case, you should use the cookbook hostsfile:

hostsfile_entry '127.0.0.1' do
  hostname  new_hostname
  aliases   [new_fqdn]
  comment   'Append by Recipe X'
  action    :append
end

Upvotes: 1

Related Questions