Amazon DetectiveのOrganizations全体有効化のために委任と自動有効化の設定をするPythonスクリプト書いた

Detectiveを全リージョンでOrganizations全体で有効化するPythonスクリプトです。サクッと有効化しましょう。
2022.01.12

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちは、臼田です。

みなさん、Detective有効化してますか?(挨拶

先日Amazon Detectiveが組織で有効化出来るようになったので以下の記事を書きました。

その際にまだAWS CLIやSDKが対応していなかったためマネジメントコンソール上で操作しましたが、無事対応したのでサクッと全リージョンで有効化するためのスクリプトを作りました。

更新内容と注意

API更新は以下の内容です。

この変更はbotocore v1.23.33から適用されています。

awscliやboto3を使用する場合はバージョンに留意してください。ちなみに2022/01/12時点ではCloudShellのawscliやboto3はまだバージョンが古いためこの作業ができませんでした。

スクリプト

手順はほとんどGuardDutyと同じです。以下のスクリプトとだいたい同じになりました。管理アカウント用とセキュリティ管理アカウント用の2本構成です。

しかし、ところどころパラメータなどが違うので気をつける必要があります。

AdminAccountId -> AccountIdとなっていたり、AccountDetails -> Accountsとなっていたりします。

管理アカウント用スクリプト

import boto3


admin_account = "999999999999"

ec2_client = boto3.client('ec2')
regions = list(map(lambda x: x['RegionName'],
                   ec2_client.describe_regions()['Regions']))

for region in regions:
    try:
        print("## " + region)
        detective = boto3.client('detective', region_name=region)
        detective.enable_organization_admin_account(
            AccountId=admin_account
        )
    except Exception as e:
        print("## Error Occurred")
        print(e)

セキュリティ管理アカウント用スクリプト

import boto3


email = "example@example.com"

account_id = boto3.client('sts').get_caller_identity()['Account']

ec2_client = boto3.client('ec2')
regions = list(map(lambda x: x['RegionName'],
                   ec2_client.describe_regions()['Regions']))

# create organizations accounts list
organizations = boto3.client('organizations')
accounts = list(
    map(lambda x: x['Id'], organizations.list_accounts()['Accounts']))
# delete owner account
accounts.remove(account_id)
account_details = []
for account in accounts:
    account_details.append({
        'AccountId': account,
        'EmailAddress': email
    })

for region in regions:
    try:
        print("## " + region)
        detective = boto3.client('detective', region_name=region)
        graph_arn = detective.list_graphs()['GraphList'][0]['Arn']
        # enable auto enable
        detective.update_organization_configuration(
            GraphArn=graph_arn,
            AutoEnable=True
        )
        # add all accounts
        detective.create_members(
            GraphArn=graph_arn,
            DisableEmailNotification=True,
            Accounts=account_details
        )
    except Exception as e:
        print("## Error Occurred")
        print(e)

まとめ

DetectiveをOrganizations全体で有効化するときに役立つスクリプトを作りました。

ガンガン有効化していきましょう。