Class: Chef::Handler::SlackReporting

Inherits:
Chef::Handler show all
Defined in:
lib/chef/handler/slack.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ SlackReporting

Returns a new instance of SlackReporting.



33
34
35
36
37
38
39
40
# File 'lib/chef/handler/slack.rb', line 33

def initialize(options = {})
  @source = options[:source] || "#{Chef::Config[:node_name]}"
  @channel = options[:channel] || "#test"
  @token = options[:token] || "token"
  @team = options[:team] || "doesnotexist"
  @username = options[:username] || "chef"
  @icon_emoj = options[:icon_emoj] || ":chef:"
end

Instance Attribute Details

#channelObject

Returns the value of attribute channel.



31
32
33
# File 'lib/chef/handler/slack.rb', line 31

def channel
  @channel
end

#icon_emojObject

Returns the value of attribute icon_emoj.



31
32
33
# File 'lib/chef/handler/slack.rb', line 31

def icon_emoj
  @icon_emoj
end

#sourceObject

Returns the value of attribute source.



31
32
33
# File 'lib/chef/handler/slack.rb', line 31

def source
  @source
end

#teamObject

Returns the value of attribute team.



31
32
33
# File 'lib/chef/handler/slack.rb', line 31

def team
  @team
end

#tokenObject

Returns the value of attribute token.



31
32
33
# File 'lib/chef/handler/slack.rb', line 31

def token
  @token
end

#usernameObject

Returns the value of attribute username.



31
32
33
# File 'lib/chef/handler/slack.rb', line 31

def username
  @username
end

Instance Method Details

#reportObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/chef/handler/slack.rb', line 42

def report
  gemspec = if Gem::Specification.respond_to? :find_by_name
              Gem::Specification.find_by_name('chef-handler-slack')
            else
              Gem.source_index.find_name('chef-handler-slack').last
            end

  Chef::Log.debug("#{gemspec.full_name} loaded as a handler.")

  if not run_status.success?
    msg = "Chef run failed on *#{source}*"
    if !run_status.exception.nil?
      msg += "\n```"
      msg += run_status.formatted_exception.encode('UTF-8', {:invalid => :replace, :undef => :replace, :replace => '?'})
      msg += '```'
    end

    send(msg)
  end
end

#send(msg) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/chef/handler/slack.rb', line 63

def send(msg)
  params = {
    :username => @username,
    :icon_emoji => @icon_emoj,
    :channel => @channel,
    :text => msg,
    :token => @token,
  }

  uri = URI("https://#{@team}.slack.com/services/hooks/incoming-webhook?token=#{@token}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  begin
    req = Net::HTTP::Post.new("#{uri.path}?#{uri.query}")
    req.set_form_data({:payload => params.to_json})
    http.request(req).body
  rescue Exception => e
    Chef::Log.warn("An unhandled execption occured while posting a message to Slack: #{e}")
  end
end