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
-
addressoptional computed - string -
allocated_storageoptional computed - number -
allow_major_version_upgradeoptional - bool -
apply_immediatelyoptional computed - bool -
arnoptional computed - string -
auto_minor_version_upgradeoptional - bool -
availability_zoneoptional computed - string -
backup_retention_periodoptional computed - number -
backup_windowoptional computed - string -
ca_cert_identifieroptional computed - string -
character_set_nameoptional computed - string -
copy_tags_to_snapshotoptional - bool -
db_subnet_group_nameoptional computed - string -
delete_automated_backupsoptional - bool -
deletion_protectionoptional - bool -
domainoptional - string -
domain_iam_role_nameoptional - string -
enabled_cloudwatch_logs_exportsoptional - set of string -
endpointoptional computed - string -
engineoptional computed - string -
engine_versionoptional computed - string -
final_snapshot_identifieroptional - string -
hosted_zone_idoptional computed - string -
iam_database_authentication_enabledoptional - bool -
idoptional computed - string -
identifieroptional computed - string -
identifier_prefixoptional computed - string -
instance_classrequired - string -
iopsoptional - number -
kms_key_idoptional computed - string -
latest_restorable_timeoptional computed - string -
license_modeloptional computed - string -
maintenance_windowoptional computed - string -
max_allocated_storageoptional - number -
monitoring_intervaloptional - number -
monitoring_role_arnoptional computed - string -
multi_azoptional computed - bool -
nameoptional computed - string -
option_group_nameoptional computed - string -
parameter_group_nameoptional computed - string -
passwordoptional - string -
performance_insights_enabledoptional - bool -
performance_insights_kms_key_idoptional computed - string -
performance_insights_retention_periodoptional computed - number -
portoptional computed - number -
publicly_accessibleoptional - bool -
replicasoptional computed - list of string -
replicate_source_dboptional - string -
resource_idoptional computed - string -
security_group_namesoptional - set of string -
skip_final_snapshotoptional - bool -
snapshot_identifieroptional computed - string -
statusoptional computed - string -
storage_encryptedoptional - bool -
storage_typeoptional computed - string -
tagsoptional - map from string to string -
timezoneoptional computed - string -
usernameoptional computed - string -
vpc_security_group_idsoptional computed - set of string -
restore_to_point_in_timelist block-
restore_timeoptional - string -
source_db_instance_identifieroptional - string -
source_dbi_resource_idoptional - string -
use_latest_restorable_timeoptional - bool
-
-
s3_importlist block-
bucket_namerequired - string -
bucket_prefixoptional - string -
ingestion_rolerequired - string -
source_enginerequired - string -
source_engine_versionrequired - string
-
-
timeoutssingle 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_immediatelyflag to instruct the service to apply the change immediately (see documentation below). When upgrading the major version of an engine,allow_major_version_upgrademust be set totrue.Note: using
apply_immediatelycan 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
-
AllocatedStorageoptional - String -
AllowMajorVersionUpgradeoptional - Boolean -
AssociatedRolesoptional - List of DBInstanceRole -
AutoMinorVersionUpgradeoptional - Boolean -
AvailabilityZoneoptional - String -
BackupRetentionPeriodoptional - Integer -
CACertificateIdentifieroptional - String -
CharacterSetNameoptional - String -
CopyTagsToSnapshotoptional - Boolean -
DBClusterIdentifieroptional - String -
DBInstanceClassrequired - String -
DBInstanceIdentifieroptional - String -
DBNameoptional - String -
DBParameterGroupNameoptional - String -
DBSecurityGroupsoptional - List -
DBSnapshotIdentifieroptional - String -
DBSubnetGroupNameoptional - String -
DeleteAutomatedBackupsoptional - Boolean -
DeletionProtectionoptional - Boolean -
Domainoptional - String -
DomainIAMRoleNameoptional - String -
EnableCloudwatchLogsExportsoptional - List -
EnableIAMDatabaseAuthenticationoptional - Boolean -
EnablePerformanceInsightsoptional - Boolean -
Engineoptional - String -
EngineVersionoptional - String -
Iopsoptional - Integer -
KmsKeyIdoptional - String -
LicenseModeloptional - String -
MasterUserPasswordoptional - String -
MasterUsernameoptional - String -
MaxAllocatedStorageoptional - Integer -
MonitoringIntervaloptional - Integer -
MonitoringRoleArnoptional - String -
MultiAZoptional - Boolean -
OptionGroupNameoptional - String -
PerformanceInsightsKMSKeyIdoptional - String -
PerformanceInsightsRetentionPeriodoptional - Integer -
Portoptional - String -
PreferredBackupWindowoptional - String -
PreferredMaintenanceWindowoptional - String -
ProcessorFeaturesoptional - List of ProcessorFeature -
PromotionTieroptional - Integer -
PubliclyAccessibleoptional - Boolean -
SourceDBInstanceIdentifieroptional - String -
SourceRegionoptional - String -
StorageEncryptedoptional - Boolean -
StorageTypeoptional - String -
Tagsoptional - List of Tag -
Timezoneoptional - String -
UseDefaultProcessorFeaturesoptional - Boolean -
VPCSecurityGroupsoptional - List
Explanation in CloudFormation Registry
The
AWS::RDS::DBInstanceresource 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
DBSnapshotIdentifierproperty with the ID of the DB snapshot that you want to use. After you restore a DB instance with aDBSnapshotIdentifierproperty, you must specify the sameDBSnapshotIdentifierproperty 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 theDBSnapshotIdentifierproperty, 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 specifiedDBSnapshotIdentifierproperty, 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
DBClusterIdentifierproperty:1. ForAWS::RDS::DBInstanceresources that don't specify theDBClusterIdentifierproperty, AWS CloudFormation saves a snapshot of the DB instance.
- For
AWS::RDS::DBInstanceresources that do specify theDBClusterIdentifierproperty, 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.