AWS Cognito delete all users from a user pool

Viewed 8677

How can we delete all users from a specific user pool in AWS Cognito using AWS CLI?

6 Answers

try with below:

aws cognito-idp list-users --user-pool-id $COGNITO_USER_POOL_ID |
jq -r '.Users | .[] | .Username' |
while read uname1; do
  echo "Deleting $uname1";
  aws cognito-idp admin-delete-user --user-pool-id $COGNITO_USER_POOL_ID --username $uname1;
done

In order to speed up deletion, I modified @GRVPrasad's answer to use xargs -P which will farm deletions out to multiple processes.

aws cognito-idp list-users --user-pool-id $COGNITO_USER_POOL_ID | jq -r '.Users | .[] | .Username' | xargs -n 1 -P 5 -I % bash -c "echo Deleting %; aws cognito-idp admin-delete-user --user-pool-id $COGNITO_USER_POOL_ID --username %"

Here is a bash version based on @ajilpm's batch script:

# deleteAllUsers.sh
COGNITO_USER_POOL_ID=$1

aws cognito-idp list-users --user-pool-id $COGNITO_USER_POOL_ID |
jq -r '.Users | .[] | .Username' |
while read user; do
  aws cognito-idp admin-delete-user --user-pool-id $COGNITO_USER_POOL_ID --username $user
  echo "$user deleted"
done

You must have jq installed and remember to make the script executable: chmod +x deleteAllUsers.sh.

The user pool id can be provided as a command line argument: ./deleteAllUsers.sh COGNITO_USER_POOL_ID.

I created a script to do it from Windows CMD if you have AWS Cli installed and configured, which will delete all the users page by page, so you need to run it till all users are removed.

You need to have JQ downloaded and its path added to system env path for the following to work.

---delete.bat---

@echo off setlocal

for /f "delims=" %%I in 
  ('aws cognito-idp list-users --user-pool-id  $COGNITO_USER_POOL_ID ^| 
    jq -r ".Users | .[] | .Username"')
do 
  (aws cognito-idp admin-delete-user --user-pool-id $COGNITO_USER_POOL_ID --username %%I 
   echo %%I deleted)

---delete.bat---

Sorry cannot add comment. I had same requirement and slight modification in command mentioned by ajilpm worked in windows 10 for me. You need to download jq.exe and keep on path in command line

---Start.bat---

@echo off setlocal

for /f "delims=" %%I in ('aws cognito-idp list-users --user-pool-id us-west-2_O7rRBQ5rr --profile dev-hb ^| jq -r ".Users | .[] | .Username"') do ( aws cognito-idp admin-delete-user --user-pool-id us-west-2_O7rRBQ5rr --username %%I --profile dev-hb)

---delete.bat---

With Python and boto3: I use email as username

import boto3 as aws
import pandas as pd

client_cognito = aws.client('cognito-idp')
getProperties = pd.read_csv('CognitoUsers.csv',header=0)
usernames = getProperties['email']

for username in usernames:
    response = client_cognito.admin_delete_user(
        UserPoolId="us-east-1_xxxxxxxxx",
        Username = username,
    )

you need login in aws-cli with your AWS Access Key ID & AWS Secret Access Key

Related