Skip to content

Instantly share code, notes, and snippets.

@cbmeeks
Created February 17, 2025 16:11
Show Gist options
  • Save cbmeeks/caf026dafb2088a6915b450f346c3ff8 to your computer and use it in GitHub Desktop.
Save cbmeeks/caf026dafb2088a6915b450f346c3ff8 to your computer and use it in GitHub Desktop.
Add Cognito Users to a Group
# Before running, make sure you set your ~/.aws/credentials and ~/.aws/config properly.
# Just run: aws configure
# Then enter your access key, secret key and region.
import boto3
client = boto3.client('cognito-idp')
user_pool_id = '<<USER POOL ID>>' # Change to your user pool ID
group_name = 'MY_GROUP' # Change to whatever group you want. Make sure it exists first.
def add_user_to_group(user_pool_id, group_name, username):
try:
response = client.admin_add_user_to_group(
UserPoolId=user_pool_id,
Username=username,
GroupName=group_name
)
print(f"User {username} added to group {group_name}")
except client.exceptions.UserNotFoundException:
print(f"User {username} not found in the user pool.")
except client.exceptions.GroupNotFoundException:
print(f"Group {group_name} not found in the user pool.")
except Exception as e:
print(f"An error occurred: {e}")
users = [
'Moe.Howard',
'Larry.Fine',
'Shemp.Howard',
]
for user in users:
add_user_to_group(user_pool_id, group_name, user)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment