Last active
June 22, 2020 02:08
-
-
Save jayzalowitz/6886e47e69871be0426e39d9401b95e2 to your computer and use it in GitHub Desktop.
Deleting unused aws sns topics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# you will need to set your keys and your region name in your ~/.aws/config for this to work | |
import boto3 | |
session = boto3.session.Session(region_name='us-east-1') # make sure this is the region you are using | |
sns = session.resource('sns') | |
client = boto3.client('sns') | |
topics = {} | |
dead_subs = [] | |
for topic in sns.topics.all(): | |
topics[topic.arn] = 0 | |
for sub in client.get_paginator('list_subscriptions').paginate(): | |
for subscription in sub["Subscriptions"]: | |
arn = subscription["TopicArn"] | |
SubscriptionArn = subscription["SubscriptionArn"] | |
try: | |
topics[arn] = topics[arn] + 1 | |
except Exception: | |
dead_subs.append(SubscriptionArn) | |
dead_topics = { key:value for (key,value) in topics.items() if value == 0} | |
for dead_topic_arn in dead_topics: | |
response = client.delete_topic( | |
TopicArn=dead_topic_arn | |
) | |
print(dead_topic_arn) | |
for dead_sub_arn in dead_subs: | |
response = client.unsubscribe( | |
SubscriptionArn=dead_sub_arn | |
) | |
print("dead_topics:") | |
print(dead_topics) | |
print("dead_subscriptions:") | |
print(dead_subs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment