Skip to content

Terraform module to create Amazon Cognito User Pools, configure its attributes and resources such as app clients, domain, resource servers. Amazon Cognito User Pools provide a secure user directory that scales to hundreds of millions of users.

License

Notifications You must be signed in to change notification settings

lgallard/terraform-aws-cognito-user-pool

Repository files navigation

Terraform

terraform-aws-cognito-user-pool

Terraform module to create Amazon Cognito User Pools, configure its attributes and resources such as app clients, domain, resource servers. Amazon Cognito User Pools provide a secure user directory that scales to hundreds of millions of users. As a fully managed service, User Pools are easy to set up without any worries about standing up server infrastructure.

Usage

You can use this module to create a Cognito User Pool using the default values or use the detailed definition to set every aspect of the Cognito User Pool

Check the examples where you can see the simple example using the default values, the simple_extended version which adds  app clients, domain, resource servers resources, or the complete version with a detailed example.

Example (simple)

This simple example creates a AWS Cognito User Pool with the default values:

module "aws_cognito_user_pool_simple" {

  source  = "lgallard/cognito-user-pool/aws"

  user_pool_name = "mypool"

  tags = {
    Owner       = "infra"
    Environment = "production"
    Terraform   = true
  }

Example (conditional creation)

If you need to create Cognito User Pool resources conditionally in ealierform versions such as 0.11, 0,12 and 0.13 you can set the input variable enabled to false:

# This Cognito User Pool will not be created
module "aws_cognito_user_pool_conditional_creation" {

  source  = "lgallard/cognito-user-pool/aws"

  user_pool_name = "conditional_user_pool"

  enabled = false

  tags = {
    Owner       = "infra"
    Environment = "production"
    Terraform   = true
  }

}

For Terraform 0.14 and later you can use count inside module blocks, or use the input variable enabled as described above.

Example (complete)

This more complete example creates a AWS Cognito User Pool using a detailed configuration. Please check the example folder to get the example with all options:

module "aws_cognito_user_pool_complete" {

  source  = "lgallard/cognito-user-pool/aws"

  user_pool_name           = "mypool"
  alias_attributes         = ["email", "phone_number"]
  auto_verified_attributes = ["email"]

  deletion_protection = "ACTIVE"

  admin_create_user_config = {
    email_subject = "Here, your verification code baby"
  }

  email_configuration = {
    email_sending_account  = "DEVELOPER"
    reply_to_email_address = "email@example.com"
    source_arn             = "arn:aws:ses:us-east-1:888888888888:identity/example.com"
  }

  password_policy = {
    minimum_length    = 10
    require_lowercase = false
    require_numbers   = true
    require_symbols   = true
    require_uppercase = true
  }

  schemas = [
    {
      attribute_data_type      = "Boolean"
      developer_only_attribute = false
      mutable                  = true
      name                     = "available"
      required                 = false
    },
    {
      attribute_data_type      = "Boolean"
      developer_only_attribute = true
      mutable                  = true
      name                     = "registered"
      required                 = false
    }
  ]

  string_schemas = [
    {
      attribute_data_type      = "String"
      developer_only_attribute = false
      mutable                  = false
      name                     = "email"
      required                 = true

      string_attribute_constraints = {
        min_length = 7
        max_length = 15
      }
    }
  ]

  recovery_mechanisms = [
     {
      name     = "verified_email"
      priority = 1
    },
    {
      name     = "verified_phone_number"
      priority = 2
    }
  ]

  tags = {
    Owner       = "infra"
    Environment = "production"
    Terraform   = true
  }

Requirements

Name Version
terraform >= v0.13.7
aws >= 4.38

Providers

Name Version
aws 5.42.0

Modules

No modules.

Resources

Name Type
aws_cognito_identity_provider.identity_provider resource
aws_cognito_resource_server.resource resource
aws_cognito_user_group.main resource
aws_cognito_user_pool.pool resource
aws_cognito_user_pool_client.client resource
aws_cognito_user_pool_domain.domain resource
aws_cognito_user_pool_ui_customization.default_ui_customization resource
aws_cognito_user_pool_ui_customization.ui_customization resource

Inputs

Name Description Type Default Required
admin_create_user_config The configuration for AdminCreateUser requests map(any) {} no
admin_create_user_config_allow_admin_create_user_only Set to True if only the administrator is allowed to create user profiles. Set to False if users can sign themselves up via an app bool true no
admin_create_user_config_email_message The message template for email messages. Must contain {username} and {####} placeholders, for username and temporary password, respectively string "{username}, your verification code is {####}" no
admin_create_user_config_email_subject The subject line for email messages string "Your verification code" no
admin_create_user_config_sms_message - The message template for SMS messages. Must contain {username} and {####} placeholders, for username and temporary password, respectively string "Your username is {username} and temporary password is {####}" no
alias_attributes Attributes supported as an alias for this user pool. Possible values: phone_number, email, or preferred_username. Conflicts with username_attributes list(string) null no
auto_verified_attributes The attributes to be auto-verified. Possible values: email, phone_number list(string) [] no
client_access_token_validity Time limit, between 5 minutes and 1 day, after which the access token is no longer valid and cannot be used. This value will be overridden if you have entered a value in token_validity_units. number 60 no
client_allowed_oauth_flows The name of the application client list(string) [] no
client_allowed_oauth_flows_user_pool_client Whether the client is allowed to follow the OAuth protocol when interacting with Cognito user pools bool true no
client_allowed_oauth_scopes List of allowed OAuth scopes (phone, email, openid, profile, and aws.cognito.signin.user.admin) list(string) [] no
client_auth_session_validity Amazon Cognito creates a session token for each API request in an authentication flow. AuthSessionValidity is the duration, in minutes, of that session token. Your user pool native user must respond to each authentication challenge before the session expires. Valid values between 3 and 15. Default value is 3. number 3 no
client_callback_urls List of allowed callback URLs for the identity providers list(string) [] no
client_default_redirect_uri The default redirect URI. Must be in the list of callback URLs string "" no
client_enable_token_revocation Whether the client token can be revoked bool true no
client_explicit_auth_flows List of authentication flows (ADMIN_NO_SRP_AUTH, CUSTOM_AUTH_FLOW_ONLY, USER_PASSWORD_AUTH) list(string) [] no
client_generate_secret Should an application secret be generated bool true no
client_id_token_validity Time limit, between 5 minutes and 1 day, after which the ID token is no longer valid and cannot be used. Must be between 5 minutes and 1 day. Cannot be greater than refresh token expiration. This value will be overridden if you have entered a value in token_validity_units. number 60 no
client_logout_urls List of allowed logout URLs for the identity providers list(string) [] no
client_name The name of the application client string null no
client_prevent_user_existence_errors Choose which errors and responses are returned by Cognito APIs during authentication, account confirmation, and password recovery when the user does not exist in the user pool. When set to ENABLED and the user does not exist, authentication returns an error indicating either the username or password was incorrect, and account confirmation and password recovery return a response indicating a code was sent to a simulated destination. When set to LEGACY, those APIs will return a UserNotFoundException exception if the user does not exist in the user pool. string null no
client_read_attributes List of user pool attributes the application client can read from list(string) [] no
client_refresh_token_validity The time limit in days refresh tokens are valid for. Must be between 60 minutes and 3650 days. This value will be overridden if you have entered a value in token_validity_units number 30 no
client_supported_identity_providers List of provider names for the identity providers that are supported on this client list(string) [] no
client_token_validity_units Configuration block for units in which the validity times are represented in. Valid values for the following arguments are: seconds, minutes, hours or days. any
{
"access_token": "minutes",
"id_token": "minutes",
"refresh_token": "days"
}
no
client_write_attributes List of user pool attributes the application client can write to list(string) [] no
clients A container with the clients definitions any [] no
default_ui_customization_css CSS file content for default UI customization string null no
default_ui_customization_image_file Image file path for default UI customization string null no
deletion_protection When active, DeletionProtection prevents accidental deletion of your user pool. Before you can delete a user pool that you have protected against deletion, you must deactivate this feature. Valid values are ACTIVE and INACTIVE. string "INACTIVE" no
device_configuration The configuration for the user pool's device tracking map(any) {} no
device_configuration_challenge_required_on_new_device Indicates whether a challenge is required on a new device. Only applicable to a new device bool null no
device_configuration_device_only_remembered_on_user_prompt If true, a device is only remembered on user prompt bool null no
domain Cognito User Pool domain string null no
domain_certificate_arn The ARN of an ISSUED ACM certificate in us-east-1 for a custom domain string null no
email_configuration The Email Configuration map(any) {} no
email_configuration_configuration_set The name of the configuration set string null no
email_configuration_email_sending_account Instruct Cognito to either use its built-in functional or Amazon SES to send out emails. Allowed values: COGNITO_DEFAULT or DEVELOPER string "COGNITO_DEFAULT" no
email_configuration_from_email_address Sender’s email address or sender’s display name with their email address (e.g. john@example.com, John Smith <john@example.com> or "John Smith Ph.D." <john@example.com>). Escaped double quotes are required around display names that contain certain characters as specified in RFC 5322 string null no
email_configuration_reply_to_email_address The REPLY-TO email address string "" no
email_configuration_source_arn The ARN of the email source string "" no
email_verification_message A string representing the email verification message string null no
email_verification_subject A string representing the email verification subject string null no
enable_propagate_additional_user_context_data Enables the propagation of additional user context data bool false no
enabled Change to false to avoid deploying any resources bool true no
identity_providers Cognito Pool Identity Providers list(any) [] no
lambda_config A container for the AWS Lambda triggers associated with the user pool any {} no
lambda_config_create_auth_challenge The ARN of the lambda creating an authentication challenge. string null no
lambda_config_custom_email_sender A custom email sender AWS Lambda trigger. any {} no
lambda_config_custom_message A custom Message AWS Lambda trigger. string null no
lambda_config_custom_sms_sender A custom SMS sender AWS Lambda trigger. any {} no
lambda_config_define_auth_challenge Defines the authentication challenge. string null no
lambda_config_kms_key_id The Amazon Resource Name of Key Management Service Customer master keys. Amazon Cognito uses the key to encrypt codes and temporary passwords sent to CustomEmailSender and CustomSMSSender. string null no
lambda_config_post_authentication A post-authentication AWS Lambda trigger string null no
lambda_config_post_confirmation A post-confirmation AWS Lambda trigger string null no
lambda_config_pre_authentication A pre-authentication AWS Lambda trigger string null no
lambda_config_pre_sign_up A pre-registration AWS Lambda trigger string null no
lambda_config_pre_token_generation (deprecated) Allow to customize identity token claims before token generation string null no
lambda_config_pre_token_generation_config Allow to customize identity token claims before token generation any {} no
lambda_config_user_migration The user migration Lambda config type string null no
lambda_config_verify_auth_challenge_response Verifies the authentication challenge response string null no
mfa_configuration Set to enable multi-factor authentication. Must be one of the following values (ON, OFF, OPTIONAL) string "OFF" no
number_schemas A container with the number schema attributes of a user pool. Maximum of 50 attributes list(any) [] no
password_policy A container for information about the user pool password policy
object({
minimum_length = number,
require_lowercase = bool,
require_numbers = bool,
require_symbols = bool,
require_uppercase = bool,
temporary_password_validity_days = number
})
null no
password_policy_minimum_length The minimum length of the password policy that you have set number 8 no
password_policy_require_lowercase Whether you have required users to use at least one lowercase letter in their password bool true no
password_policy_require_numbers Whether you have required users to use at least one number in their password bool true no
password_policy_require_symbols Whether you have required users to use at least one symbol in their password bool true no
password_policy_require_uppercase Whether you have required users to use at least one uppercase letter in their password bool true no
password_policy_temporary_password_validity_days The minimum length of the password policy that you have set number 7 no
recovery_mechanisms The list of Account Recovery Options list(any) [] no
resource_server_identifier An identifier for the resource server string null no
resource_server_name A name for the resource server string null no
resource_server_scope_description The scope description string null no
resource_server_scope_name The scope name string null no
resource_servers A container with the user_groups definitions list(any) [] no
schemas A container with the schema attributes of a user pool. Maximum of 50 attributes list(any) [] no
sms_authentication_message A string representing the SMS authentication message string null no
sms_configuration The SMS Configuration map(any) {} no
sms_configuration_external_id The external ID used in IAM role trust relationships string "" no
sms_configuration_sns_caller_arn The ARN of the Amazon SNS caller. This is usually the IAM role that you've given Cognito permission to assume string "" no
sms_verification_message A string representing the SMS verification message string null no
software_token_mfa_configuration Configuration block for software token MFA (multifactor-auth). mfa_configuration must also be enabled for this to work map(any) {} no
software_token_mfa_configuration_enabled If true, and if mfa_configuration is also enabled, multi-factor authentication by software TOTP generator will be enabled bool false no
string_schemas A container with the string schema attributes of a user pool. Maximum of 50 attributes list(any) [] no
tags A mapping of tags to assign to the User Pool map(string) {} no
temporary_password_validity_days The user account expiration limit, in days, after which the account is no longer usable number 7 no
user_attribute_update_settings Configuration block for user attribute update settings. Must contain key attributes_require_verification_before_update with list with only valid values of email and phone_number map(list(string)) null no
user_group_description The description of the user group string null no
user_group_name The name of the user group string null no
user_group_precedence The precedence of the user group number null no
user_group_role_arn The ARN of the IAM role to be associated with the user group string null no
user_groups A container with the user_groups definitions list(any) [] no
user_pool_add_ons Configuration block for user pool add-ons to enable user pool advanced security mode features map(any) {} no
user_pool_add_ons_advanced_security_mode The mode for advanced security, must be one of OFF, AUDIT or ENFORCED string null no
user_pool_name The name of the user pool string n/a yes
username_attributes Specifies whether email addresses or phone numbers can be specified as usernames when a user signs up. Conflicts with alias_attributes list(string) null no
username_configuration The Username Configuration. Setting case_sensitive specifies whether username case sensitivity will be applied for all users in the user pool through Cognito APIs map(any) {} no
verification_message_template The verification message templates configuration map(any) {} no
verification_message_template_default_email_option The default email option. Must be either CONFIRM_WITH_CODE or CONFIRM_WITH_LINK. Defaults to CONFIRM_WITH_CODE string null no
verification_message_template_email_message_by_link The email message template for sending a confirmation link to the user, it must contain the {##Click Here##} placeholder string null no
verification_message_template_email_subject_by_link The subject line for the email message template for sending a confirmation link to the user string null no

Outputs

Name Description
arn The ARN of the user pool
client_ids The ids of the user pool clients
client_ids_map The ids map of the user pool clients
client_secrets The client secrets of the user pool clients
client_secrets_map The client secrets map of the user pool clients
creation_date The date the user pool was created
domain_app_version The app version
domain_aws_account_id The AWS account ID for the user pool owner
domain_cloudfront_distribution The name of the CloudFront distribution
domain_cloudfront_distribution_arn The ARN of the CloudFront distribution
domain_cloudfront_distribution_zone_id The ZoneID of the CloudFront distribution
domain_s3_bucket The S3 bucket where the static files for this domain are stored
endpoint The endpoint name of the user pool. Example format: cognito-idp.REGION.amazonaws.com/xxxx_yyyyy
id The id of the user pool
last_modified_date The date the user pool was last modified
name The name of the user pool
resource_servers_scope_identifiers A list of all scopes configured in the format identifier/scope_name

Know issues

Removing all lambda triggers

If you define lambda triggers using the lambda_config block or any lambda_config_* variable and you want to remove all triggers, define the lambda_config block with an empty map {} and apply the plan. Then comment the lambda_config block or define it as null and apply the plan again.

This is needed because all parameters for the lambda_config block are optional and keeping all block attributes empty or null forces to create a lambda_config {} block very time a plan/apply is run.

About

Terraform module to create Amazon Cognito User Pools, configure its attributes and resources such as app clients, domain, resource servers. Amazon Cognito User Pools provide a secure user directory that scales to hundreds of millions of users.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages