Integration of SaltStack and Telegram
- Tutorial

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:
- Bot created
- Bot added to chat
- 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:

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:

In chat:
