Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRY within a Chef recipe

What's the best way to do a little DRY within a chef recipe? I.e. just break out little bits of the Ruby code, so I'm not copying pasting it over and over again.

The following fails of course, with:

NoMethodError: undefined method `connect_root' for Chef::Resource::RubyBlock

I may have multiple ruby_blocks in one recipe, as they do different things and need to have different not_if blocks to be truley idempotent.

def connect_root(root_password)
  m = Mysql.new("localhost", "root", root_password)
  begin
    yield m
  ensure
    m.close
  end
end

ruby_block "set readonly" do
  block do
    connect_root node[:mysql][:server_root_password] do |connection|
      command = 'SET GLOBAL read_only = ON'
      Chef::Log.info "#{command}"
      connection.query(command)
    end
  end
  not_if do
    ro = nil
    connect_root node[:mysql][:server_root_password] do |connection|
      connection.query("SELECT @@read_only as ro") {|r| r.each_hash {|h| 
        ro = h['ro']
      } }
    end
    ro
  end
end
like image 261
DragonFax Avatar asked Mar 24 '13 04:03

DragonFax


2 Answers

For the record, I just created a library with the following. But that seems overkill for DRY within one file. I also couldn't figure out how to get any other namespace for the module to use, to work.

class Chef
  class Resource
    def connect_root(root_password)
      ...
like image 20
DragonFax Avatar answered Nov 18 '22 06:11

DragonFax


As you already figured out, you cannot define functions in recipes. For that libraries are provided. You should create a file (e.g. mysql_helper.rb ) inside libraries folder in your cookbook with the following:

module MysqlHelper
  def self.connect_root( root_password )
    m = Mysql.new("localhost", "root", root_password)
    begin
      yield m
    ensure
      m.close
    end
  end
end

It must be a module, not a class. Notice also we define it as static (using self.method_name). Then you will be able to use functions defined in this module in your recipes using module name with method name:

MysqlHelper.connect_root node[:mysql][:server_root_password] do |connection|
  [...]
end
like image 131
Draco Ater Avatar answered Nov 18 '22 06:11

Draco Ater