Integration of SaltStack and Telegram

  • Tutorial

image
In this article I would like to talk about sending notifications to Telegram chat when using SaltStack. Starting from version 2015.5.0, SaltStack provides integration with Slack out of the box, however Telegram is also a popular messenger and is actively used among Russian users. Therefore, I hope that the article will be useful to its readers.


Introduction


Generally speaking, SaltStack is a constructor and, like many other tools, provides options for customization and expansion. In particular, its own executable modules .


How you can create a Telegram bot in Python is described in detail here . As an addition, it will be described how, using a small Python module, this approach can be tied to SaltStack.


Setup process


Start writing the module after:


  1. Bot created
  2. Bot added to chat
  3. Received chat_id

Note. You can get the chat id using the following python script:


import requests
URL = 'https://api.telegram.org/bot'
TOKEN = <токен вашего бота>
try:
    request = requests.post('{url}{token}/getUpdates'.format(url=URL, token=TOKEN))
    print request.json()['result'][0]['message']['chat']['id']
except Exception,e:
    print str(e)

So, we pass to the main thing. As described in the documentation , the SaltStack module should be located in the directory _modules/and look like this:


import requests
URL='https://api.telegram.org/bot'
def notify(message, token, chat_id):
        message_data = {
                'chat_id': chat_id,
                'text': message
        }
        try:
                request = requests.post('{url}{token}/sendMessage'.format(url=URL, token=token), data=message_data)
        except Exception,e:
                return False, str(e)
        if not request.status_code == 200:
                return False, "Return status is unsuccessful"
        # для наглядности вторым значением возвращается строка со служебной информацией.
        return True, "Message was successfully sent"

Next, you need to run the module synchronization command so that they appear on the minions:
salt '*' saltutil.sync_modules


If everything completed successfully, the result will be approximately the following:


image


And finally, create a status file (in this example - send_telegram.sls)


send message about minion id:
  module.run:
    # telegram - имя python-модуля, notify - метод в этом модуле
    - name: telegram.notify
    - kwargs:
      message: command executed on minion with id {{ grains['id'] }}
      token: <токен вашего бота>
      chat_id: 

We check the functionality of the created module:
salt '*' state.apply send_telegram


On the side of the master:


image


In chat:


image


Sources


  1. Python telegram bot using only requests
  2. Writing execution modules
  3. How do I use salt states?


Also popular now: