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?

【Lambda関数】アカウントにタグを付与

Posted at

はじめに

Organizationsで管理しているアカウントにタグを付与させるために、Lambda関数を作成しました。

概要

CloudShellからLambda関数を実行して、Organizationsに所属しているアカウントに以下のタグを付与させる。
・Env:[dev/stg/prd]
 →タグを見れば環境がわかるため
・System_name:任意のシステム名
 →SNSトピックにシステム名を付与させれば、アカウントタグを取得したLambda関数でメール送信が可能になる

構築内容

import boto3
import logging

# ロガー設定
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    org_client = boto3.client("organizations")

    # eventから変数を取得
    account_id  = event.get("account_id")
    env         = event.get("env")
    system_name = event.get("system_name")

    if not account_id or not env or not system_name:
        logger.error("Missing required parameters: account_id, env, system_name")
        return {
            "statusCode": 400,
            "body": "account_id, env, and system_name are required in event"
        }

    # タグを定義
    tags = [
        {"Key": "Env", "Value": env},
        {"Key": "SystemName", "Value": system_name}
    ]

    try:
        logger.info(f"Tagging account {account_id} with tags: {tags}")
        org_client.tag_resource(
            ResourceId=account_id,
            Tags=tags
        )
        logger.info(f"Successfully tagged account {account_id}")
        return {
            "statusCode": 200,
            "body": f"Tags {tags} were successfully added to account {account_id}"
        }
    except Exception as e:
        logger.exception(f"Failed to tag account {account_id}: {str(e)}")
        return {
            "statusCode": 500,
            "body": str(e)
        }

実行結果

CloudShellで実行

aws lambda invoke --function-name add_tag_account --payload '{"account_id":"123456789123","env":"Prd","system_name":"Test"}' --cli-binary-format raw-in-base64-out response.json --query 'StatusCode'; cat response.json

以下が表示されること

{"statusCode": 200, "body": "Tags [{'Key': 'Env', 'Value': 'Prd'}, {'Key': 'SystemName', 'Value': 'Test'}] were successfully added to account 123456789123"}

まとめ

アカウントにタグを付与させとけば、他のLambdaで使えたりするので便利かも
今回はキーを固定にしたけど、キーも指定することで汎用性が高まるかなと

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?