Skip to main content

Module: rds-cluster

Terraform module to provision an RDS Aurora cluster for MySQL or Postgres.

Supports Amazon Aurora Serverless.

Usage

For a complete example, see examples/complete.

For automated tests of the complete example using bats and Terratest (which tests and deploys the example on AWS), see test.

Basic example

module "rds_cluster_aurora_postgres" {
source = "cloudposse/rds-cluster/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"

name = "postgres"
engine = "aurora-postgresql"
cluster_family = "aurora-postgresql9.6"
# 1 writer, 1 reader
cluster_size = 2
# 1 writer, 3 reader
# cluster_size = 4
# 1 writer, 5 reader
# cluster_size = 6
namespace = "eg"
stage = "dev"
admin_user = "admin1"
admin_password = "Test123456789"
db_name = "dbname"
db_port = 5432
instance_type = "db.r4.large"
vpc_id = "vpc-xxxxxxxx"
security_groups = ["sg-xxxxxxxx"]
subnets = ["subnet-xxxxxxxx", "subnet-xxxxxxxx"]
zone_id = "Zxxxxxxxx"
}

Serverless Aurora MySQL 5.6

module "rds_cluster_aurora_mysql_serverless" {
source = "cloudposse/rds-cluster/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
namespace = "eg"
stage = "dev"
name = "db"
engine = "aurora"
engine_mode = "serverless"
cluster_family = "aurora5.6"
cluster_size = 0
admin_user = "admin1"
admin_password = "Test123456789"
db_name = "dbname"
db_port = 3306
instance_type = "db.t2.small"
vpc_id = "vpc-xxxxxxxx"
security_groups = ["sg-xxxxxxxx"]
subnets = ["subnet-xxxxxxxx", "subnet-xxxxxxxx"]
zone_id = "Zxxxxxxxx"
enable_http_endpoint = true

scaling_configuration = [
{
auto_pause = true
max_capacity = 256
min_capacity = 2
seconds_until_auto_pause = 300
}
]
}

Serverless Aurora 2.07.1 MySQL 5.7

module "rds_cluster_aurora_mysql_serverless" {
source = "cloudposse/rds-cluster/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
namespace = "eg"
stage = "dev"
name = "db"
engine = "aurora-mysql"
engine_mode = "serverless"
engine_version = "5.7.mysql_aurora.2.07.1"
cluster_family = "aurora-mysql5.7"
cluster_size = 0
admin_user = "admin1"
admin_password = "Test123456789"
db_name = "dbname"
db_port = 3306
vpc_id = "vpc-xxxxxxxx"
security_groups = ["sg-xxxxxxxx"]
subnets = ["subnet-xxxxxxxx", "subnet-xxxxxxxx"]
zone_id = "Zxxxxxxxx"
enable_http_endpoint = true

scaling_configuration = [
{
auto_pause = true
max_capacity = 16
min_capacity = 1
seconds_until_auto_pause = 300
timeout_action = "ForceApplyCapacityChange"
}
]
}

With cluster parameters

module "rds_cluster_aurora_mysql" {
source = "cloudposse/rds-cluster/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
engine = "aurora"
cluster_family = "aurora-mysql5.7"
cluster_size = 2
namespace = "eg"
stage = "dev"
name = "db"
admin_user = "admin1"
admin_password = "Test123456789"
db_name = "dbname"
instance_type = "db.t2.small"
vpc_id = "vpc-xxxxxxx"
security_groups = ["sg-xxxxxxxx"]
subnets = ["subnet-xxxxxxxx", "subnet-xxxxxxxx"]
zone_id = "Zxxxxxxxx"

cluster_parameters = [
{
name = "character_set_client"
value = "utf8"
},
{
name = "character_set_connection"
value = "utf8"
},
{
name = "character_set_database"
value = "utf8"
},
{
name = "character_set_results"
value = "utf8"
},
{
name = "character_set_server"
value = "utf8"
},
{
name = "collation_connection"
value = "utf8_bin"
},
{
name = "collation_server"
value = "utf8_bin"
},
{
name = "lower_case_table_names"
value = "1"
apply_method = "pending-reboot"
},
{
name = "skip-character-set-client-handshake"
value = "1"
apply_method = "pending-reboot"
}
]
}

With enhanced monitoring

# create IAM role for monitoring
resource "aws_iam_role" "enhanced_monitoring" {
name = "rds-cluster-example-1"
assume_role_policy = data.aws_iam_policy_document.enhanced_monitoring.json
}

# Attach Amazon's managed policy for RDS enhanced monitoring
resource "aws_iam_role_policy_attachment" "enhanced_monitoring" {
role = aws_iam_role.enhanced_monitoring.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonRDSEnhancedMonitoringRole"
}

# allow rds to assume this role
data "aws_iam_policy_document" "enhanced_monitoring" {
statement {
actions = [
"sts:AssumeRole",
]

effect = "Allow"

principals {
type = "Service"
identifiers = ["monitoring.rds.amazonaws.com"]
}
}
}

module "rds_cluster_aurora_postgres" {
source = "cloudposse/rds-cluster/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
engine = "aurora-postgresql"
cluster_family = "aurora-postgresql9.6"
cluster_size = 2
namespace = "eg"
stage = "dev"
name = "db"
admin_user = "admin1"
admin_password = "Test123456789"
db_name = "dbname"
db_port = 5432
instance_type = "db.r4.large"
vpc_id = "vpc-xxxxxxx"
security_groups = ["sg-xxxxxxxx"]
subnets = ["subnet-xxxxxxxx", "subnet-xxxxxxxx"]
zone_id = "Zxxxxxxxx"

# enable monitoring every 30 seconds
rds_monitoring_interval = 30

# reference iam role created above
rds_monitoring_role_arn = aws_iam_role.enhanced_monitoring.arn
}

Examples

Review the complete example to see how to use this module.

Variables

Required Variables

subnets (list(string)) required

List of VPC subnet IDs

vpc_id (string) required

VPC ID to create the cluster in (e.g. vpc-a22222ee)

Optional Variables

activity_stream_enabled (bool) optional

Whether to enable Activity Streams


Default value: false

activity_stream_kms_key_id (string) optional

The ARN for the KMS key to encrypt Activity Stream Data data. When specifying activity_stream_kms_key_id, activity_stream_enabled needs to be set to true


Default value: ""

activity_stream_mode (string) optional

The mode for the Activity Streams. async and sync are supported. Defaults to async


Default value: "async"

admin_password (string) optional

Password for the master DB user. Ignored if snapshot_identifier or replication_source_identifier is provided


Default value: ""

admin_user (string) optional

Username for the master DB user. Ignored if snapshot_identifier or replication_source_identifier is provided


Default value: "admin"

admin_user_secret_kms_key_id (string) optional

Amazon Web Services KMS key identifier is the key ARN, key ID, alias ARN, or alias name for the KMS key.
To use a KMS key in a different Amazon Web Services account, specify the key ARN or alias ARN.
If not specified, the default KMS key for your Amazon Web Services account is used.



Default value: null

allocated_storage (number) optional

The allocated storage in GBs


Default value: null

allow_major_version_upgrade (bool) optional

Enable to allow major engine version upgrades when changing engine versions. Defaults to false.


Default value: false

allowed_cidr_blocks (list(string)) optional

List of CIDR blocks allowed to access the cluster


Default value: [ ]

allowed_ipv6_cidr_blocks (list(string)) optional

List of IPv6 CIDR blocks allowed to access the cluster


Default value: [ ]

apply_immediately (bool) optional

Specifies whether any cluster modifications are applied immediately, or during the next maintenance window


Default value: true

auto_minor_version_upgrade (bool) optional

Indicates that minor engine upgrades will be applied automatically to the DB instance during the maintenance window


Default value: true

autoscaling_enabled (bool) optional

Whether to enable cluster autoscaling


Default value: false

autoscaling_max_capacity (number) optional

Maximum number of instances to be maintained by the autoscaler


Default value: 5

autoscaling_min_capacity (number) optional

Minimum number of instances to be maintained by the autoscaler


