티스토리 뷰

Mattermost로 메세지를 출력하려 할때 단순 text 형태로 출력되는 것이 가독성이 너무 떨어진다는 판단이 들어
AlertManager에서 Slack에 출력시키는 것처럼 할수 있는 방법이 없을까 조사하게 되었고

다음과 같은 방법을 찾게 되어 이에 대하여 기술하고자 한다.

Mattermost Attachments

참고
기본적으로 markdown 으로 기본적인 표현들이 가능하다. 다만 다수의 라인이 하나의 메세지로 전달되어야할때
이를 표현할 방법이 없어 이를 attachments라는 formatting option을 사용하여 표현하고자 한다.

처음 attachments 링크를 보고 첨부파일로 생각해서 이를 조사할 생각을 못하였다가 다시 확인해보니 markdown에서 표현하지 못하는 다른 표현을 할수 있다는 내용을 보고 이를 활용할수 있겠다 생각이 들었다.

먼저 Attachments를 소개하자면 다수의 text formatting 옵션을 가지고 slack의 non-markdown 연동과의 호환성 제공하는 배열이다.

다음과 같은 옵션을 제공한다.

  • fallback
  • color
  • author_name
  • author_link
  • author_icon
  • title
  • title_link
  • Fields (title, value, short)
  • image_url
  • thumb_url

위와 같은 옵션들을 attachments 배열내에 선언하여 사용할수 있다.
실제 추가되는 attachments 배열은 다음과 같이 추가되어진다. 예제와 함께 간단히 알아보도록 하자.

sample shell script

webhook 주소를 통해 아래와 같은 attachments를 포함한 message posting이 가능하다.

#!/bin/bash

# for message with attachments
curl -i -X POST -H "Content-Type: application/json" \
 -d '{"username": "pythonbot", "channel":"staging", "attachments": [{"text":"send a test message :tada:"}]}' \
 http://192.168.56.20/hooks/q4d3ikpupfbidkuo9uh8j8za5h

sample python code

먼저 config.json으로 url 부터 channel등을 입력받도록 하고,

{
    "mattermost_webhook_url": "http://192.168.56.20/hooks/q4d3ikpupfbidkuo9uh8j8za5h",
    "mattermost_webhook_channel": "dev"
}

앞선 shell script 와 같이 attachments를 포함한 message 전달을 python code로 수행할수 있다.

import requests
from urllib import request, error

_RED="#FF2D00"
_GREEN="009D31"

with open('config.json', 'r') as fd:
    cred = json.loads(fd.read())

def send_alarm_exit(message, color):
    headers = {'Content-Type': 'application/json'}
    values = '{ \
        "username": "pybot", \
        "channel": "' + cred["mattermost_webhook_channel"] + '", \
        "icon_url": "https://img.icons8.com/fluent/200/000000/binoculars.png", \
        "attachments": [{ \
            "color": "' + color + '", \
            "title": "test mattermost message", \
            "author_name": "mattermost alert", \
            "author_icon": "https://img.icons8.com/fluent/200/000000/binoculars.png", \
            "text": "' + message + '" \
        }] \
    }'
    response = requests.post(cred["mattermost_webhook_url"], headers=headers, data=values)
    # print(response.request.body)
    # print(response.status_code)
    # print(response.content)

Print result

실제 출력된 결과는 다음과 같다.
코드상에 color에 따라 다르게 출력도 시킬수 있으며 title에 대한 링크도 가능하다.

'DevOps > System&Tools' 카테고리의 다른 글

Grafana with okta  (0) 2021.10.19
Ansible dynamic global variable  (0) 2021.09.11
How to post message with api and bot token on mattermost  (0) 2021.07.05
Initialize Jenkins Authentication  (0) 2021.04.19
Selenium with Jenkins  (0) 2021.01.21
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함