Creating Cognito user pools is more commonly done using CloudFormation templates. Various sections of the CloudFormation template correspond to the CLI commands that you saw in the previous section:
- You can start the template with a description and a name. We will call our template file cognito-user-pool-cf-template.yml. You can find the file under the resources folder for this recipe:
---
AWSTemplateFormatVersion: '2010-09-09'
Description: Cognito User Pool with SMS and MFA Verification
- Start to define the role for our resource with an inline policy definition, as follows:
Resources:
SNSRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service:
- "cognito-idp.amazonaws.com"
Action:
- "sts:AssumeRole"
Policies:
- PolicyName: "CognitoSNSPolicy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action: "sns:publish"
Resource: "*"
- Define the user pool resource with the type AWS::Cognito::UserPool:
UserPool:
Type: "AWS::Cognito::UserPool"
- Under Properties, define AutoVerifiedAttributes and AliasAttributes:
Properties:
AutoVerifiedAttributes:
- phone_number
UsernameAttributes:
- phone_number
- Define an SMS verification message and an email verification subject:
SmsVerificationMessage: 'Your verification code from qnatime.com is {####}.'
- Define MFA and SMS configuration, as follows:
MfaConfiguration: "ON"
SmsConfiguration:
ExternalId: 'some-unique-external-id-preferably-a-uuid'
SnsCallerArn: !GetAtt SNSRole.Arn
- We will define the AdminCreateUserConfig property, as follows:
AdminCreateUserConfig:
AllowAdminCreateUserOnly: false
InviteMessageTemplate:
SMSMessage: 'Your username for qnatime.com is {username} and password is {####}.'
UnusedAccountValidityDays: 7
We are not using InviteMessageTemplate in this recipe, as we are performing user creation by admin, but it is given for reference.
- Although it is not required, we will provide a name and add a tag for this user pool:
UserPoolName: 'Qnatime.com User Pool'
UserPoolTags:
Team: Dev
- In the Outputs section, we will return the user pool ID and the client ID, as follows:
Outputs:
UserPoolId:
Value: !Ref UserPool
Export:
Name: "UserPool::Id"
UserPoolClientId:
Value: !Ref UserPoolClient
Export:
Name: "UserPoolClient::Id"
The complete CloudFormation template is available in the code files.
- Execute the CloudFormation template to create a CloudFormation stack.
- You can run the describe-stacks sub-command to get the status and the user-pool-id. You can also use the describe-user-pool sub-command with the ID returned by the describe-stacks sub-command, in order to verify the new Cognito user pool.
- To clean up, you can delete the user pool by deleting the stack, or you can keep the stack.