Now that the notification is created, you need to create rules that use it. You’ll also want to study the Slack Webhook message format. A very simple rule to test your integration is to just send a message on any action event that comes into Analytics.
[ruby]
rules ‘org notifier’
rule on action
when
true
then
notify(‘slack’, ‘
{
"text": "test from the blog post"
}
‘)
end
end
[/ruby]
Slack expects a JSON document to be sent in the Webhook, and Chef Analytics 1.1.4 supports multi-line notifications to be written. The minimum payload you’ll need to send is the “text” property. Save this rule, and you should start seeing messages in your Slack channel as things change on the Chef Server.
That’s cool, but the message could be formatted better. Slack lets you modify the message a few different ways. You can add the “username” property to set the username in the Slack channel, and you can specify an icon by setting the “icon_emoji” property. Say for instance we want to write a rule to notify Slack when an Chef Audit Mode rule fails.
[ruby]
rules ‘failed-audit’
rule on run_control_group
when
status != ‘success’
then
notify(‘slack’, ‘
{
"username": "Audit Alarm",
"icon_emoji": ":rotating_light:",
"text": "{{message.name}} (cookbook {{message.cookbook_name}}) had `{{message.number_failed}}` failed audit test(s) on node `{{message.run.node_name}}` in organization `{{message.organization_name}}`"
}
‘)
end
end
[/ruby]
This will result in a message in Slack that looks like the below.
You can enhance this message a bit more by using the message attachments feature. Say for instance you want audit rules to stand out a bit more in a channel, you can set the message attachment color to “warning”, to make channel members see it better.
[ruby]
rules ‘failed-audit’
rule on run_control_group
when
status != ‘success’
then
alert:warn(‘{{message.cookbook_name}} {{message.recipe_name}} audit failed’)
notify(‘slack’, ‘
{
"username": "Audit Alarm",
"icon_emoji": ":rotating_light:",
"attachments": [ {
"text": "{{message.name}} (cookbook {{message.cookbook_name}}) had `{{message.number_failed}}` failed audit test(s) on node `{{message.run.node_name}}` in organization `{{message.organization_name}}`",
"color": "danger"
}]
}
‘)
end
end
[/ruby]
This rule will give you a message like the one below.
You can leverage all of Slack’s formatting rules as well to make you messages stand out even more. Hopefully this post will help you get started with Analytics and Slack. The two tools combined give you a powerful combination to enhance your chatops experience and effectiveness.