Default value: 1

autoscaling_policy_type (string) optional

Autoscaling policy type. TargetTrackingScaling and StepScaling are supported


Default value: "TargetTrackingScaling"

autoscaling_scale_in_cooldown (number) optional

The amount of time, in seconds, after a scaling activity completes and before the next scaling down activity can start. Default is 300s


Default value: 300

autoscaling_scale_out_cooldown (number) optional

The amount of time, in seconds, after a scaling activity completes and before the next scaling up activity can start. Default is 300s


Default value: 300

autoscaling_target_metrics (string) optional

The metrics type to use. If this value isn't provided the default is CPU utilization


Default value: "RDSReaderAverageCPUUtilization"

autoscaling_target_value (number) optional

The target value to scale with respect to target metrics


Default value: 75

backtrack_window (number) optional

The target backtrack window, in seconds. Only available for aurora engine currently. Must be between 0 and 259200 (72 hours)


Default value: 0

backup_window (string) optional

Daily time range during which the backups happen


Default value: "07:00-09:00"

ca_cert_identifier (string) optional

The identifier of the CA certificate for the DB instance


Default value: null

cluster_dns_name (string) optional

Name of the cluster CNAME record to create in the parent DNS zone specified by zone_id. If left empty, the name will be auto-asigned using the format master.var.name


Default value: ""

cluster_family (string) optional

The family of the DB cluster parameter group


Default value: "aurora5.6"

cluster_identifier (string) optional

The RDS Cluster Identifier. Will use generated label ID if not supplied


Default value: ""

cluster_parameters optional

List of DB cluster parameters to apply


Type:

list(object({
apply_method = string
name = string
value = string
}))

Default value: [ ]

cluster_size (number) optional

Number of DB instances to create in the cluster


Default value: 2

cluster_type (string) optional

Either regional or global.
If regional will be created as a normal, standalone DB.
If global, will be made part of a Global cluster (requires global_cluster_identifier).



Default value: "regional"

copy_tags_to_snapshot (bool) optional

Copy tags to backup snapshots


Default value: false

db_cluster_instance_class (string) optional

This setting is required to create a provisioned Multi-AZ DB cluster


Default value: null

db_name (string) optional

Database name (default is not to create a database)


Default value: ""

db_port (number) optional

Database port


Default value: 3306

deletion_protection (bool) optional

If the DB instance should have deletion protection enabled


Default value: false

egress_enabled (bool) optional

Whether or not to apply the egress security group rule to default security group, defaults to true


Default value: true

enable_global_write_forwarding (bool) optional

Set to true, to forward writes to an associated global cluster.


Default value: false

enable_http_endpoint (bool) optional

Enable HTTP endpoint (data API). Only valid when engine_mode is set to serverless


Default value: false

enabled_cloudwatch_logs_exports (list(string)) optional

List of log types to export to cloudwatch. The following log types are supported: audit, error, general, slowquery


Default value: [ ]

engine (string) optional

The name of the database engine to be used for this DB cluster. Valid values: aurora, aurora-mysql, aurora-postgresql


Default value: "aurora"

engine_mode (string) optional

The database engine mode. Valid values: parallelquery, provisioned, serverless


Default value: "provisioned"

engine_version (string) optional

The version of the database engine to use. See aws rds describe-db-engine-versions


Default value: ""

enhanced_monitoring_attributes (list(string)) optional

The attributes for the enhanced monitoring IAM role


Default value:

[
"enhanced-monitoring"
]
enhanced_monitoring_role_enabled (bool) optional

A boolean flag to enable/disable the creation of the enhanced monitoring IAM role. If set to false, the module will not create a new role and will use rds_monitoring_role_arn for enhanced monitoring


Default value: false

global_cluster_identifier (string) optional

ID of the Aurora global cluster


Default value: ""

iam_database_authentication_enabled (bool) optional

Specifies whether or mappings of AWS Identity and Access Management (IAM) accounts to database accounts is enabled


Default value: false

iam_roles (list(string)) optional

Iam roles for the Aurora cluster


Default value: [ ]

instance_availability_zone (string) optional

