Try using Junos' On-box Python #Bonus 1 Something like ChatOps / Commit and post to Slack

The other day, I introduced Junos's On-box Python Commit Script. In that, I wrote something fluffy like "something like ChatOps" as an example of what can be realized with Commit Script.

That's why (?), This time it's something like ChatOps, so I wrote a Commit Script to post to Slack after committing with the Junos router. (You may get angry if you call this kind of thing ChatOps, but please forgive it as a simple example.)

code

The script looks like this: The URL should be replaced appropriately.

post-slack.py


from junos import Junos_Context
import json
import urllib
import urllib2

def post_slack(_username, _text):
  url = 'https://hooks.slack.com/services/************'
  headers = {'Content-Type': 'application/json'}
  params = json.dumps({"username": _username, "text": _text})

  req = urllib2.Request(url, params, headers)
  res = urllib2.urlopen(req)

  if res.getcode() != 200:
    message = '{0} {1} failed: {2}'.format(method, uri, res.getcode())
    raise SlackPostError(message)

def main():
  login_name = Junos_Context['user-context']['login-name']
  host_name = Junos_Context['hostname']
  product_name = Junos_Context['product']

  name = 'Junos Router({0})'.format(host_name)

  type = 'commit'
  if Junos_Context['commit-context'].has_key('commit-check'):
    type = 'commit check'
  elif Junos_Context['commit-context'].has_key('commit-confirm'):
    type = 'commit confirmed'
  elif Junos_Context['commit-context'].has_key('commit-boot'):
    print 'boot-time commit should be ignored'
    sys.exit()

  comment = ''
  if Junos_Context['commit-context'].has_key('commit-comment'):
    comment = ' with comment: {0}'.format(Junos_Context['commit-context']['commit-comment'])

  text = 'User {0} trying {1} to {2}({3}){4}.'.format(login_name, type, host_name, product_name, comment)
  post_slack(name, text)

if __name__ == '__main__':
  main()

Execution result

It works like this.

slack-junos-post2.png

Commentary

It's a simple script, so if you read it, you'll understand it, but I'll explain it briefly.

This script creates a message when a Commit event occurs, depending on what kind of Commit event it is, and posts it to Slack. In a Commit Script, you can refer to a variable called Junos_Context to get information about who executed the Commit event and why. For example, you can get the following input:

junos_context.json


{
	"product": "vmx",
	"user-context": {
		"login-name": "root",
		"user": "root",
		"class-name": "super-user",
		"uid": "0"
	},
	"routing-engine-name": "re0",
	"script-type": "commit",
	"re-master": null,
	"hostname": "vmx1",
	"pid": "17688",
	"tty": "/dev/pts/1",
	"commit-context": {
		"database-path": "/var/run/db/juniper.db",
		"commit-check": null
	},
	"chassis": "others",
	"localtime": "Tue Dec 27 19:36:45 2016",
	"localtime-iso": "2016-12-27 19:36:45 UTC"
}

If you read this result, you can see that the product "vmx" with the host name "vmx1" was Commit Checked by the user "root". What parameters are included is [Official Documentation](https://www.juniper.net/techpubs/en_US/junos16.1/topics/reference/general/junos-script-automation-junos-xsl-global- Since it is summarized in params-and-var.html), the message is generated based on the conditions such as whether it is commit check, whether it is commit confirmed, and whether there is a comment.

The part to be posted to Slack is cut out as the post_slack method, but it is just to generate the parameter including the content you want to post in JSON format and POST it using Urllib2.

By the way, the Commit Script doesn't know if the Commit was successful or not, so even if the Commit fails, it will be posted to Slack.

Recommended Posts

Try using Junos' On-box Python #Bonus 1 Something like ChatOps / Commit and post to Slack
Try using Junos On-box Python # 2 Commit Script
Try using Junos On-box Python # 1 Op Script
Image characters and post to slack (python slackbot)
Post to vim → Python → Slack
Post to slack with Python 3
Post to Twitter using Python
Post to Slack in Python
Try to make it using GUI and PyQt in Python
From Python to using MeCab (and CaboCha)
Log in to Slack using requests in Python
Try to operate Excel using Python (Xlwings)
Try something like Python for-else in Ruby
Try to make something like C # LINQ
Try to make BOT by linking spreadsheet and Slack with python 2/2 (python + gspread + slackbot)
Try to make BOT by linking spreadsheet and Slack with python 1/2 (python + gspread + slackbot)
Try using tensorflow ① Build python environment and introduce tensorflow
Try using ChatWork API and Qiita API in Python
(Python) Try to develop a web application using Django
Try to operate DB with Python and visualize with d3
Try to extract high frequency words using NLTK (python)
Something to enjoy with Prim Pro (X-Play) and Python
I saw this commit and thought I wanted something like rake version: bump in Python too