Sending Slack Notifications from Ansible: A Quick Guide

Baldev yadav
Cypik
Published in
6 min readMay 3, 2024

In this post let us quickly show you how to send Slack notifications from the Ansible playbook.

Being notified is always good instead of sitting and waiting for a task to be completed and looking at the screen.

Also if something fails, we can immediately look into it with a quick notification sent to our Slack channel.

So let us see how to use the famous Slack with Ansible and send notifications from Ansible to Slack.

Table of Contents

  • Configuring Slack — Creating webhook URL
  • Validating the webhook
  • Ansible Playbook to send Notifications using Slack
  • Send Slack notification after a task is completed or failed
  • Send Slack notification once provisioning is complete ( Additional )
  • Conclusion

Configuring Slack — Creating webhook URL

To be able to send notifications from Ansible or any other service to Slack, you have to create a webhook which can be done by creating a new Slack App.

Go tohttps://api.slack.com/apps

Click on Create New App

you will see an option to start from scratch or to use the existing manifests. Choose scratch

Once you have chosen scratch. you would see a model to fill in the name of your application and choose the workspace.

If you are logged in to more than one Slack workspace you might see all of those workspaces on a dropdown, choose your org/workspace

I named my app as Ansible-Bot and chose Gritfy as the workspace

Now click on Create App

You will see the following screen with an option to configure your Slack app further.

You can change the ICON and the App name and do a lot of customizations. I will leave that to your choice.

Toggle the switch on the top to make it on

Once you have enabled it you will see a screen with the following content

Now click on Add New Webhook to Workspace

You will be seeing a screen to get authorization to connect to your workspace given below.

There you have to choose the slack channel name to which this incoming webhook would post messages.

You will see the list of channels available in your workspace on the dropdown. Select one.

You must have the channel created before doing this integration to see the channel name available for you to choose from.

I am selecting our existing channel named #ansible-notifications

and click Allow once you have selected to move on.

Now you will see your Webhook URL available and listed in the incoming Webhooks section like this

You can find the webhook URL and copy it, which can later be used in Ansible to send notifications

webhook slack URL would like this ( the actual token is obfuscated for security reasons )

https://hooks.slack.com/services/**********/**********/************************

Validating the webhook

If everything is done right when you are executing the CURL in your terminal. you would get a message Hello World from the Ansible-bot to the ansible-notifications channel

In the previous step when you are done creating the webhook, there will be another message posted on the channel added an integration to this channel: Ansible-Bot

Here are the messages you might possibly see on your channel if everything is configured right

Now we have the webhook URL ready, let us use it in the Ansible playbook to send notifications

Ansible Playbook to send Notifications using Slack

Now we can put this webhook URL into the Ansible playbook and test it out.

we will give you a few examples playbooks where we send Slack notifications from an Ansible playbook

Send Slack notification after a task is completed or failed

Here is the Ansible playbook where we wait for the file to exist or be available, using Ansible retry.

Based on the final status of the task, we will be sending a Slack notification directly from the ansible-playbook

In the following playbook, you need to replace the token field and the channel

token: **********/**********/************************
channel: '#ansible-notifications'

the token can be directly taken from the webhook URL

https://hooks.slack.com/services/**********/**********/************************

You can copy the random strings, basically, everything after https://hooks.slack.com/services/

Note*: For security reasons we have replaced the actual characters with *

here is the complete playbook

---
- hosts: localhost
remote_user: ubuntu
become: true
roles:
- { role: ansible-role-slack-ssh-notifier, tags: ["slack-ssh-notifier"]}

default: main.yaml

---

# Slack Notification Variables
channel: "" # Name of Slack Channel
hostname: "" # Hostname
webhook_url: "" # url of Slack Webhook
dir_path: "/opt/slack-ssh-notifier"

tasks: configure.yml

---

- name: create slack ssh notifier dirs
file:
path: "{{ item|safe|trim }}"
state: directory
mode: 0755
changed_when: false
with_items:
- "{{ dir_path }}"

- name: Create slack ssh notifier script
template:
dest: "{{ dir_path }}/ssh_alert.sh"
mode: +x
src: "{{ item }}"
with_items:
- config/ssh_alert.sh.j2

tasks: install.yml

---

- name: run slack ssh notifier script
shell: echo "session required pam_exec.so {{ dir_path }}/ssh_alert.sh" >> /etc/pam.d/sshd
changed_when: false

tasks: main.yml

---

- import_tasks: configure.yml
- import_tasks: install.yml

templates>config: ssh_alert.sh.j2

#!/bin/bash

# Add Chaneel Name and Webhook URL of slack here to send Slack Notification
channel="{{ channel }}"
webhook_url="{{ webhook_url }}"

if [[ $channel == "" ]]
then
echo "No channel specified"
exit 1
fi

shift
host="{{ hostname }}"

content="\"attachments\": [ { \"mrkdwn_in\": [\"text\", \"fallback\"], \"fallback\": \"SSH login: $USER connected to \`$host\`\", \"text\": \"SSH login to \`$host\`\", \"fields\": [ { \"title\": \"User\", \"value\": \"$PAM_USER\", \"short\": true }, { \"title\": \"IP Address\", \"value\": \"$PAM_RHOST\", \"short\": true }, { \"title\": \"Date\", \"value\": \"`date`\", \"short\": true } ], \"color\": \"#F35A00\" } ]"
if [[ $content == "" ]]
then
echo "No text specified"
exit 1
fi
if [ "${PAM_TYPE}" == "open_session" ]; then
curl -s -X POST --data-urlencode "payload={\"channel\": \"$channel\", \"mrkdwn\": true, \"username\": \"ssh-bot\", $content, \"icon_emoji\": \":computer:\"}" $webhook_url
fi

exit 0

Here is the execution result of the playbook

I have received the message in our ansible-notifications slack channel.

We have successfully validated that we are able to send messages from Ansible to Slack.

Conclusion

Hope this article helped you to understand how Ansible can be used with Slack and how to send messages to Slack from Ansible.

We have also learned how to configure the slack webhook and use the webhook in the Ansible slack module.

we can now send Slack notifications for failed or successful jobs and notify the stakeholders.

Hope this article helps you.

We at Gritfy do Product Development and DevOps/SRE Support services. If you have any requirements.

Please do write to us at hello@gritfy.com

Summary

In this post, I showed “Sending Slack Notifications from Ansible”

Enjoy it! That’s it; We did it…

For hassle-free cloud management with DevOps at the center of the process, contact us at info@cypik.com

Cypik.

About the author:
I’m Baldev Yadav, an experienced Linux enthusiast and DevOps engineer. I’m passionate about automating and streamlining development processes, and currently, I work as a DevOps Engineer at Cypik. I specialize in cloud technologies with a focus on Ansible and DigitalOcean.

--

--