Optional parameter to place cluster instances in a specific availability zone. If left empty, will place randomly


Default value: ""

instance_parameters optional

List of DB instance parameters to apply


Type:

list(object({
apply_method = string
name = string
value = string
}))

Default value: [ ]

instance_type (string) optional

Instance type to use


Default value: "db.t2.small"

intra_security_group_traffic_enabled (bool) optional

Whether to allow traffic between resources inside the database's security group.


Default value: false

iops (number) optional

The amount of provisioned IOPS. Setting this implies a storage_type of 'io1'. This setting is required to create a Multi-AZ DB cluster. Check TF docs for values based on db engine


Default value: null

kms_key_arn (string) optional

The ARN for the KMS encryption key. When specifying kms_key_arn, storage_encrypted needs to be set to true


Default value: ""

maintenance_window (string) optional

Weekly time range during which system maintenance can occur, in UTC


Default value: "wed:03:00-wed:04:00"

manage_admin_user_password (bool) optional

Set to true to allow RDS to manage the master user password in Secrets Manager. Cannot be set if master_password is provided


Default value: false

network_type (string) optional

The network type of the cluster. Valid values: IPV4, DUAL.


Default value: "IPV4"

parameter_group_name_prefix_enabled (bool) optional

Set to true to use name_prefix to name the cluster and database parameter groups. Set to false to use name instead


Default value: true

performance_insights_enabled (bool) optional

Whether to enable Performance Insights


Default value: false

performance_insights_kms_key_id (string) optional

The ARN for the KMS key to encrypt Performance Insights data. When specifying performance_insights_kms_key_id, performance_insights_enabled needs to be set to true


Default value: ""

performance_insights_retention_period (number) optional

Amount of time in days to retain Performance Insights data. Either 7 (7 days) or 731 (2 years)


Default value: null

publicly_accessible (bool) optional

Set to true if you want your cluster to be publicly accessible (such as via QuickSight)


Default value: false

rds_monitoring_interval (number) optional

The interval, in seconds, between points when enhanced monitoring metrics are collected for the DB instance. To disable collecting Enhanced Monitoring metrics, specify 0. The default is 0. Valid Values: 0, 1, 5, 10, 15, 30, 60


Default value: 0

rds_monitoring_role_arn (string) optional

The ARN for the IAM role that permits RDS to send enhanced monitoring metrics to CloudWatch Logs


Default value: null

rds_ri_duration (number) optional

The number of years to reserve the instance. Values can be 1 or 3 (or in seconds, 31536000 or 94608000)


Default value: 1

rds_ri_offering_type (string) optional

Offering type of reserved DB instances. Valid values are 'No Upfront', 'Partial Upfront', 'All Upfront'.


Default value: ""

reader_dns_name (string) optional

Name of the reader endpoint CNAME record to create in the parent DNS zone specified by zone_id. If left empty, the name will be auto-asigned using the format replicas.var.name


Default value: ""

replication_source_identifier (string) optional

ARN of a source DB cluster or DB instance if this DB cluster is to be created as a Read Replica


Default value: ""

restore_to_point_in_time optional

List of point-in-time recovery options. Valid parameters are:


source_cluster_identifier
Identifier of the source database cluster from which to restore.
restore_type:
Type of restore to be performed. Valid options are "full-copy" and "copy-on-write".
use_latest_restorable_time:
Set to true to restore the database cluster to the latest restorable backup time. Conflicts with restore_to_time.
restore_to_time:
Date and time in UTC format to restore the database cluster to. Conflicts with use_latest_restorable_time.



Type:

list(object({
source_cluster_identifier = string
restore_type = optional(string, "copy-on-write")
use_latest_restorable_time = optional(bool, true)
restore_to_time = optional(string, null)
}))

Default value: [ ]

retention_period (number) optional

Number of days to retain backups for


Default value: 5

s3_import optional

Restore from a Percona Xtrabackup in S3. The bucket_name is required to be in the same region as the resource.


Type:

object({
bucket_name = string
bucket_prefix = string
ingestion_role = string
source_engine = string
source_engine_version = string
})

