Skip to content

Instantly share code, notes, and snippets.

@yardbirdsax
Created January 29, 2020 17:01
Show Gist options
  • Save yardbirdsax/6991a238c65e6bd75bd0b0196eea8312 to your computer and use it in GitHub Desktop.
Save yardbirdsax/6991a238c65e6bd75bd0b0196eea8312 to your computer and use it in GitHub Desktop.
Creating Cognito users from a JSON export
#! /usr/bin/env python3
import boto3
import botocore
import json
import argparse
from pprint import pprint
# import sys
parser = argparse.ArgumentParser()
parser.add_argument("--filename",type=str,help="The name of the JSON file that contains the users to create.")
parser.add_argument("--userpool-name",type=str,help="The name of the user pool to create the users in.")
parser.add_argument('--password',type=str,help="The temporary password to set.")
args = parser.parse_args()
try:
fileHandle = open(file=args.filename,mode='r')
userObj = json.load(fileHandle)
client = boto3.client('cognito-idp')
userPools = client.list_user_pools(MaxResults=60)
# pprint(userPools)
userPoolId = ""
for userPool in userPools['UserPools']:
if userPool['Name'] == args.userpool_name:
userPoolId = userPool['Id']
if userPoolId == "":
raise Exception("User pool specified not found.")
else:
print(f"User pool found, ID is {userPoolId}.")
for user in userObj['Users']:
userName = user['Username']
for attrib in user['Attributes']:
if attrib['Name'] == 'email':
emailAddress = attrib['Value']
password = args.password
# Check if the user already exists
try:
existingUser = client.admin_get_user(UserPoolId=userPoolId,Username=userName)
print(f"User {userName} already exists, skipping.")
continue
except client.exceptions.UserNotFoundException:
print(f"User {userName} not found, creating.")
response = client.admin_create_user(
UserPoolId=userPoolId,
Username=userName,
UserAttributes=[
{
'Name': 'email',
'Value': emailAddress
},
{
'Name': 'email_verified',
'Value': 'True'
}
],
MessageAction="SUPPRESS",
TemporaryPassword=password
)
print(f" User {userName} created, temporary password is {password}.")
except Exception as inst:
print(f"Error occurred! Detail: {inst}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment