AWS Amazon RDS Instance
This page shows how to write Terraform and CloudFormation for Amazon RDS Instance and write them securely.
aws_db_instance (Terraform)
The Instance in Amazon RDS can be configured in Terraform with the resource name aws_db_instance
. The following sections describe 5 examples of how to use the resource and its parameters.
Example Usage from GitHub
resource "aws_db_instance" "mysql-default" {
engine = "mysql"
instance_class = "db.t3.large"
}
resource "aws_db_instance" "mysql-allocated-storage" {
resource "aws_db_instance" "mysql-default" {
engine = "mysql"
instance_class = "db.t3.large"
}
resource "aws_db_instance" "mysql-allocated-storage" {
resource "aws_db_instance" "d1" {
engine = "mysql"
instance_class = "db.t3.large"
}
resource "aws_db_instance" "d2" {
resource "aws_db_instance" "secureInstance" {
allocated_storage = 20
storage_type = "gp2"
engine = "mysql"
engine_version = "5.7"
instance_class = "db.t2.micro"
resource "aws_db_instance" "pass_main_db" {
count = 1
allocated_storage = 100
max_allocated_storage = 150
storage_type = "gp2"
engine = "mysql"
Security Best Practices for aws_db_instance
There are 4 settings in aws_db_instance that should be taken care of for security reasons. The following section explain an overview and example code.
Ensure backup retension of your RDS instance is specified
It's better to set it explicitly to reduce the risk of availability issues.
Ensure your RDS instance blocks unwanted access
It's better to limit accessibility to the minimum that is required for your application to work.
Ensure to enable Performance Insights of your RDS instance
It is better to Performance Insights of the RDS instance. The feature will help investigate the availability issues of the instance.
Ensure to enable storage encryption of your RDS instance
It is better to enable storage encryption of your RDS instance. Encryption reduces the risk of data leakage.
Parameters
-
address
optional computed - string -
allocated_storage
optional computed - number -
allow_major_version_upgrade
optional - bool -
apply_immediately
optional computed - bool -
arn
optional computed - string -
auto_minor_version_upgrade
optional - bool -
availability_zone
optional computed - string -
backup_retention_period
optional computed - number -
backup_window
optional computed - string -
ca_cert_identifier
optional computed - string -
character_set_name
optional computed - string -
copy_tags_to_snapshot
optional - bool -
db_subnet_group_name
optional computed - string -
delete_automated_backups
optional - bool -
deletion_protection
optional - bool -
domain
optional - string -
domain_iam_role_name
optional - string -
enabled_cloudwatch_logs_exports
optional - set of string -
endpoint
optional computed - string -
engine
optional computed - string -
engine_version
optional computed - string -
final_snapshot_identifier
optional - string -
hosted_zone_id
optional computed - string -
iam_database_authentication_enabled
optional - bool -
id
optional computed - string -
identifier
optional computed - string -
identifier_prefix
optional computed - string -
instance_class
required - string -
iops
optional - number -
kms_key_id
optional computed - string -
latest_restorable_time
optional computed - string -
license_model
optional computed - string -
maintenance_window
optional computed - string -
max_allocated_storage
optional - number -
monitoring_interval
optional - number -
monitoring_role_arn
optional computed - string -
multi_az
optional computed - bool -
name
optional computed - string -
option_group_name
optional computed - string -
parameter_group_name
optional computed - string -
password
optional - string -
performance_insights_enabled
optional - bool -
performance_insights_kms_key_id
optional computed - string -
performance_insights_retention_period
optional computed - number -
port
optional computed - number -
publicly_accessible
optional - bool -
replicas
optional computed - list of string -
replicate_source_db
optional - string -
resource_id
optional computed - string -
security_group_names
optional - set of string -
skip_final_snapshot
optional - bool -
snapshot_identifier
optional computed - string -
status
optional computed - string -
storage_encrypted
optional - bool -
storage_type
optional computed - string -
tags
optional - map from string to string -
timezone
optional computed - string -
username
optional computed - string -
vpc_security_group_ids
optional computed - set of string -
restore_to_point_in_time
list block-
restore_time
optional - string -
source_db_instance_identifier
optional - string -
source_dbi_resource_id
optional - string -
use_latest_restorable_time
optional - bool
-
-
s3_import
list block-
bucket_name
required - string -
bucket_prefix
optional - string -
ingestion_role
required - string -
source_engine
required - string -
source_engine_version
required - string
-
-
timeouts
single block
Explanation in Terraform Registry
Provides an RDS instance resource. A DB instance is an isolated database environment in the cloud. A DB instance can contain multiple user-created databases. Changes to a DB instance can occur when you manually change a parameter, such as
allocated_storage
, and are reflected in the next maintenance window. Because of this, Terraform may report a difference in its planning phase because a modification has not yet taken place. You can use theapply_immediately
flag to instruct the service to apply the change immediately (see documentation below). When upgrading the major version of an engine,allow_major_version_upgrade
must be set totrue
.Note: using
apply_immediately
can result in a brief downtime as the server reboots. See the AWS Docs on [RDS Maintenance][2] for more information. Note: All arguments including the username and password will be stored in the raw state as plain-text. Read more about sensitive data in state. > Hands-on: Try the Manage AWS RDS Instances tutorial on HashiCorp Learn.
Tips: Best Practices for The Other AWS Amazon RDS Resources
In addition to the aws_rds_cluster, AWS Amazon RDS has the other resources that should be configured for security reasons. Please check some examples of those resources and precautions.
aws_rds_cluster
Ensure backup retension of your RDS cluster is specified
It's better to set it explicitly to reduce the risk of availability issues.
aws_rds_cluster_instance
Ensure your RDS cluster instance blocks unwanted access
It's better to limit accessibily to the minimum that is required for the application to work.
AWS::RDS::DBInstance (CloudFormation)
The DBInstance in RDS can be configured in CloudFormation with the resource name AWS::RDS::DBInstance
. The following sections describe 10 examples of how to use the resource and its parameters.
Example Usage from GitHub
Type: AWS::RDS::DBInstance
Properties:
DeletionProtection: !If [IsProd, true, false]
PubliclyAccessible: true # change depending on bastion config
EnablePerformanceInsights: true
Engine: Postgres
Type: AWS::RDS::DBInstance
Properties:
DeletionProtection: !If [IsProd, true, false]
PubliclyAccessible: true # change depending on bastion config
EnablePerformanceInsights: true
Engine: Postgres
Type: AWS::RDS::DBInstance
Properties:
DeletionProtection: !If [IsProd, true, false]
PubliclyAccessible: true # change depending on bastion config
EnablePerformanceInsights: true
Engine: Postgres
Type: AWS::RDS::DBInstance
Properties:
DBSecurityGroups: [!Ref 'MyDbSecurityByEC2SecurityGroup', !Ref 'MyDbSecurityByCIDRIPGroup']
AllocatedStorage: '5'
DBInstanceClass: db.m1.small
Engine: MySQL
Type: AWS::RDS::DBInstance
Properties:
Engine: aurora
PubliclyAccessible: 'false'
DBInstanceClass: db.r4.large
DBClusterIdentifier:
"Type": "AWS::RDS::DBInstance",
"Properties": {
"StorageEncrypted": true
}
},
"SensitiveDBInstance": {
"Type": "AWS::RDS::DBInstance",
"Properties": {
"SourceDBInstanceIdentifier": { "Ref": "MasterDBIdentifier" },
"DBInstanceClass": { "Ref": "RdsInstanceType" },
"DBInstanceIdentifier":
{
"Type": "AWS::RDS::DBInstance",
"Properties": {
"SourceDBInstanceIdentifier": "sampleDbInstance",
"MasterUserPassword": {
"Ref": "Password"
}
"path": "/ResourceTypes/AWS::RDS::DBInstance/Properties/BackupRetentionPeriod/Value",
"value": {
"ValueType": "AWS::RDS::DBInstance.BackupRetentionPeriod"
}
},
{
"path": "/ResourceTypes/AWS::RDS::DBInstance/Properties/BackupRetentionPeriod/Value",
"value": {
"ValueType": "AWS::RDS::DBInstance.BackupRetentionPeriod"
}
},
{
Parameters
-
AllocatedStorage
optional - String -
AllowMajorVersionUpgrade
optional - Boolean -
AssociatedRoles
optional - List of DBInstanceRole -
AutoMinorVersionUpgrade
optional - Boolean -
AvailabilityZone
optional - String -
BackupRetentionPeriod
optional - Integer -
CACertificateIdentifier
optional - String -
CharacterSetName
optional - String -
CopyTagsToSnapshot
optional - Boolean -
DBClusterIdentifier
optional - String -
DBInstanceClass
required - String -
DBInstanceIdentifier
optional - String -
DBName
optional - String -
DBParameterGroupName
optional - String -
DBSecurityGroups
optional - List -
DBSnapshotIdentifier
optional - String -
DBSubnetGroupName
optional - String -
DeleteAutomatedBackups
optional - Boolean -
DeletionProtection
optional - Boolean -
Domain
optional - String -
DomainIAMRoleName
optional - String -
EnableCloudwatchLogsExports
optional - List -
EnableIAMDatabaseAuthentication
optional - Boolean -
EnablePerformanceInsights
optional - Boolean -
Engine
optional - String -
EngineVersion
optional - String -
Iops
optional - Integer -
KmsKeyId
optional - String -
LicenseModel
optional - String -
MasterUserPassword
optional - String -
MasterUsername
optional - String -
MaxAllocatedStorage
optional - Integer -
MonitoringInterval
optional - Integer -
MonitoringRoleArn
optional - String -
MultiAZ
optional - Boolean -
OptionGroupName
optional - String -
PerformanceInsightsKMSKeyId
optional - String -
PerformanceInsightsRetentionPeriod
optional - Integer -
Port
optional - String -
PreferredBackupWindow
optional - String -
PreferredMaintenanceWindow
optional - String -
ProcessorFeatures
optional - List of ProcessorFeature -
PromotionTier
optional - Integer -
PubliclyAccessible
optional - Boolean -
SourceDBInstanceIdentifier
optional - String -
SourceRegion
optional - String -
StorageEncrypted
optional - Boolean -
StorageType
optional - String -
Tags
optional - List of Tag -
Timezone
optional - String -
UseDefaultProcessorFeatures
optional - Boolean -
VPCSecurityGroups
optional - List
Explanation in CloudFormation Registry
The
AWS::RDS::DBInstance
resource creates an Amazon RDS DB instance.If you import an existing DB instance, and the template configuration doesn't match the actual configuration of the DB instance, AWS CloudFormation applies the changes in the template during the import operation.
Important If a DB instance is deleted or replaced during an update, AWS CloudFormation deletes all automated snapshots. However, it retains manual DB snapshots. During an update that requires replacement, you can apply a stack policy to prevent DB instances from being replaced. For more information, see Prevent Updates to Stack Resources.
Updating DB instancesWhen properties labeled "Update requires: Replacement" are updated, AWS CloudFormation first creates a replacement DB instance, then changes references from other dependent resources to point to the replacement DB instance, and finally deletes the old DB instance.
Important We highly recommend that you take a snapshot of the database before updating the stack. If you don't, you lose the data when AWS CloudFormation replaces your DB instance. To preserve your data, perform the following procedure: Deactivate any applications that are using the DB instance so that there's no activity on the DB instance.
Create a snapshot of the DB instance. For more information about creating DB snapshots, see Creating a DB Snapshot.
If you want to restore your instance using a DB snapshot, modify the updated template with your DB instance changes and add the
DBSnapshotIdentifier
property with the ID of the DB snapshot that you want to use. After you restore a DB instance with aDBSnapshotIdentifier
property, you must specify the sameDBSnapshotIdentifier
property for any future updates to the DB instance. When you specify this property for an update, the DB instance is not restored from the DB snapshot again, and the data in the database is not changed. However, if you don't specify theDBSnapshotIdentifier
property, an empty DB instance is created, and the original DB instance is deleted. If you specify a property that is different from the previous snapshot restore property, a new DB instance is restored from the specifiedDBSnapshotIdentifier
property, and the original DB instance is deleted.Update the stack.
For more information about updating other properties of this resource, see
[ModifyDBInstance](https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_ModifyDBInstance.html)
. For more information about updating stacks, see AWS CloudFormation Stacks Updates.Deleting DB instancesFor DB instances that are part of an Aurora DB cluster, you can set a deletion policy for your DB instance to control how AWS CloudFormation handles the DB instance when the stack is deleted. For Amazon RDS DB instances, you can choose to retain the DB instance, to delete the DB instance, or to create a snapshot of the DB instance. The default AWS CloudFormation behavior depends on the
DBClusterIdentifier
property:1. ForAWS::RDS::DBInstance
resources that don't specify theDBClusterIdentifier
property, AWS CloudFormation saves a snapshot of the DB instance.
- For
AWS::RDS::DBInstance
resources that do specify theDBClusterIdentifier
property, AWS CloudFormation deletes the DB instance. For more information, see DeletionPolicy Attribute.
Frequently asked questions
What is AWS Amazon RDS Instance?
AWS Amazon RDS Instance is a resource for Amazon RDS of Amazon Web Service. Settings can be wrote in Terraform and CloudFormation.
Where can I find the example code for the AWS Amazon RDS Instance?
For Terraform, the gilyas/infracost, infracost/infracost and terraform-aws-modules/terraform-aws-pricing source code examples are useful. See the Terraform Example section for further details.
For CloudFormation, the ProbablyNextTime/db_labs, jetbridge/sls-flask and Svjard/ephemeris source code examples are useful. See the CloudFormation Example section for further details.