Default value: null

scaling_configuration optional

List of nested attributes with scaling properties. Only valid when engine_mode is set to serverless


Type:

list(object({
auto_pause = bool
max_capacity = number
min_capacity = number
seconds_until_auto_pause = number
timeout_action = string
}))

Default value: [ ]

security_groups (list(string)) optional

List of security groups to be allowed to connect to the DB instance


Default value: [ ]

serverlessv2_scaling_configuration optional

serverlessv2 scaling properties


Type:

object({
min_capacity = number
max_capacity = number
})

Default value: null

skip_final_snapshot (bool) optional

Determines whether a final DB snapshot is created before the DB cluster is deleted


Default value: true

snapshot_identifier (string) optional

Specifies whether or not to create this cluster from a snapshot


Default value: null

source_region (string) optional

Source Region of primary cluster, needed when using encrypted storage and region replicas


Default value: ""

storage_encrypted (bool) optional

Specifies whether the DB cluster is encrypted. The default is false for provisioned engine_mode and true for serverless engine_mode


Default value: false

storage_type (string) optional

One of 'standard' (magnetic), 'gp2' (general purpose SSD), 'io1' (provisioned IOPS SSD), 'aurora', or 'aurora-iopt1'


Default value: null

subnet_group_name (string) optional

Database subnet group name. Will use generated label ID if not supplied.


Default value: ""

timeouts_configuration optional

List of timeout values per action. Only valid actions are create, update and delete


Type:

list(object({
create = string
update = string
delete = string
}))

Default value: [ ]

use_reserved_instances (bool) optional

WARNING: Observe your plans and applies carefully when using this feature.
It has potential to be very expensive if not used correctly.


Whether to use reserved instances.



Default value: false

vpc_security_group_ids (list(string)) optional

Additional security group IDs to apply to the cluster, in addition to the provisioned default security group with ingress traffic from existing CIDR blocks and existing security groups


Default value: [ ]

zone_id (any) optional

Route53 DNS Zone ID as list of string (0 or 1 items). If empty, no custom DNS name will be published.
If the list contains a single Zone ID, a custom DNS name will be pulished in that zone.
Can also be a plain string, but that use is DEPRECATED because of Terraform issues.



Default value: [ ]

Context Variables

The following variables are defined in the context.tf file of this module and part of the terraform-null-label pattern.

additional_tag_map (map(string)) optional

Additional key-value pairs to add to each map in tags_as_list_of_maps. Not added to tags or id.
This is for some rare cases where resources want additional configuration of tags
and therefore take a list of maps with tag key, value, and additional configuration.


Required: No

Default value: { }

attributes (list(string)) optional

ID element. Additional attributes (e.g. workers or cluster) to add to id,
in the order they appear in the list. New attributes are appended to the
end of the list. The elements of the list are joined by the delimiter
and treated as a single ID element.


Required: No

Default value: [ ]

context (any) optional

Single object for setting entire context at once.
See description of individual variables for details.
Leave string and numeric variables as null to use default value.
Individual variable settings (non-null) override settings in context object,
except for attributes, tags, and additional_tag_map, which are merged.


Required: No

Default value:

{
"additional_tag_map": {},
"attributes": [],
"delimiter": null,
"descriptor_formats": {},
"enabled": true,
"environment": null,
"id_length_limit": null,
"label_key_case": null,
"label_order": [],
"label_value_case": null,
"labels_as_tags": [
"unset"
],
"name": null,
"namespace": null,
"regex_replace_chars": null,
"stage": null,
"tags": {},
"tenant": null
}
delimiter (string) optional

Delimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.


Required: No

Default value: null

descriptor_formats (any) optional

Describe additional descriptors to be output in the descriptors output map.
Map of maps. Keys are names of descriptors. Values are maps of the form
\{<br/> format = string<br/> labels = list(string)<br/> \}
(Type is any so the map values can later be enhanced to provide additional options.)
format is a Terraform format string to be passed to the format() function.
labels is a list of labels, in order, to pass to format() function.
Label values will be normalized before being passed to format() so they will be
identical to how they appear in id.
Default is {} (descriptors output will be empty).


