LoginSignup
4
6

More than 5 years have passed since last update.

AWS LambdaでCognitoユーザ一覧を取得

Posted at

意外と情報がなくて手こずったので備忘録。

とりあえず全ユーザを取得したい場合

フィルタや属性の指定は不要なので、以下のようなロジックを書けばOK。(Serverless Frameworkで開発することを前提としてます。)

ちなみに引数としてUserPoolIdをもらう前提で書いてます。

import json
from datetime import datetime
import os
import boto3

cognito_client = boto3.client('cognito-idp')

def list_users(event, context):

    if 'UserPoolId' not in event:
        raise KeyError("UserPoolId does not exist.")

    response = cognito_client.list_users(
        UserPoolId = event['UserPoolId']
    )

    return json.dumps(response, default=support_datetime_default)

def support_datetime_default(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(repr(obj) + " is not JSON serializable")

support_datetime_default関数を利用することで、response内に存在する「datetime.datetime・・・」という厄介でそのままJSON化できない値をJSON化可能な文字列に変換してくれます。

serverless.ymlはこんな感じ。引数でアクセスに必要なキーを取得し、かつIAM Roleを割り当てるので、これなら機密情報は何も載りません。

service: lambda-cognito-user-manager

provider:
  name: aws
  runtime: python3.6
  region: us-east-1
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "cognito-idp:ListUsers"
      Resource: "arn:aws:cognito-idp:*"

functions:
  cognito-manager:
    handler: handler.list_users
    memorySize: 128
    timeout: 

実行してみる

引数には以下を渡します。

{
  "UserPoolId": "us-east-1_XXXXXXXXXXX"
}

無事、値が取れました。

{
  "Users": [
    {
      "Username": "admin",
      "Attributes": [
        {
          "Name": "sub",
          "Value": "00000000-0000-0000-XXXX-XXXXXXXXXXXX"
        },
        {
          "Name": "email_verified",
          "Value": "false"
        },
        {
          "Name": "email",
          "Value": "xxxxxx@xxx.com"
        }
      ],
      "UserCreateDate": "2018-09-01T07:07:28.497000+00:00",
      "UserLastModifiedDate": "2018-09-01T07:09:20.934000+00:00",
      "Enabled": true,
      "UserStatus": "CONFIRMED"
    }
  ],
  "ResponseMetadata": {
    "RequestId": "XXXXXXXX-xxxx-xxxx-0000-XXXXXXXXXX",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "date": "Sun, 02 Sep 2018 08:37:00 GMT",
      "content-type": "application/x-amz-json-1.1",
      "content-length": "312",
      "connection": "keep-alive",
      "x-amzn-requestid": "XXXXXXXX-xxxx-xxxx-0000-XXXXXXXXXX"
    },
    "RetryAttempts": 0
  }
}

その他注意点など

Limitに60までしか指定できないとか、それ以上を取得する場合はどうするかとか、、、その辺はこちらの記事が参考になりそう。

[Boto3]ListUsersAPIでCognitoのユーザーを検索する

4
6
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
6