-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
README.md
1374 lines (1108 loc) · 53.5 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Amazon Relational Database Service Construct Library
```ts nofixture
import * as rds from 'aws-cdk-lib/aws-rds';
```
## Starting a clustered database
To set up a clustered database (like Aurora), define a `DatabaseCluster`. You must
always launch a database in a VPC. Use the `vpcSubnets` attribute to control whether
your instances will be launched privately or publicly:
You must specify the instance to use as the writer, along with an optional list
of readers (up to 15).
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_01_0 }),
credentials: rds.Credentials.fromGeneratedSecret('clusteradmin'), // Optional - will default to 'admin' username and generated password
writer: rds.ClusterInstance.provisioned('writer', {
publiclyAccessible: false,
}),
readers: [
rds.ClusterInstance.provisioned('reader1', { promotionTier: 1 }),
rds.ClusterInstance.serverlessV2('reader2'),
],
vpcSubnets: {
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
},
vpc,
});
```
To adopt Aurora I/O-Optimized, specify `DBClusterStorageType.AURORA_IOPT1` on the `storageType` property.
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraPostgres({ version: rds.AuroraPostgresEngineVersion.VER_15_2 }),
credentials: rds.Credentials.fromUsername('adminuser', { password: SecretValue.unsafePlainText('7959866cacc02c2d243ecfe177464fe6') }),
writer: rds.ClusterInstance.provisioned('writer', {
publiclyAccessible: false,
}),
readers: [
rds.ClusterInstance.provisioned('reader')
],
storageType: rds.DBClusterStorageType.AURORA_IOPT1,
vpcSubnets: {
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
},
vpc,
});
```
If there isn't a constant for the exact version you want to use,
all of the `Version` classes have a static `of` method that can be used to create an arbitrary version.
```ts
const customEngineVersion = rds.AuroraMysqlEngineVersion.of('5.7.mysql_aurora.2.08.1');
```
By default, the master password will be generated and stored in AWS Secrets Manager with auto-generated description.
Your cluster will be empty by default. To add a default database upon construction, specify the
`defaultDatabaseName` attribute.
To use dual-stack mode, specify `NetworkType.DUAL` on the `networkType` property:
```ts
declare const vpc: ec2.Vpc; // VPC and subnets must have IPv6 CIDR blocks
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_02_1 }),
writer: rds.ClusterInstance.provisioned('writer', {
publiclyAccessible: false,
}),
vpc,
networkType: rds.NetworkType.DUAL,
});
```
For more information about dual-stack mode, see [Working with a DB cluster in a VPC](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html).
If you want to issue read/write transactions directly on an Aurora Replica, you can use local write forwarding on [Aurora MySQL](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-mysql-write-forwarding.html)
and [Aurora PostgreSQL](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-postgresql-write-forwarding.html).
Local write forwarding allows read replicas to accept write transactions and forward them to the writer DB instance to be committed.
To enable local write forwarding, set the `enableLocalWriteForwarding` property to `true`:
```ts
declare const vpc: ec2.IVpc;
new rds.DatabaseCluster(this, 'DatabaseCluster', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_07_0 }),
writer: rds.ClusterInstance.serverlessV2('writerInstance'),
readers: [
rds.ClusterInstance.serverlessV2('readerInstance1'),
],
vpc,
enableLocalWriteForwarding: true,
});
```
**Note**: Local write forwarding is supported only for Aurora MySQL 3.04 or higher, and for Aurora PostgreSQL
16.4 or higher (for version 16), 15.8 or higher (for version 15), and 14.13 or higher (for version 14).
Use `DatabaseClusterFromSnapshot` to create a cluster from a snapshot:
```ts
declare const vpc: ec2.Vpc;
new rds.DatabaseClusterFromSnapshot(this, 'Database', {
engine: rds.DatabaseClusterEngine.aurora({ version: rds.AuroraEngineVersion.VER_1_22_2 }),
writer: rds.ClusterInstance.provisioned('writer'),
vpc,
snapshotIdentifier: 'mySnapshot',
});
```
By default, automatic minor version upgrades for the engine type are enabled in a cluster, but you can also disable this.
To do so, set `autoMinorVersionUpgrade` to `false`.
```ts
declare const vpc: ec2.IVpc;
new rds.DatabaseCluster(this, 'DatabaseCluster', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_07_0 }),
writer: rds.ClusterInstance.serverlessV2('writerInstance'),
vpc,
autoMinorVersionUpgrade: false,
});
```
### Updating the database instances in a cluster
Database cluster instances may be updated in bulk or on a rolling basis.
An update to all instances in a cluster may cause significant downtime. To reduce the downtime, set the
`instanceUpdateBehavior` property in `DatabaseClusterBaseProps` to `InstanceUpdateBehavior.ROLLING`.
This adds a dependency between each instance so the update is performed on only one instance at a time.
Use `InstanceUpdateBehavior.BULK` to update all instances at once.
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_01_0 }),
writer: rds.ClusterInstance.provisioned('Instance', {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.SMALL),
}),
readers: [rds.ClusterInstance.provisioned('reader')],
instanceUpdateBehaviour: rds.InstanceUpdateBehaviour.ROLLING, // Optional - defaults to rds.InstanceUpdateBehaviour.BULK
vpc,
});
```
### Serverless V2 instances in a Cluster
It is possible to create an RDS cluster with _both_ serverlessV2 and provisioned
instances. For example, this will create a cluster with a provisioned writer and
a serverless v2 reader.
> *Note* Before getting starting with this type of cluster it is
> highly recommended that you read through the [Developer Guide](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2.setting-capacity.html)
> which goes into much more detail on the things you need to take into
> consideration.
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_01_0 }),
writer: rds.ClusterInstance.provisioned('writer'),
readers: [
rds.ClusterInstance.serverlessV2('reader'),
],
vpc,
});
```
### Monitoring
There are some CloudWatch metrics that are [important for Aurora Serverless
v2](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2.setting-capacity.html#aurora-serverless-v2.viewing.monitoring).
- `ServerlessDatabaseCapacity`: An instance-level metric that can also be
evaluated at the cluster level. At the cluster-level it represents the average
capacity of all the instances in the cluster.
- `ACUUtilization`: Value of the `ServerlessDatabaseCapacity`/ max ACU of the
cluster.
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_01_0 }),
writer: rds.ClusterInstance.provisioned('writer'),
readers: [
rds.ClusterInstance.serverlessV2('reader'),
],
vpc,
});
cluster.metricServerlessDatabaseCapacity({
period: Duration.minutes(10),
}).createAlarm(this, 'capacity', {
threshold: 1.5,
evaluationPeriods: 3,
});
cluster.metricACUUtilization({
period: Duration.minutes(10),
}).createAlarm(this, 'alarm', {
evaluationPeriods: 3,
threshold: 90,
});
```
#### Capacity & Scaling
There are some things to take into consideration with Aurora Serverless v2.
To create a cluster that can support serverless v2 instances you configure a
minimum and maximum capacity range on the cluster. This is an example showing
the default values:
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_01_0 }),
writer: rds.ClusterInstance.serverlessV2('writer'),
serverlessV2MinCapacity: 0.5,
serverlessV2MaxCapacity: 2,
vpc,
});
```
The capacity is defined as a number of Aurora capacity units (ACUs). You can
specify in half-step increments (40, 40.5, 41, etc). Each serverless instance in
the cluster inherits the capacity that is defined on the cluster. It is not
possible to configure separate capacity at the instance level.
The maximum capacity is mainly used for budget control since it allows you to
set a cap on how high your instance can scale.
The minimum capacity is a little more involved. This controls a couple different
things.
* The scale-up rate is proportional to the current capacity (larger instances
scale up faster)
* Adjust the minimum capacity to obtain a suitable scaling rate
* Network throughput is proportional to capacity
> *Info* More complete details can be found [in the docs](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2.setting-capacity.html#aurora-serverless-v2-examples-setting-capacity-range-for-cluster)
Another way that you control the capacity/scaling of your serverless v2 reader
instances is based on the [promotion tier](https://aws.amazon.com/blogs/aws/additional-failover-control-for-amazon-aurora/)
which can be between 0-15. Any serverless v2 instance in the 0-1 tiers will scale alongside the
writer even if the current read load does not require the capacity. This is
because instances in the 0-1 tier are first priority for failover and Aurora
wants to ensure that in the event of a failover the reader that gets promoted is
scaled to handle the write load.
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_01_0 }),
writer: rds.ClusterInstance.serverlessV2('writer'),
readers: [
// will be put in promotion tier 1 and will scale with the writer
rds.ClusterInstance.serverlessV2('reader1', { scaleWithWriter: true }),
// will be put in promotion tier 2 and will not scale with the writer
rds.ClusterInstance.serverlessV2('reader2'),
],
vpc,
});
```
* When the writer scales up, any readers in tier 0-1 will scale up to match
* Scaling for tier 2-15 is independent of what is happening on the writer
* Readers in tier 2-15 scale up based on read load against the individual reader
When configuring your cluster it is important to take this into consideration
and ensure that in the event of a failover there is an instance that is scaled
up to take over.
### Mixing Serverless v2 and Provisioned instances
You are able to create a cluster that has both provisioned and serverless
instances. [This blog post](https://aws.amazon.com/blogs/database/evaluate-amazon-aurora-serverless-v2-for-your-provisioned-aurora-clusters/)
has an excellent guide on choosing between serverless and provisioned instances
based on use case.
There are a couple of high level differences:
* Engine Version (serverless only supports MySQL 8+ & PostgreSQL 13+)
* Memory up to 256GB can be supported by serverless
#### Provisioned writer
With a provisioned writer and serverless v2 readers, some of the serverless
readers will need to be configured to scale with the writer so they can act as
failover targets. You will need to determine the correct capacity based on the
provisioned instance type and it's utilization.
As an example, if the CPU utilization for a db.r6g.4xlarge (128 GB) instance
stays at 10% most times, then the minimum ACUs may be set at 6.5 ACUs
(10% of 128 GB) and maximum may be set at 64 ACUs (64x2GB=128GB). Keep in mind
that the speed at which the serverless instance can scale up is determined by
the minimum capacity so if your cluster has spiky workloads you may need to set
a higher minimum capacity.
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_01_0 }),
writer: rds.ClusterInstance.provisioned('writer', {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.R6G, ec2.InstanceSize.XLARGE4),
}),
serverlessV2MinCapacity: 6.5,
serverlessV2MaxCapacity: 64,
readers: [
// will be put in promotion tier 1 and will scale with the writer
rds.ClusterInstance.serverlessV2('reader1', { scaleWithWriter: true }),
// will be put in promotion tier 2 and will not scale with the writer
rds.ClusterInstance.serverlessV2('reader2'),
],
vpc,
});
```
In the above example `reader1` will scale with the writer based on the writer's
utilization. So if the writer were to go to `50%` utilization then `reader1`
would scale up to use `32` ACUs. If the read load stayed consistent then
`reader2` may remain at `6.5` since it is not configured to scale with the
writer.
If one of your Aurora Serverless v2 DB instances consistently reaches the
limit of its maximum capacity, Aurora indicates this condition by setting the
DB instance to a status of `incompatible-parameters`. While the DB instance has
the incompatible-parameters status, some operations are blocked. For example,
you can't upgrade the engine version.
#### CA certificate
Use the `caCertificate` property to specify the [CA certificates](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html)
to use for a cluster instances:
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_01_0 }),
writer: rds.ClusterInstance.provisioned('writer', {
caCertificate: rds.CaCertificate.RDS_CA_RSA2048_G1,
}),
readers: [
rds.ClusterInstance.serverlessV2('reader', {
caCertificate: rds.CaCertificate.of('custom-ca'),
}),
],
vpc,
});
```
### Migrating from instanceProps
Creating instances in a `DatabaseCluster` using `instanceProps` & `instances` is
deprecated. To migrate to the new properties you can provide the
`isFromLegacyInstanceProps` property.
For example, in order to migrate from this deprecated config:
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({
version: rds.AuroraMysqlEngineVersion.VER_3_03_0,
}),
instances: 2,
instanceProps: {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.SMALL),
vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },
vpc,
},
});
```
You would need to migrate to this. The old method of providing `instanceProps`
and `instances` will create the number of `instances` that you provide. The
first instance will be the writer and the rest will be the readers. It's
important that the `id` that you provide is `Instance{NUMBER}`. The writer
should always be `Instance1` and the readers will increment from there.
Make sure to run a `cdk diff` before deploying to make sure that all changes are
expected. **Always test the migration in a non-production environment first.**
```ts
const instanceProps = {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.SMALL),
isFromLegacyInstanceProps: true,
};
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({
version: rds.AuroraMysqlEngineVersion.VER_3_03_0,
}),
vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },
vpc,
writer: rds.ClusterInstance.provisioned('Instance1', {
instanceType: instanceProps.instanceType,
isFromLegacyInstanceProps: instanceProps.isFromLegacyInstanceProps,
}),
readers: [
rds.ClusterInstance.provisioned('Instance2', {
instanceType: instanceProps.instanceType,
isFromLegacyInstanceProps: instanceProps.isFromLegacyInstanceProps,
}),
],
});
```
## Starting an instance database
To set up an instance database, define a `DatabaseInstance`. You must
always launch a database in a VPC. Use the `vpcSubnets` attribute to control whether
your instances will be launched privately or publicly:
```ts
declare const vpc: ec2.Vpc;
const instance = new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.oracleSe2({ version: rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1 }),
// optional, defaults to m5.large
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.SMALL),
credentials: rds.Credentials.fromGeneratedSecret('syscdk'), // Optional - will default to 'admin' username and generated password
vpc,
vpcSubnets: {
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
}
});
```
If there isn't a constant for the exact engine version you want to use,
all of the `Version` classes have a static `of` method that can be used to create an arbitrary version.
```ts
const customEngineVersion = rds.OracleEngineVersion.of('19.0.0.0.ru-2020-04.rur-2020-04.r1', '19');
```
By default, the master password will be generated and stored in AWS Secrets Manager.
To use the storage auto scaling option of RDS you can specify the maximum allocated storage.
This is the upper limit to which RDS can automatically scale the storage. More info can be found
[here](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIOPS.StorageTypes.html#USER_PIOPS.Autoscaling)
Example for max storage configuration:
```ts
declare const vpc: ec2.Vpc;
const instance = new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_16_3 }),
// optional, defaults to m5.large
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL),
vpc,
maxAllocatedStorage: 200,
});
```
To use dual-stack mode, specify `NetworkType.DUAL` on the `networkType` property:
```ts
declare const vpc: ec2.Vpc; // VPC and subnets must have IPv6 CIDR blocks
const instance = new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_16_3 }),
vpc,
networkType: rds.NetworkType.DUAL,
publiclyAccessible: false,
});
```
For more information about dual-stack mode, see [Working with a DB instance in a VPC](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html).
Use `DatabaseInstanceFromSnapshot` and `DatabaseInstanceReadReplica` to create an instance from snapshot or
a source database respectively:
```ts
declare const vpc: ec2.Vpc;
new rds.DatabaseInstanceFromSnapshot(this, 'Instance', {
snapshotIdentifier: 'my-snapshot',
engine: rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_16_3 }),
// optional, defaults to m5.large
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),
vpc,
});
declare const sourceInstance: rds.DatabaseInstance;
new rds.DatabaseInstanceReadReplica(this, 'ReadReplica', {
sourceDatabaseInstance: sourceInstance,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),
vpc,
});
```
Automatic backups of read replica instances are only supported for MySQL and MariaDB. By default,
automatic backups are disabled for read replicas and can only be enabled (using `backupRetention`)
if also enabled on the source instance.
Creating a "production" Oracle database instance with option and parameter groups:
[example of setting up a production oracle instance](test/integ.instance.lit.ts)
Use the `storageType` property to specify the [type of storage](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html)
to use for the instance:
```ts
declare const vpc: ec2.Vpc;
const iopsInstance = new rds.DatabaseInstance(this, 'IopsInstance', {
engine: rds.DatabaseInstanceEngine.mysql({ version: rds.MysqlEngineVersion.VER_8_0_39 }),
vpc,
storageType: rds.StorageType.IO1,
iops: 5000,
});
const gp3Instance = new rds.DatabaseInstance(this, 'Gp3Instance', {
engine: rds.DatabaseInstanceEngine.mysql({ version: rds.MysqlEngineVersion.VER_8_0_39 }),
vpc,
allocatedStorage: 500,
storageType: rds.StorageType.GP3,
storageThroughput: 500, // only applicable for GP3
});
```
Use the `allocatedStorage` property to specify the amount of storage (in gigabytes) that is initially allocated for the instance
to use for the instance:
```ts
declare const vpc: ec2.Vpc;
// Setting allocatedStorage for DatabaseInstance
const iopsInstance = new rds.DatabaseInstance(this, 'IopsInstance', {
engine: rds.DatabaseInstanceEngine.mysql({ version: rds.MysqlEngineVersion.VER_8_0_39 }),
vpc,
storageType: rds.StorageType.IO1,
iops: 5000,
allocatedStorage: 500,
});
// Setting allocatedStorage for DatabaseInstance replica
// Note: If allocatedStorage isn't set here, the replica instance will inherit the allocatedStorage of the source instance
declare const sourceInstance: rds.DatabaseInstance;
new rds.DatabaseInstanceReadReplica(this, 'ReadReplica', {
sourceDatabaseInstance: sourceInstance,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),
vpc,
allocatedStorage: 500,
});
```
Use the `caCertificate` property to specify the [CA certificates](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html)
to use for the instance:
```ts
declare const vpc: ec2.Vpc;
new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.mysql({ version: rds.MysqlEngineVersion.VER_8_0_39 }),
vpc,
caCertificate: rds.CaCertificate.RDS_CA_RSA2048_G1,
});
```
You can specify a custom CA certificate with:
```ts
declare const vpc: ec2.Vpc;
new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.mysql({ version: rds.MysqlEngineVersion.VER_8_0_39 }),
vpc,
caCertificate: rds.CaCertificate.of('future-rds-ca'),
});
```
## Setting Public Accessibility
You can set public accessibility for the `DatabaseInstance` or the `ClusterInstance` using the `publiclyAccessible` property.
If you specify `true`, it creates an instance with a publicly resolvable DNS name, which resolves to a public IP address.
If you specify `false`, it creates an internal instance with a DNS name that resolves to a private IP address.
The default value will be `true` if `vpcSubnets` is `subnetType: SubnetType.PUBLIC`, `false` otherwise. In the case of a
cluster, the default value will be determined on the vpc placement of the `DatabaseCluster` otherwise it will be determined
based on the vpc placement of standalone `DatabaseInstance`.
```ts
declare const vpc: ec2.Vpc;
// Setting public accessibility for DB instance
new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.mysql({
version: rds.MysqlEngineVersion.VER_8_0_19,
}),
vpc,
vpcSubnets: {
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
},
publiclyAccessible: true,
});
// Setting public accessibility for DB cluster instance
new rds.DatabaseCluster(this, 'DatabaseCluster', {
engine: rds.DatabaseClusterEngine.auroraMysql({
version: rds.AuroraMysqlEngineVersion.VER_3_03_0,
}),
writer: rds.ClusterInstance.serverlessV2('Writer', {
publiclyAccessible: true,
}),
vpc,
vpcSubnets: {
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
},
});
```
## Instance events
To define Amazon CloudWatch event rules for database instances, use the `onEvent`
method:
```ts
declare const instance: rds.DatabaseInstance;
declare const fn: lambda.Function;
const rule = instance.onEvent('InstanceEvent', { target: new targets.LambdaFunction(fn) });
```
## Login credentials
By default, database instances and clusters (with the exception of `DatabaseInstanceFromSnapshot` and `ServerlessClusterFromSnapshot`) will have `admin` user with an auto-generated password.
An alternative username (and password) may be specified for the admin user instead of the default.
The following examples use a `DatabaseInstance`, but the same usage is applicable to `DatabaseCluster`.
```ts
declare const vpc: ec2.Vpc;
const engine = rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_16_3 });
new rds.DatabaseInstance(this, 'InstanceWithUsername', {
engine,
vpc,
credentials: rds.Credentials.fromGeneratedSecret('postgres'), // Creates an admin user of postgres with a generated password
});
new rds.DatabaseInstance(this, 'InstanceWithUsernameAndPassword', {
engine,
vpc,
credentials: rds.Credentials.fromPassword('postgres', SecretValue.ssmSecure('/dbPassword', '1')), // Use password from SSM
});
const mySecret = secretsmanager.Secret.fromSecretName(this, 'DBSecret', 'myDBLoginInfo');
new rds.DatabaseInstance(this, 'InstanceWithSecretLogin', {
engine,
vpc,
credentials: rds.Credentials.fromSecret(mySecret), // Get both username and password from existing secret
});
```
Secrets generated by `fromGeneratedSecret()` can be customized:
```ts
declare const vpc: ec2.Vpc;
const engine = rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_16_3 });
const myKey = new kms.Key(this, 'MyKey');
new rds.DatabaseInstance(this, 'InstanceWithCustomizedSecret', {
engine,
vpc,
credentials: rds.Credentials.fromGeneratedSecret('postgres', {
secretName: 'my-cool-name',
encryptionKey: myKey,
excludeCharacters: '!&*^#@()',
replicaRegions: [{ region: 'eu-west-1' }, { region: 'eu-west-2' }],
}),
});
```
### Snapshot credentials
As noted above, Databases created with `DatabaseInstanceFromSnapshot` or `ServerlessClusterFromSnapshot` will not create user and auto-generated password by default because it's not possible to change the master username for a snapshot. Instead, they will use the existing username and password from the snapshot. You can still generate a new password - to generate a secret similarly to the other constructs, pass in credentials with `fromGeneratedSecret()` or `fromGeneratedPassword()`.
```ts
declare const vpc: ec2.Vpc;
const engine = rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_16_3 });
const myKey = new kms.Key(this, 'MyKey');
new rds.DatabaseInstanceFromSnapshot(this, 'InstanceFromSnapshotWithCustomizedSecret', {
engine,
vpc,
snapshotIdentifier: 'mySnapshot',
credentials: rds.SnapshotCredentials.fromGeneratedSecret('username', {
encryptionKey: myKey,
excludeCharacters: '!&*^#@()',
replicaRegions: [{ region: 'eu-west-1' }, { region: 'eu-west-2' }],
}),
});
```
## Connecting
To control who can access the cluster or instance, use the `.connections` attribute. RDS databases have
a default port, so you don't need to specify the port:
```ts
declare const cluster: rds.DatabaseCluster;
cluster.connections.allowFromAnyIpv4(ec2.Port.allTraffic(), 'Open to the world');
```
The endpoints to access your database cluster will be available as the `.clusterEndpoint` and `.readerEndpoint`
attributes:
```ts
declare const cluster: rds.DatabaseCluster;
const writeAddress = cluster.clusterEndpoint.socketAddress; // "HOSTNAME:PORT"
```
For an instance database:
```ts
declare const instance: rds.DatabaseInstance;
const address = instance.instanceEndpoint.socketAddress; // "HOSTNAME:PORT"
```
## Rotating credentials
When the master password is generated and stored in AWS Secrets Manager, it can be rotated automatically:
```ts
declare const instance: rds.DatabaseInstance;
declare const mySecurityGroup: ec2.SecurityGroup;
instance.addRotationSingleUser({
automaticallyAfter: Duration.days(7), // defaults to 30 days
excludeCharacters: '!@#$%^&*', // defaults to the set " %+~`#$&*()|[]{}:;<>?!'/@\"\\"
securityGroup: mySecurityGroup, // defaults to an auto-created security group
});
```
[example of setting up master password rotation for a cluster](test/integ.cluster-rotation.lit.ts)
The multi user rotation scheme is also available:
```ts
declare const instance: rds.DatabaseInstance;
declare const myImportedSecret: rds.DatabaseSecret;
instance.addRotationMultiUser('MyUser', {
secret: myImportedSecret, // This secret must have the `masterarn` key
});
```
It's also possible to create user credentials together with the instance/cluster and add rotation:
```ts
declare const instance: rds.DatabaseInstance;
const myUserSecret = new rds.DatabaseSecret(this, 'MyUserSecret', {
username: 'myuser',
secretName: 'my-user-secret', // optional, defaults to a CloudFormation-generated name
dbname: 'mydb', //optional, defaults to the main database of the RDS cluster this secret gets attached to
masterSecret: instance.secret,
excludeCharacters: '{}[]()\'"/\\', // defaults to the set " %+~`#$&*()|[]{}:;<>?!'/@\"\\"
});
const myUserSecretAttached = myUserSecret.attach(instance); // Adds DB connections information in the secret
instance.addRotationMultiUser('MyUser', { // Add rotation using the multi user scheme
secret: myUserSecretAttached,
});
```
**Note**: This user must be created manually in the database using the master credentials.
The rotation will start as soon as this user exists.
Access to the Secrets Manager API is required for the secret rotation. This can be achieved either with
internet connectivity (through NAT) or with a VPC interface endpoint. By default, the rotation Lambda function
is deployed in the same subnets as the instance/cluster. If access to the Secrets Manager API is not possible from
those subnets or using the default API endpoint, use the `vpcSubnets` and/or `endpoint` options:
```ts
declare const instance: rds.DatabaseInstance;
declare const myEndpoint: ec2.InterfaceVpcEndpoint;
instance.addRotationSingleUser({
vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS }, // Place rotation Lambda in private subnets
endpoint: myEndpoint, // Use VPC interface endpoint
});
```
See also [aws-cdk-lib/aws-secretsmanager](https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk-lib/aws-secretsmanager/README.md) for credentials rotation of existing clusters/instances.
By default, any stack updates will cause AWS Secrets Manager to rotate a secret immediately. To prevent this behavior and wait until the next scheduled rotation window specified via the `automaticallyAfter` property, set the `rotateImmediatelyOnUpdate` property to false:
```ts
declare const instance: rds.DatabaseInstance;
declare const mySecurityGroup: ec2.SecurityGroup;
instance.addRotationSingleUser({
automaticallyAfter: Duration.days(7), // defaults to 30 days
excludeCharacters: '!@#$%^&*', // defaults to the set " %+~`#$&*()|[]{}:;<>?!'/@\"\\"
securityGroup: mySecurityGroup, // defaults to an auto-created security group
rotateImmediatelyOnUpdate: false, // defaults to true
});
```
## IAM Authentication
You can also authenticate to a database instance using AWS Identity and Access Management (IAM) database authentication;
See <https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html> for more information
and a list of supported versions and limitations.
The following example shows enabling IAM authentication for a database instance and granting connection access to an IAM role.
### Instance
```ts
declare const vpc: ec2.Vpc;
const instance = new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.mysql({ version: rds.MysqlEngineVersion.VER_8_0_19 }),
vpc,
iamAuthentication: true, // Optional - will be automatically set if you call grantConnect().
});
const role = new iam.Role(this, 'DBRole', { assumedBy: new iam.AccountPrincipal(this.account) });
instance.grantConnect(role); // Grant the role connection access to the DB.
```
### Proxy
The following example shows granting connection access for RDS Proxy to an IAM role.
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({
version: rds.AuroraMysqlEngineVersion.VER_3_03_0,
}),
writer: rds.ClusterInstance.provisioned('writer'),
vpc,
});
const proxy = new rds.DatabaseProxy(this, 'Proxy', {
proxyTarget: rds.ProxyTarget.fromCluster(cluster),
secrets: [cluster.secret!],
vpc,
});
const role = new iam.Role(this, 'DBProxyRole', { assumedBy: new iam.AccountPrincipal(this.account) });
proxy.grantConnect(role, 'admin'); // Grant the role connection access to the DB Proxy for database user 'admin'.
```
**Note**: In addition to the setup above, a database user will need to be created to support IAM auth.
See <https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html> for setup instructions.
To specify the details of authentication used by a proxy to log in as a specific database
user use the `clientPasswordAuthType` property:
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({
version: rds.AuroraMysqlEngineVersion.VER_3_03_0,
}),
writer: rds.ClusterInstance.provisioned('writer'),
vpc,
});
const proxy = new rds.DatabaseProxy(this, 'Proxy', {
proxyTarget: rds.ProxyTarget.fromCluster(cluster),
secrets: [cluster.secret!],
vpc,
clientPasswordAuthType: rds.ClientPasswordAuthType.MYSQL_NATIVE_PASSWORD,
});
```
### Cluster
The following example shows granting connection access for an IAM role to an Aurora Cluster.
```ts
declare const vpc: ec2.Vpc;
const cluster = new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({
version: rds.AuroraMysqlEngineVersion.VER_3_03_0,
}),
writer: rds.ClusterInstance.provisioned('writer'),
vpc,
});
const role = new iam.Role(this, 'AppRole', { assumedBy: new iam.ServicePrincipal('someservice.amazonaws.com') });
cluster.grantConnect(role, 'somedbuser');
```
**Note**: In addition to the setup above, a database user will need to be created to support IAM auth.
See <https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html> for setup instructions.
## Kerberos Authentication
You can also authenticate using Kerberos to a database instance using AWS Managed Microsoft AD for authentication;
See <https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html> for more information
and a list of supported versions and limitations.
The following example shows enabling domain support for a database instance and creating an IAM role to access
Directory Services.
```ts
declare const vpc: ec2.Vpc;
const role = new iam.Role(this, 'RDSDirectoryServicesRole', {
assumedBy: new iam.CompositePrincipal(
new iam.ServicePrincipal('rds.amazonaws.com'),
new iam.ServicePrincipal('directoryservice.rds.amazonaws.com'),
),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonRDSDirectoryServiceAccess'),
],
});
const instance = new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.mysql({ version: rds.MysqlEngineVersion.VER_8_0_19 }),
vpc,
domain: 'd-????????', // The ID of the domain for the instance to join.
domainRole: role, // Optional - will be create automatically if not provided.
});
```
You can also use the Kerberos authentication for an Aurora database cluster.
```ts
declare const vpc: ec2.Vpc;
const iamRole = new iam.Role(this, 'Role', {
assumedBy: new iam.CompositePrincipal(
new iam.ServicePrincipal('rds.amazonaws.com'),
new iam.ServicePrincipal('directoryservice.rds.amazonaws.com'),
),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonRDSDirectoryServiceAccess'),
],
});
new rds.DatabaseCluster(this, 'Database', {
engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_05_1 }),
writer: rds.ClusterInstance.provisioned('Instance', {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MEDIUM),
}),
vpc,
domain: 'd-????????', // The ID of the domain for the cluster to join.
domainRole: iamRole, // Optional - will be created automatically if not provided.
});
```
**Note**: In addition to the setup above, you need to make sure that the database instance or cluster has network connectivity
to the domain controllers. This includes enabling cross-VPC traffic if in a different VPC and setting up the
appropriate security groups/network ACL to allow traffic between the database instance and domain controllers.
Once configured, see <https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html> for details
on configuring users for each available database engine.
## Metrics
Database instances and clusters both expose metrics (`cloudwatch.Metric`):
```ts
// The number of database connections in use (average over 5 minutes)
declare const instance: rds.DatabaseInstance;
const dbConnections = instance.metricDatabaseConnections();
// Average CPU utilization over 5 minutes
declare const cluster: rds.DatabaseCluster;
const cpuUtilization = cluster.metricCPUUtilization();
// The average amount of time taken per disk I/O operation (average over 1 minute)
const readLatency = instance.metric('ReadLatency', { statistic: 'Average', period: Duration.seconds(60) });
```
## Enabling S3 integration
Data in S3 buckets can be imported to and exported from certain database engines using SQL queries. To enable this
functionality, set the `s3ImportBuckets` and `s3ExportBuckets` properties for import and export respectively. When
configured, the CDK automatically creates and configures IAM roles as required.
Additionally, the `s3ImportRole` and `s3ExportRole` properties can be used to set this role directly.
Note: To use `s3ImportRole` and `s3ExportRole` with Aurora PostgreSQL, you must also enable the S3 import and export features when you create the DatabaseClusterEngine.
You can read more about loading data to (or from) S3 here:
* Aurora MySQL - [import](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.LoadFromS3.html)
and [export](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.SaveIntoS3.html).
* Aurora PostgreSQL - [import](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Migrating.html#USER_PostgreSQL.S3Import)
and [export](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/postgresql-s3-export.html).
* Microsoft SQL Server - [import and export](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/SQLServer.Procedural.Importing.html)
* PostgreSQL - [import](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL.Procedural.Importing.html)
and [export](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/postgresql-s3-export.html)
* Oracle - [import and export](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html)
The following snippet sets up a database cluster with different S3 buckets where the data is imported and exported -
```ts
import * as s3 from 'aws-cdk-lib/aws-s3';
declare const vpc: ec2.Vpc;
const importBucket = new s3.Bucket(this, 'importbucket');
const exportBucket = new s3.Bucket(this, 'exportbucket');
new rds.DatabaseCluster(this, 'dbcluster', {
engine: rds.DatabaseClusterEngine.auroraMysql({