Junso의 On-box Python# 사은품 1ChatOps의 무언가/Commiit를 사용해 슬랙에 보내보세요.

며칠 전 Junso의 On-box Python의 Commiit Script를 소개합니다.
그중에서도 Commit Script가 이룰 수 있는 예로'ChatOps의 무엇'같은 불안한 일들을 적었다.
그러니까 (´63;)이번엔 ChatOps에 대해 뭐냐면 Junso 라우터에 Commiit를 먼저 쓴 다음 Slack에 Commiit Script를 썼어요.
(이 정도 사안을 ChatOps라고 부르면 욕을 먹을 수도 있지만 간단한 예이니 용서해 주세요.)

코드


스크립트는 다음과 같습니다.URL을 적절하게 바꿔야 합니다.
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()

실행 결과


이런 느낌으로 일하다.

해설


간단한 각본이라서 읽으면 알 것 같지만, 간단하게 설명해 주세요.
이 스크립트에서는 공용 이벤트가 발생할 때 해당 공용 이벤트의 유형에 따라 정보를 생성하여 Slack에 보냅니다.
Commit Script에서는 참조Junos_Context 변수를 통해 해당 Commiit 이벤트를 누가 어떤 이유로 수행했는지 정보를 얻을 수 있습니다.
예를 들어, 다음과 같은 입력을 사용할 수 있습니다.
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"
}
이 결과를 읽으면'vmx1'호스트 이름을 가진'vmx'제품으로'루트'사용자가 Commiit Check을 진행했음을 알 수 있습니다.
어떤 매개 변수공식 문서가 포함되어 있기 때문에 이를 바탕으로commiit check,commiit confirmed,유무 평론 등 조건에서 정보를 생성했습니다.
슬랙에서 사서함에 있는 부분에 대해postSlack 방법으로 잘라내어 JSON 형식의 Post 내용을 포함하는 인자를 생성하였으며 Urllib2로만 POST를 진행하였습니다.
그나저나 Commit Script는 이 Commiit의 성공 여부를 알지 못하며, 설령 Commiit가 실패하더라도 Slack에 의해 인수될 것이다.

좋은 웹페이지 즐겨찾기