tabimoba.net

とあるエンジニアの雑記帳

OpenVPNの接続・切断をSlackに通知する

はじめに

OpenVPNに接続あるいは切断された際に、以下のようにSlackへ通知する仕組みを追加してみます。

f:id:tabimoba:20200406011910p:plain

手順

1. SlackのIncoming Webhooksを用意する

下記URLの手順に従い、Incoming Webhooksを用意します。あわせて、投稿先のワークスペースとチャンネルも用意します。 https://api.slack.com/incoming-webhooks

2. 接続・切断通知用のスクリプトを作成する

SCRIPT_DIR=`echo $(cd $(dirname $0) && pwd)`
/bin/sh ${SCRIPT_DIR}/send-slack-message.sh connect $common_name $untrusted_ip $ifconfig_pool_remote_ip
SCRIPT_DIR=`echo $(cd $(dirname $0) && pwd)`
/bin/sh ${SCRIPT_DIR}/send-slack-message.sh disconnect $common_name $untrusted_ip $ifconfig_pool_remote_ip
URL="<Incomming WebhooksのURL>"
#BGCOLOR="gray"
MESSAGE=""

if [ "$1" = "connect" ]; then
        #BGCOLOR="yellow"
        MESSAGE="VPN: $2 is connected.\nClient-IP: $3\nVPN-IP: $4"
fi

if [ "$1" = "disconnect" ]; then
        #BGCOLOR="green"
        MESSAGE="VPN: $2 is disconnected.\nClient-IP: $3\nVPN-IP: $4"
fi


curl -H "Content-Type: application/json" \
     -X POST \
     -m 5 \
     -d "{\"text\": \"$MESSAGE\" }" \
     $URL &

3. server.confに設定を追加する

/etc/openvpn/server.conf に以下の設定を追加します。

client-connect /opt/scripts/send-slack-connected-message.sh
client-disconnect /opt/scripts/send-slack-disconnected-message.sh