📜 ⬆️ ⬇️

Integration SaltStack and Telegram

image
In this article I would like to talk about sending notifications to the Telegram chat using SaltStack. Starting from version 2015.5.0, SaltStack provides integration with Slack out of the box, however Telegram is also a popular instant 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 opportunities for customization and expansion. In particular, its own executables .


How you can create 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


To start writing a module should be after:


  1. Created bot
  2. Bot added to chat
  3. Chat_id received

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, go to the main thing. As described in the documentation , the SaltStack module should be located in the _modules/ directory 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 execute the command to synchronize the modules so that they appear on the minions:
salt '*' saltutil.sync_modules


If everything is completed successfully, the result will be approximately as follows:


image


And finally, we create a state 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: <id   Telegram> 

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


On the side of the master:


image


In chat:


image


Sources


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


')

Source: https://habr.com/ru/post/330028/


All Articles