Ansible Slack - How to send Slack notification from Ansible

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 complete 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.

Ansible Slack

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.

Goto https://api.slack.com/apps

Click on Create new App 

Ansible Notification

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

Ansible Slack

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

Now click on Create App 

You would 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.

Now we have to create an Incoming Webhooks. Click on Incoming Webhooks under the features side menu to begin

Slack webhook

Toggle the switch on the top to make it on 

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

Slack webhook

Now click on Add New Webhook to Workspace

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

ansible bot slack

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

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

It is mandatory for you to have the channel created prior doing this integration so that you can see the channel name available for you to choose.

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

ansible slack configuration

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

Before we can use this webhook in our ansible playbook let us use the sample CURL request given by slack and validate.

curl -X POST -H 'Content-type: application/json' – data '{"text":"Hello, World!"}' https://hooks.slack.com/services/**********/**********/************************

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 would be another message posted on the channel added an integration to this channel: 

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

Ansible Slack

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 example 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 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
  tasks:
  - name: Wait for the file to be available
    register: fileexists
    file:
      path: /tmp/myprocess.pid
      state: file
    until: fileexists is not failed
    retries: 5
    delay: 10
    ignore_errors: true
  
  - name: notify Slack that the job is failing
    tags: slack
    community.general.slack:
      token: T0266NX8KPF/B03FHCHAZJM/fk4OApn8KMGilhxxVtQ
      msg: |
          ### StatusUpdate ###
          – ------------------------------------
          ``
          `Server`: {{ansible_host}}
          `Status`: Ansible File Watcher Job failed
          – ------------------------------------
      channel: '#ansible-notifications'
      color: good
      username: 'Ansible on {{ inventory_hostname }}'
      link_names: 0
      parse: 'none'
    when: fileexists is failed
    ignore_errors: true

  - name: notify Slack that the job is Successful
    tags: slack
    community.general.slack:
      token: T0266NX8KPF/B03FHCHAZJM/fk4OApn8KMGilhxxVtQ
      msg: |
          ### StatusUpdate ###
          – ------------------------------------
          ``
          `Server`: {{ansible_host}}
          `Status`: Ansible File Watcher Job Successful.
          – ------------------------------------
      channel: '#ansible-notifications'
      color: good
      username: 'Ansible on {{ inventory_hostname }}'
      link_names: 0
      parse: 'none'
    when: fileexists is not failed

 

Here is the execution result of the playbook

Ansible Slack

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

ansible slack notification

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

The playbook we have used here is from our another article on Ansible retry. Do read it for further reference.

Ansible Retry Examples – Retry a task until condition met | DevopsJunction

 

Send Slack notification once provisioning complete ( Additional )

Here is one more example that I have created for the ansible slack example.

In this playbook we are performing a list of tasks as a server provisioning and installing a NODE JS application

we have used various ansible modules/features in this to relate to the realtime use case

  1. Ansible apt module to download packages and install on ubuntu
  2. Shell module to validate the nodejs version and npm
  3. Validate the installation using an ansible assert module
  4. file module to create a directory and to change ownership
  5. git module to download source code from GitHub
  6. async and poll module to start the job async and poll
  7. wait_for module to validate the node server is up and running

This would be a good learning material for you.

Note*: I have written dedicated articles on all these modules with various examples. you can refer it here we have around 60+ articles on ansible. read all of them here

---
  - name: Install and Launch the Simple NodeJS Application
    hosts: testserver
    vars:
       - destdir: /apps/sampleapp
       - gittoken: *****************

    pre_tasks:
      - name : install dependencies before starting
        become: yes
        register: aptinstall
        apt:
           name: 
            - nodejs
            - npm
            - git
           state: latest
           update_cache: yes
      
      - name : validate the nodejs installation
        debug: msg="Installation of node is Successfull"
        when: aptinstall is changed
    
    tasks:
       - name: Version of Node and NPM
         shell:
            "npm -v && nodejs -v"
         register: versioninfo

       - name: Validate if the installation is intact
         assert:
          that: "versioninfo is changed"

      
       - name: Create Dest Directory if not exists
         become: yes
         file: 
          path: "{{ destdir }}"
          state: directory
          owner: vagrant
          group: vagrant
          mode: 0755

       - name: Download the NodeJS code from the GitRepo
         become: yes
         git:
            repo: 'https://{{gittoken}}@github.com/AKSarav/SampleNodeApp.git'
            dest: "{{ destdir }}"

       - name: Change the ownership of the directory
         become: yes
         file:
           path: "{{destdir}}"
           owner: "vagrant"
         register: chgrpout

       - name: Install Dependencies with NPM install command
         shell:
            "npm install"
         args:
            chdir: "{{ destdir }}"
         register: npminstlout

       - name: Debug npm install command
         debug: msg='{{npminstlout.stdout_lines}}'


       - name: Start the App
         async: 10
         poll: 0
         shell:
            "(node index.js > nodesrv.log 2>&1 &)"
         args:
           chdir: "{{ destdir }}"
         register: appstart

       - name: Validating the port is open
         tags: nodevalidate
         wait_for:
           host: "localhost"
           port: 5000
           delay: 10
           timeout: 30
           state: started
           msg: "NodeJS server is not running"

    post_tasks:
        - name: notify Slack that the servers have been updated 
          tags: slack
          community.general.slack:
            token: **********/**********/************************ 
            msg: |
                ### StatusUpdate ###
                – ------------------------------------
                ``
                `Server`: {{ansible_host}}
                `Status`: NodeJS Sample Application installed successfully
                – ------------------------------------
            channel: '#ansible'
            color: good
            username: 'Ansible on {{ inventory_hostname }}'
            link_names: 0
            parse: 'none'
          delegate_to: localhost

 

this playbook would do everything necessary for installing and running the node application.

once the application started running you would be getting a slack notification. Is not that cool?

Automation is not here to replace us but to give us some time to relax 😛

 

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 learnt 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 [email protected]

 

Cheers
Sarav AK

Follow me on Linkedin My Profile
Follow DevopsJunction onFacebook orTwitter
For more practical videos and tutorials. Subscribe to our channel

Buy Me a Coffee at ko-fi.com

Signup for Exclusive "Subscriber-only" Content

Loading