0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

EventBridgeのルールをboto3で一括削除

Posted at

はじめに

EventBridgeのルールを数百個削除する必要があったので作成しました。
ただコンソールから手動で削除する場合でも、チェックボックスがあるので少数であれば比較的楽に消せると思います。
削除結果をログとして残しておきたい場合などに参考にしてもらえたらと思います。

目次

  1. コード
  2. boto3のエラーハンドリング
  3. 参考文献

コード

import boto3
from botocore.exceptions import ClientError

delete_rules = ["rule_0","rule_1"]

client = boto3.client('events')

print(f'all rules: {len(delete_rules)}')
cnt = 0
fails = []
for delete_rule in delete_rules:
    print(f'start: {delete_rule}')
    try:
        res_targets = client.list_targets_by_rule(Rule=delete_rule)
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFoundException':
            print(f'{delete_rule} not found, skip\n')
            fails.append(delete_rule)
            continue
    targets = [target['Id'] for target in res_targets['Targets']]
    res_rules = client.describe_rule(Name=delete_rule)
    if res_rules['State'] == 'DISABLED':
        client.remove_targets(Rule=delete_rule,Ids=targets)
        print('delete targets\n')
        cnt+=1
    else:
        print('status is ENABLED, skip\n')
        fails.append(delete_rule)
        continue
    client.delete_rule(Name=delete_rule)
    print('delete rule\n')
    
print(f'total deleted rules count: {cnt}')
print(f'fails: {fails}')

boto3のエラーハンドリング

削除対象のルールが実際には存在しなかった場合を想定してResourceNotFoundExceptionを指定します。

なお、直接

try:
    res_targets = client.list_targets_by_rule(Rule=delete_rule)
except ResourceNotFoundException:

のように指定すると

NameError: name 'ResourceNotFoundException' is not defined

となるので注意が必要。

参考文献

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?