LoginSignup
5
1

コスト配分タグのアクティブ化をスケジュールで自動化する

Posted at

初めに

Organizationsで管理するコスト配分タグについて、アクティブ化漏れを防ぐためにスケジュールで有効化する機会があったのでその内容について記載します。

コスト配分タグとは

タグはAWSに割り当てるラベルで、キーと値から構成されます。
タグを割り当てておくことでAWSのコストについてもタグごとに管理することができます。
逆にタグがついていないと詳細にコストを追うことが困難になることがあるので注意が必要だと思います。

構成

本当はコスト配分タグが追加される度に有効化ができればよかったのですが、そのやり方は難しそうだったのでコスト配分タグの有効化を行うLambdaをEventBridgeでスケジュール実行する形をとりました。
Lambdaで実行するコマンドは以下の2つです。

Lambda

Pythonで記載しています。
「ListCostAllocationTags」で非アクティブのコスト配分タグのリストを取得し、「UpdateCostAllocationTagsStatus」で有効化する処理です。

import boto3

client = boto3.client('ce')

def lambda_handler(event, context):
    try:
        print(f'START: ListCostAllocationTags')
        response = client.list_cost_allocation_tags(
            Status='Inactive',
            Type='UserDefined'
        )
        print(f'InactiveList: {response}')
        print(f'END: ListCostAllocationTags')
        print(f'START: UpdateCostAllocationTagsStatus')
        for x in response['CostAllocationTags']:
            print(f'TagKey: {x.get('TagKey')}')
            client.update_cost_allocation_tags_status(
                CostAllocationTagsStatus=[
                    {
                        'TagKey': x.get('TagKey'),
                        'Status': 'Active'
                    }
                ]
            )
        print(f'END: UpdateCostAllocationTagsStatus')
        print(f'<<< SUCCESS >>>')
        return('200')
    except Exception as e:
        print(f'<<< ERROR: {e} >>>')
        return('400')

また、LambdaのIAMロールには以下の権限付与をしておきます。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ce:UpdateCostAllocationTagsStatus",
                "ce:ListCostAllocationTags"
            ],
            "Resource": "*"
        }
    ]
}

EventBridge

EventBridgeのスケジュール機能で作成したLambdaを定期実行するようにスケジュール設定を行います。
実行間隔は任意の間隔で、ターゲットに作成したLambdaを指定します。

検証

コスト配分タグの一部を非アクティブ化します。
image.png

LambdaをPythonで作成します。
image.png

image.png

EventBridgeのスケジュールでLambdaを指定したスケジュールを作成します。

image.png

スケジュールで実行されるのを待ちます。

image.png

非アクティブ化したコスト配分タグが有効化されるのを確認できました。

image.png

終わりに

Organizationsで新たにAWSアカウントを招待した時にはコスト配分タグは非アクティブとなってしまうので、そのような場合にアクティブ化漏れを防ぐことが可能です。
何かの参考になれば幸いです。

5
1
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
5
1