Required: No

Default value: { }

enabled (bool) optional

Set to false to prevent the module from creating any resources
Required: No

Default value: null

environment (string) optional

ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'
Required: No

Default value: null

id_length_limit (number) optional

Limit id to this many characters (minimum 6).
Set to 0 for unlimited length.
Set to null for keep the existing setting, which defaults to 0.
Does not affect id_full.


Required: No

Default value: null

label_key_case (string) optional

Controls the letter case of the tags keys (label names) for tags generated by this module.
Does not affect keys of tags passed in via the tags input.
Possible values: lower, title, upper.
Default value: title.


Required: No

Default value: null

label_order (list(string)) optional

The order in which the labels (ID elements) appear in the id.
Defaults to ["namespace", "environment", "stage", "name", "attributes"].
You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present.


Required: No

Default value: null

label_value_case (string) optional

Controls the letter case of ID elements (labels) as included in id,
set as tag values, and output by this module individually.
Does not affect values of tags passed in via the tags input.
Possible values: lower, title, upper and none (no transformation).
Set this to title and set delimiter to "" to yield Pascal Case IDs.
Default value: lower.


Required: No

Default value: null

labels_as_tags (set(string)) optional

Set of labels (ID elements) to include as tags in the tags output.
Default is to include all labels.
Tags with empty values will not be included in the tags output.
Set to [] to suppress all generated tags.
Notes:
The value of the name tag, if included, will be the id, not the name.
Unlike other null-label inputs, the initial setting of labels_as_tags cannot be
changed in later chained modules. Attempts to change it will be silently ignored.


Required: No

Default value:

[
"default"
]
name (string) optional

ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.
This is the only ID element not also included as a tag.
The "name" tag is set to the full id string. There is no tag with the value of the name input.


Required: No

Default value: null

namespace (string) optional

ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique
Required: No

Default value: null

regex_replace_chars (string) optional

Terraform regular expression (regex) string.
Characters matching the regex will be removed from the ID elements.
If not set, "/[^a-zA-Z0-9-]/" is used to remove all characters other than hyphens, letters and digits.


Required: No

Default value: null

stage (string) optional

ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'
Required: No

Default value: null

tags (map(string)) optional

Additional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.


Required: No

Default value: { }

tenant (string) optional

ID element (Rarely used, not included by default). A customer identifier, indicating who this instance of a resource is for
Required: No

Default value: null

Outputs

activity_stream_arn

Activity Stream ARN

activity_stream_name

Activity Stream Name

arn

Amazon Resource Name (ARN) of the cluster

cluster_identifier

Cluster Identifier

cluster_resource_id

The region-unique, immutable identifie of the cluster

cluster_security_groups

Default RDS cluster security groups

database_name

Database name

dbi_resource_ids

List of the region-unique, immutable identifiers for the DB instances in the cluster

endpoint

The DNS address of the RDS instance

instance_endpoints

List of DNS addresses for the DB instances in the cluster

master_host

DB Master hostname

master_username

Username for the master DB user

reader_endpoint

A read-only endpoint for the Aurora cluster, automatically load-balanced across replicas

replicas_host

Replicas hostname

reserved_instance

All information about the reserved instance(s) if created.

security_group_arn

Security Group ARN

security_group_id

Security Group ID

security_group_name

Security Group name

Dependencies

Requirements

  • terraform, version: >= 1.0.0
  • aws, version: >= 4.23.0
  • null, version: >= 2.0
  • random, version: >= 2.0

Providers

  • aws, version: >= 4.23.0
  • random, version: >= 2.0

Modules

NameVersionSourceDescription
dns_master0.12.2cloudposse/route53-cluster-hostname/awsn/a
dns_replicas0.12.2cloudposse/route53-cluster-hostname/awsn/a
enhanced_monitoring_label0.25.0cloudposse/label/nulln/a
rds_identifier0.25.0cloudposse/label/nulln/a
this0.25.0cloudposse/label/nulln/a

Resources

The following resources are used by this module:

Data Sources

The following data sources are used by this module: