Skip to content

Cognito user pool - Add user to groups in bulk

0

Cognito user pool console has a bulk user import operation, but I see no way there to add users to groups. Is there a tool (aws/community) for that? Thanks, JD

1 Answer
0

Bulk User Group Assignments in Cognito

There are several ways to handle bulk user group assignments in Cognito:

  1. AWS CLI Script
  2. AWS SDK (Python)

AWS CLI Script Solution

Note: This script is provided as a sample only, for illustrative purposes. Please use at your own risk. No support is provided.

#!/bin/bash

## Script to add multiple users to a Cognito user group
## Usage: ./add_users_to_group.sh <user-pool-id> <group-name> <users-file>

## Check if required parameters are provided
if [ $# -ne 3 ]; then
    echo "Usage: $0 <user-pool-id> <group-name> <users-file>"
    echo "Example: $0 us-east-1_g6HtViokm TestGroup users.txt"
    exit 1
fi

USER_POOL_ID=$1
GROUP_NAME=$2
USERS_FILE=$3

# Check if users file exists
if [ ! -f "$USERS_FILE" ]; then
    echo "Error: Users file '$USERS_FILE' not found."
    exit 1
fi

## Check if the group exists, create it if it doesn't
GROUP_EXISTS=$(aws cognito-idp list-groups --user-pool-id $USER_POOL_ID --query "Groups[?GroupName=='$GROUP_NAME'].GroupName" --output text)

if [ -z "$GROUP_EXISTS" ]; then
    echo "Group '$GROUP_NAME' does not exist. Creating it..."
    aws cognito-idp create-group --user-pool-id $USER_POOL_ID --group-name $GROUP_NAME --description "Group created by script"

    if [ $? -ne 0 ]; then
        echo "Error: Failed to create group '$GROUP_NAME'."
        exit 1
    fi

    echo "Group '$GROUP_NAME' created successfully."
fi

# Read users file line by line and add each user to the group
echo "Adding users to group '$GROUP_NAME'..."
TOTAL_USERS=0
SUCCESSFUL_ADDS=0

while IFS= read -r username || [ -n "$username" ]; do
    ## Skip empty lines and lines starting with #
    if [ -z "$username" ] || [[ $username == \#* ]]; then
        continue
    fi

    TOTAL_USERS=$((TOTAL_USERS + 1))

    echo "Adding user '$username' to group '$GROUP_NAME'..."
    aws cognito-idp admin-add-user-to-group \
        --user-pool-id $USER_POOL_ID \
        --group-name $GROUP_NAME \
        --username "$username"

    if [ $? -eq 0 ]; then
        SUCCESSFUL_ADDS=$((SUCCESSFUL_ADDS + 1))
        echo "User '$username' added successfully."
    else
        echo "Error: Failed to add user '$username' to group."
    fi
done < "$USERS_FILE"

echo "Summary: Added $SUCCESSFUL_ADDS out of $TOTAL_USERS users to group '$GROUP_NAME'."

## List users in the group to verify
echo "Users in group '$GROUP_NAME':"
aws cognito-idp list-users-in-group --user-pool-id $USER_POOL_ID --group-name $GROUP_NAME --query "Users[].Username" --output table
AWS
answered 9 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.