LoginSignup
2
1

IBM Cloud Functionsを利用してCISの送信元IPアドレス変更をSlackへ通知する

Last updated at Posted at 2023-06-29

はじめに

IBM Cloud Functionsを利用してCISの送信元IPアドレス変更をSlackへ定期的に通知する方法を紹介します。

スクリプト(bash)で実行した例は下記記事で紹介しておりますのでご参照ください。

IBM Cloud CISの送信元IPアドレス変更を検知する
https://qiita.com/aktech/items/f6cf0a9771c26c117825

今回はサーバーレスのFunctionsを用いる例となります。
image.png

Functions アクション(Action)の設定

Python3.11環境を選択しました。

image.png

cis-ip-check-action
import sys
import requests
import json

def main(params):
    try:
        url = "https://api.cis.cloud.ibm.com/v1/ips"
        url_slack = "https://hooks.slack.com/services/xxxxxxxxx/xxxxxxx/xxxxxxxxxxxxxxxxxxxxx"
        r = requests.get(url)
        if r.status_code != 200:
            return {
                'statusCode': r.status_code,
                'body': {'message': 'Error processing your request'}
            }
        elif r.json()["result"]["etag"] == "38f79d050aa027e3be3865e495dcc9bc":
            body = {'username':'CIS IP Check','icon_emoji':':warning:','text':'There is no difference.'}
            response = requests.post(url_slack,data=json.dumps(body))
            return {
                'body': {'message': 'There is no difference.'}
            }
        else:
            body = {'username':'CIS IP Check','icon_emoji':':warning:','text':'There is a difference. CIS IPS has been changed.'}
            response = requests.post(url_slack,data=json.dumps(body))
            return {
                'body': {'message': 'There is a difference. CIS IPS has been changed.'}
            }
    except requests.ConnectionError:
        return {
            'body': {'message': 'break.'}
        }

CISの送信元IPアドレスリストが変更となった場合、APIから応答されるetagが変更になることを前提としたコードになります(2023/06/29時点で応答されるetagは"38f79d050aa027e3be3865e495dcc9bc"です)

Functions トリガー(Trigger)の設定

トリガー > 作成 > トリガー > Periodic (時刻に基づいてアクションをトリガーします)

今回は、22:00 JST(10:00 PM)、23:00 JST(11:00 PM)、00:00 JST(12:00 AM) に実行する例です。
(Functionsの画面から定期実行間隔を指定可能。Cron構文での指定可能)

image.png

image.png

実行結果(トリガーによる定期実行)

Functionsで指定した時間にSlackへ定期通知ができていることを確認した。

image.png

実行結果(コードの動作確認)

コードを設定する画面で手動起動して動作確認することも可能

下記画面で起動ボタンを押すと、右側に結果が表示される

image.png

参考URL

IBM Cloud Functions からPythonで Slack にメッセージをPostする
https://qiita.com/c_u/items/5399b5bef20158787ca2

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1