🙆‍♀️

【cloudfront編】AWS Boto3 by Pythonで特定タグ付与状況のリスト抽出

2023/03/15に公開約1,700字

1. 本稿の概要

◆ ゴール

以下のような機能を満たすPythonスクリプトを作成しました。
こちらはcloudfront向けです。

  • CloudFront Distributionsで特定タグ(Owner)の付与状況をリスト化
  • ローカル環境でI/Oが自由なPythonスクリプトとして実行
  • その抽出結果はCSVカンマ区切り形式でローカルに出力

◆ 背景、前提、その他サービスまとめなど

全体論はこちら を参照
CloudfrontのBotoというかAPIは少々勝手が違うんですかね・・・もっと簡単にできる方法あれば教えてください
※単にタグを棚卸したり付与するだけならタグエディタで見るのが一番楽かとは思います。

2. 開発

◆ 概説

CloudFrontのID、Ownerタグが未付与のリソースの一覧を出力します。
とりあえず単体では東京リージョンのみを対象としています。

◆ コード

check_owner_tag_cloudfront.py
import boto3 # pip install boto3

def check_owner_tag_cloudfront(arg_region = 'ap-northeast-1'):
    cloudfrontclient = boto3.client(service_name = 'cloudfront', region_name=arg_region)
    resp_data = cloudfrontclient.list_distributions()

    for num, distribution in enumerate(resp_data['DistributionList']['Items'], 1):
        resp_tags = cloudfrontclient.list_tags_for_resource(
            Resource=distribution['ARN']
        )
        cloudfront_tags = dict([(tag['Key'], tag['Value']) for tag in resp_tags['Tags']['Items']])
        cloudfront_name = distribution['DomainName']
        cloudfront_owner = cloudfront_tags.get('Owner', 'Ownerタグなし')
        print(str(num)  + ',' + str(arg_region) + ',' + str(cloudfront_name) + ',' + str(cloudfront_owner))
 
if __name__ == "__main__":
    check_owner_tag_cloudfront()

◆ 実行例

py .\check_owner_tag_cloudfront.py
1,ap-northeast-1,xxxxxxxxxxxxxxxx.cloudfront.net,Ownerタグなし
2,ap-northeast-1,yyyyyyyyyyyyyyyy.cloudfront.net,kangaezaru
...

◆ 参考等

Discussion

ログインするとコメントできます