Sub topic 5
Creating a DB instance
This chapter assumes you can use the AWS CLI, know what a VPC, subnet and security group are, and have chosen an engine, instance class and storage type in the earlier chapters. Here you assemble those choices into a running instance, then confirm it is healthy.
What you need before you call create
create-db-instance fails or produces a poor result if its dependencies are missing. Gather these first:
| Dependency | Why it is needed | Created in |
|---|---|---|
| DB subnet group | Tells RDS which subnets, in at least two Availability Zones, it may place the instance in | This chapter |
| VPC security group | Controls which clients can reach the database port | Networking chapter |
| Parameter group (optional) | Holds engine settings. If you omit it, RDS attaches the default group for the engine family | Parameter groups chapter |
| KMS key (optional) | Encrypts storage and the managed secret. If you omit it, the AWS managed key `aws/rds` is used | Encryption chapter |
Step 1: Create the DB subnet group
A DB subnet group is a named list of subnets. RDS requires subnets in at least two Availability Zones, even for a single-AZ instance, so that Multi-AZ or a later restore can use another zone. Use private subnets, meaning subnets whose route table has no route to an internet gateway.
aws rds create-db-subnet-group \
--db-subnet-group-name demo-subnets \
--db-subnet-group-description "Private subnets for the demo database" \
--subnet-ids subnet-0123456789abcdef0 subnet-0fedcba9876543210The subnets must all belong to the same VPC. That VPC is then the VPC of every instance that uses the group. You cannot place an instance in a VPC without a subnet group for it.
Step 2: Create the instance
The following command creates a small, private, encrypted PostgreSQL instance.
aws rds create-db-instance \
--db-instance-identifier demo-pg \
--engine postgres \
--db-instance-class db.t4g.micro \
--allocated-storage 20 \
--storage-type gp3 \
--master-username appadmin \
--manage-master-user-password \
--db-subnet-group-name demo-subnets \
--vpc-security-group-ids sg-0123456789abcdef0 \
--no-publicly-accessible \
--storage-encrypted \
--backup-retention-period 7The call returns immediately with the instance in the creating state. RDS keeps working in the background.
What each option does
--db-instance-identifieris the name of the instance. It must be lowercase, start with a letter, and be unique per account and Region. It becomes part of the endpoint hostname.--engineselects the database engine. Without--engine-version, RDS picks the current default major version for that engine. Pin the version explicitly in anything you intend to repeat, so two environments do not drift apart.--db-instance-classmust be available for your engine, version and Region. To check, runaws rds describe-orderable-db-instance-options --engine postgres --db-instance-class db.t4g.micro.--allocated-storageis in GiB. The minimum depends on the storage type and engine. For gp3 on PostgreSQL, 20 GiB is the minimum.--master-usernameis the administrative user. Engines reserve some names, so a name such asadmincan be rejected.--manage-master-user-passwordmakes RDS generate the master password and keep it in AWS Secrets Manager. Do not combine it with--master-user-password, because the two options conflict.--vpc-security-group-idsattaches the security group. If you leave it out, RDS attaches the VPC's default security group, which is usually not what you want.--no-publicly-accessiblegives the instance only a private IP address. State this explicitly. The default depends on the VPC, and instances in a default VPC can be public unless you say otherwise.--storage-encryptedturns on encryption at rest. You can only set this at creation. An unencrypted instance can be encrypted later only by copying a snapshot with encryption and restoring it.--backup-retention-period 7keeps automated backups for seven days. Through the CLI and API the default is one day. The console proposes seven.
Options worth adding for real workloads
These are not in the minimal command, but you will often need them:
--db-namecreates an initial database. If you omit it, PostgreSQL still has the built-inpostgresdatabase.--db-parameter-group-nameattaches a custom parameter group instead of the default. Changing which group is attached later can require a reboot.--multi-azcreates a standby in a second Availability Zone. This is covered in the Multi-AZ chapter.--deletion-protectionblocksdelete-db-instanceuntil you turn the protection off. It is a cheap safeguard for anything that matters.--tagshelps cost allocation and cleanup, for exampleKey=project,Value=demo.--kms-key-idselects a customer managed key for storage encryption.--master-user-secret-kms-key-idselects the key that encrypts the managed secret.
Step 3: Wait for the instance and read its details
Creation commonly takes five to fifteen minutes. The status moves through creating, usually backing-up while the first backup runs, and then available. Do not try to connect until the status is available.
import boto3
rds = boto3.client("rds")
rds.get_waiter("db_instance_available").wait(DBInstanceIdentifier="demo-pg")
instance = rds.describe_db_instances(DBInstanceIdentifier="demo-pg")["DBInstances"][0]
endpoint = instance["Endpoint"]
print(endpoint["Address"], endpoint["Port"])
print(instance["MasterUserSecret"]["SecretArn"])The waiter polls every 30 seconds and gives up after 60 attempts, about 30 minutes, and then raises a WaiterError. The Endpoint key is absent while the instance is still creating, so reading it before the waiter returns raises a KeyError. Your client's credentials need rds:DescribeDBInstances. The MasterUserSecret block also contains SecretStatus and KmsKeyId, which tell you whether the secret is active and which key protects it.
The secret holds a JSON document with username and password. Your application reads it through Secrets Manager rather than from a config file. Reading the secret requires secretsmanager:GetSecretValue on that ARN and kms:Decrypt on its key.
Verifying the result
After the instance is available, check four things:
PubliclyAccessibleisfalsein thedescribe-db-instancesoutput.StorageEncryptedistrue.BackupRetentionPeriodis7.VpcSecurityGroupslists the group you intended and its status isactive.
You can run this check with the CLI query option, which avoids reading the whole JSON document:
aws rds describe-db-instances \
--db-instance-identifier demo-pg \
--query "DBInstances[0].[DBInstanceStatus,PubliclyAccessible,StorageEncrypted,BackupRetentionPeriod]"Common errors
| Error or symptom | Likely cause | Fix |
|---|---|---|
| `DBSubnetGroupDoesNotCoverEnoughAZs` | The subnet group has subnets in only one Availability Zone | Add a subnet from another zone to the group |
| `DBInstanceAlreadyExists` | The identifier is already in use in this account and Region | Choose a different identifier |
| `InvalidParameterCombination` | Incompatible options, such as an instance class the engine does not support, or both a managed and a manual master password | Check orderable options and remove the conflicting flag |
| `InvalidVPCNetworkStateFault` or a subnet group error | The subnet group, VPC or security group do not match | Use a security group from the same VPC as the subnet group |
| Instance stuck in `incompatible-network` | The VPC lost a required resource, such as subnets or an IP address | Restore the missing network resource, then reboot |
| `Endpoint` missing in the response | The instance is still `creating` | Wait for `available` |
Summary of the creation workflow
- Build or choose private subnets in two or more Availability Zones, and create a DB subnet group from them.
- Prepare a security group that allows the database port only from your application's security group.
- Run
create-db-instancewith encryption, private access, backup retention and a managed master password set explicitly. - Wait for
available, then read the endpoint and secret ARN. - Verify the settings with
describe-db-instancesbefore you load any data.
Exercise
You run create-db-instance without the --publicly-accessible or --no-publicly-accessible flag, and without --storage-encrypted. A colleague says this is fine because "the defaults are safe". Which two settings should you check on the new instance, and why is it risky to rely on the defaults?
Show answer
Check PubliclyAccessible and StorageEncrypted in the describe-db-instances output. The default for public accessibility depends on the VPC, so an instance in a default VPC can receive a public address. Encryption at rest is off unless you request it with --storage-encrypted, and it cannot be switched on for an existing instance. It would require copying an encrypted snapshot and restoring from it. Always set both flags explicitly.
Exercise
Your create-db-instance call returns DBSubnetGroupDoesNotCoverEnoughAZs. What is wrong, and how do you fix it without recreating the VPC?
Show answer
The DB subnet group contains subnets from only one Availability Zone. RDS requires subnets in at least two zones. Create or choose a subnet in a different zone within the same VPC and add it to the group, for example with aws rds modify-db-subnet-group, then repeat the create call.