LoginSignup
4
5

More than 3 years have passed since last update.

AWS Lambda boto3でCognitoのユーザーを削除する

Last updated at Posted at 2020-11-27

はじめに

AWS LambdaでCognitoのユーザーを削除します。
ランタイムはpythonです。
環境変数COGNITO_MAX_RESULTSには、50を指定します。
ユーザープールの数が50以下である事を想定しています。
Cognitoからユーザーを削除する場合、ループ処理となり、たまにコケることがあるため、リトライ処理を追加しています。

Lambdaのスクリプト

Lambda
import os
import boto3

cognito = boto3.client('cognito-idp', region_name='ap-northeast-1')

def handler(event, context):

    user_pool_name = 'ユーザープール名'
    user_ids = ['ユーザーID']

    # Cognitoからユーザーを削除する
    response = delCognitoUser(user_pool_name, user_ids)

    return response

    def getUserPoolId(user_pool_name):
        """[サービスに紐づくCognitoのユーザープールIDを取得する]

        Args:
            user_pool_name ([str]): [Cognitoユーザープール名]

        Returns:
            [str]: [CognitoユーザープールID]
        """

        # COGNITO_MAX_RESULTSの数だけ、ユーザープールの情報を取得する
        userPools = cognito.list_user_pools(
            MaxResults=int(os.environ['COGNITO_MAX_RESULTS'])
        )

        # サービス識別名に紐づくユーザープールIDを探索する
        for userPool in userPools['UserPools']:
            if userPool['Name'] == user_pool_name:
                return userPool['Id']

    def delCognitoUser(user_pool_name, user_ids):   
        """[Cognitoからユーザーを削除する]

        Args:
            user_pool_name ([str]): [Cognitoユーザープール名]
            user_ids ([list]): [ユーザーID]

        Returns:
            [list]: [Cognitoの結果]
        """

        # サービスに紐づくCognitoのユーザープールIDを取得する
        user_pool_id = getUserPoolId(user_pool_name)

        for user_id in user_ids:
            # Cognitoのユーザープールからユーザーを削除する

            while True:
                try:
                    response = cognito.admin_delete_user(
                        UserPoolId=user_pool_id,
                        Username=user_id
                    )
                    print(user_id)
                    print(response)
                except cognito.exceptions.TooManyRequestsException:
                    print('time wait 5 seconds')
                    time.sleep(5)  # 必要であれば失敗時の処理
                except cognito.exceptions.UserNotFoundException:
                    print('UserNotFoundException: ' + user_id)
                    break
                else:
                    break  # 失敗しなかった時はループを抜ける
            else:
                print('Do not delete: ' + user_id)
                continue  # リトライが全部失敗した時の処理

        return True
4
5
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
4
5