この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
こんにちは、臼田です。
めんどくさいことが大嫌いなので、今回も楽をするスクリプトを共有します。
SNSのunsubscribeリンク
Amazon SNSのメール通知の本文には通知を停止する「unsubscribe」リンクがあり、よくメールを見た人が間違えて押すことによりSNSの配信が停止されるという運用ミスが発生します。
リンクの存在意義自体はあるのでこの機能自体は悪くないものですが、運用上気をつけないといけないので自前の通知システムの場合には無効化したいです。そのための設定は下記で紹介されています。
で、このAPIを叩く際に初回のConfirm subscriptionメールからパラメータを抜き出す作業はただただめんどうなので、なるべく楽にやりたいわけです。
更にいうと、下記みたいに全リージョンでSNS Topicを作成した日には、現状ではConfirmメールが15通(全リージョン分)届くのです、やってられませんね。
というわけで、届いたメールのリンクをコピペするだけでこれを実現したいと思います。
スクリプト
下記のPythonスクリプトを適当に保存して実行してください。Python3で実行してください。
import re
import boto3
snsurl_pattern = re.compile(r'https://sns\.(.*?)\..*TopicArn=(.*?)&.*Token=([0-9,a-f]*)&.*')
print('please enter "Confirm subscription" Link URL. (e.g. https://sns.us-east-1.amazonaws.com/confirmation.html?TopicArn=...)')
while True:
input_url = input('(if you want to stop, please enter "end") enter url: ')
if input_url == "end": break
m = snsurl_pattern.match(input_url)
if m is None:
print('input is wrong. please enter "Confirm subscription" Link URL.')
continue
region = m.group(1)
topicarn = m.group(2)
token = m.group(3)
sns = boto3.client('sns', region_name=region)
r = sns.confirm_subscription(
TopicArn=topicarn,
Token=token,
AuthenticateOnUnsubscribe='true'
)
print(r)
やってみた
SNSのサブスクリプションを作成した際に届くメールの「Confirm subscription」リンクをコピーします。
スクリプトを実行してURLを貼り付けます。
$ python confirm-and-disable-unsubscribe.py
please enter "Confirm subscription" Link URL. (e.g. https://sns.us-east-1.amazonaws.com/confirmation.html?TopicArn=...)
(if you want to stop, please enter "end") enter url: https://sns.ap-northeast-1.amazonaws.com/confirmation.html?TopicArn=arn:aws:sns:ap-northeast-1:999999999999:send_mail&Token=sampletoken&Endpoint=testmail@example.com
{'SubscriptionArn': 'arn:aws:sns:ap-northeast-1:999999999999:send_mail:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx', 'ResponseMetadata': {'RequestId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx', 'content-type': 'text/xml', 'content-length': '404', 'date': 'Sun, 23 Sep 2018 10:47:27 GMT'}, 'RetryAttempts': 0}}
(if you want to stop, please enter "end") enter url: end
繰り返しURLを入力できるので、15通あってもコピペし続けるだけで終わります。
まとめ
SNSにメールを登録する際のunsubscribeリンク無効化をできるだけ簡単にできるスクリプトを紹介しました。
本当は、最初からAPIで出来ると嬉しいのですが、SNSの性質上Topic管理者が受け取る側の意思を無視して勝手にunsubscribeを無効にすることはいろいろ問題があるので仕方ないですね。
メールをトリガーに上記のようなスクリプトを発動させることができれば、より幸せかもしれませんね。