Class: ChefMOTD

Inherits:
Chef::Handler
  • Object
show all
Defined in:
lib/chef-handler-motd.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = defaults) ⇒ ChefMOTD

Returns a new instance of ChefMOTD.



29
30
31
32
# File 'lib/chef-handler-motd.rb', line 29

def initialize(options = defaults)
  @priority = options[:priority]
  @keep_old_entries = options[:keep_old_entries]
end

Instance Attribute Details

#keep_old_entriesObject (readonly)

Returns the value of attribute keep_old_entries.



27
28
29
# File 'lib/chef-handler-motd.rb', line 27

def keep_old_entries
  @keep_old_entries
end

#priorityObject (readonly)

Returns the value of attribute priority.



27
28
29
# File 'lib/chef-handler-motd.rb', line 27

def priority
  @priority
end

Instance Method Details

#defaultsObject



34
35
36
37
38
39
# File 'lib/chef-handler-motd.rb', line 34

def defaults
  return {
    :priority => '05', 
    :keep_old_entries => false
  }
end

#delete_outdatedObject



41
42
43
44
45
46
47
48
49
# File 'lib/chef-handler-motd.rb', line 41

def delete_outdated
  if @keep_old_entries then return end
  Dir.entries('/etc/update-motd.d').select do |entry|
    /chef-motd/.match(entry) && !/^#{@priority}/.match(entry)
  end.each do |del|
    Chef::Log.warn "Deleting #{del} as it does not match the current ChefMOTD priority"
    FileUtils.rm ::File.join('/etc', 'update-motd.d', del)
  end
end

#generate_messageObject



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/chef-handler-motd.rb', line 57

def generate_message
  msg = <<-eos
#!/bin/sh
echo \"Node #{node.name} last success at #{Time.now.to_s} in #{run_status.elapsed_time} seconds\"
echo \"Updated resources on last run (total: #{run_status.updated_resources.length}):\"
  eos
  run_status.updated_resources.each do |res|
    msg += "echo \"  #{res.resource_name}[#{res.name}]\"\n"
  end
  return msg
end

#reportObject



69
70
71
72
73
74
75
# File 'lib/chef-handler-motd.rb', line 69

def report
  if run_status.success?
    Chef::Log.info 'Updating Chef info in MOTD ...'
    delete_outdated
    write_out(generate_message)
  end
end

#write_out(msg) ⇒ Object



51
52
53
54
55
# File 'lib/chef-handler-motd.rb', line 51

def write_out(msg)
  file = "/etc/update-motd.d/#{@priority}-chef-motd"
  ::File.open(file, 'w') {|f| f.puts msg}
  ::File.chmod(0755, file)
end