Skip to content

Instantly share code, notes, and snippets.

@Dzhuneyt
Created December 10, 2020 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dzhuneyt/06e5829e5e331f3c4667b4a60a12080b to your computer and use it in GitHub Desktop.
Save Dzhuneyt/06e5829e5e331f3c4667b4a60a12080b to your computer and use it in GitHub Desktop.
Create a Cognito User Pool and the first user, programmatically, using AWS CDK and Custom Resources
import {UserPool} from '@aws-cdk/aws-cognito';
import {Construct, Duration} from '@aws-cdk/core';
import {AwsCustomResource, AwsCustomResourcePolicy, PhysicalResourceId} from '@aws-cdk/custom-resources';
export class Cognito extends Construct {
public userPool: UserPool;
constructor(scope: Construct, id: string) {
super(scope, id);
const ADMIN_USERNAME = 'admin';
const ADMIN_PASSWORD = 'password';
this.userPool = new UserPool(this, 'Default', {
userPoolName: "TaxiApp",
autoVerify: {email: true},
passwordPolicy: {
minLength: 6,
requireDigits: false,
requireLowercase: false,
requireSymbols: false,
requireUppercase: false,
tempPasswordValidity: Duration.days(90),
},
});
const createFirstAdmin = new AwsCustomResource(this, 'createFirstAdmin', {
onCreate: {
service: 'CognitoIdentityServiceProvider',
action: 'adminCreateUser',
parameters: {
UserPoolId: this.userPool.userPoolId,
Username: ADMIN_USERNAME,
MessageAction: 'SUPPRESS',
TemporaryPassword: ADMIN_PASSWORD,
},
physicalResourceId: PhysicalResourceId.of(`createFirstAdmin_${ADMIN_USERNAME}`),
},
onDelete: {
service: "CognitoIdentityServiceProvider",
action: "adminDeleteUser",
parameters: {
UserPoolId: this.userPool.userPoolId,
Username: ADMIN_USERNAME,
},
},
policy: AwsCustomResourcePolicy.fromSdkCalls({resources: AwsCustomResourcePolicy.ANY_RESOURCE}),
});
const forceAdminPassword = new AwsCustomResource(this, 'forceAdminPassword', {
onCreate: {
service: 'CognitoIdentityServiceProvider',
action: 'adminSetUserPassword',
parameters: {
UserPoolId: this.userPool.userPoolId,
Username: ADMIN_USERNAME,
Permanent: true,
Password: ADMIN_PASSWORD,
},
physicalResourceId: PhysicalResourceId.of('forceAdminPassword'),
},
policy: AwsCustomResourcePolicy.fromSdkCalls({resources: AwsCustomResourcePolicy.ANY_RESOURCE}),
});
forceAdminPassword.node.addDependency(createFirstAdmin);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment