LoginSignup
3
2

More than 1 year has passed since last update.

【AWS】LambdaからCognitoユーザーを削除する

Posted at

LambdaからCognitoユーザーを削除することがあり、少し手間取ったので残しておきます。

前提

  • Cognitoの削除が可能なポリシーをLambdaのロールにアタッチしていること。
  • ※今回はAWS管理ポリシーの AmazonCongitoPowerUser をLambdaのロールにアタッチしています。
  • LambdaのランタイムはNode.js 14.x です。

Lambdaのコード

index.js
let aws = require("aws-sdk");

exports.handler = async (event) => {

    // eventから削除するCognitoユーザーのユーザー名リストを受け取る
    let userNameList = event.userNameList;

    // Cognitoユーザーの無効化メソッドをコール
    await disalbeCognito(userNameList);

    const response = {
        statusCode: 200,
    };
    return response;
};

/**
 * Cognito情報を無効化し、ログインできないようにする
 */
async function disalbeCognito(userNameList){

    if (userNameList.length > 0) {
        // Cognitoを使う準備
        aws.config.update({
            region: 'ap-northeast-1',
        });
        const cognito = new aws.CognitoIdentityServiceProvider({
            apiVersion: '2016-04-18'
        });
        // 対象のCognitoユーザープールID
        const user_pool_id = "hogehoge";

        for (let userName of userNameList) {
            // ユーザー削除
            try {
                await cognito.adminDeleteUser({
                    UserPoolId: user_pool_id,
                    Username: userName
                }).promise();
                console.log("Success! userName : " + userName);
            } catch (err) {
                console.log("Failed! userName : " + userName);
                if (err.code == 'UserNotFoundException') {
                    // ユーザープールにユーザーが存在していない場合
                    console.log('UserNotFoundException');
                } else {
                    // その他のエラー
                    console.log(err, err.stack);
                }
                throw err;
            }
        }
    }
}
3
2
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
3
2