-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathinstance.ts
1412 lines (1238 loc) · 47.8 KB
/
instance.ts
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
import { Construct } from 'constructs';
import { CaCertificate } from './ca-certificate';
import { DatabaseSecret } from './database-secret';
import { Endpoint } from './endpoint';
import { IInstanceEngine } from './instance-engine';
import { IOptionGroup } from './option-group';
import { IParameterGroup, ParameterGroup } from './parameter-group';
import { applyDefaultRotationOptions, defaultDeletionProtection, engineDescription, renderCredentials, setupS3ImportExport, helperRemovalPolicy, renderUnless } from './private/util';
import { Credentials, PerformanceInsightRetention, RotationMultiUserOptions, RotationSingleUserOptions, SnapshotCredentials } from './props';
import { DatabaseProxy, DatabaseProxyOptions, ProxyTarget } from './proxy';
import { CfnDBInstance, CfnDBInstanceProps } from './rds.generated';
import { ISubnetGroup, SubnetGroup } from './subnet-group';
import * as ec2 from '../../aws-ec2';
import * as events from '../../aws-events';
import * as iam from '../../aws-iam';
import * as kms from '../../aws-kms';
import * as logs from '../../aws-logs';
import * as s3 from '../../aws-s3';
import * as secretsmanager from '../../aws-secretsmanager';
import { ArnComponents, ArnFormat, Duration, FeatureFlags, IResource, Lazy, RemovalPolicy, Resource, Stack, Token, Tokenization } from '../../core';
import * as cxapi from '../../cx-api';
/**
* A database instance
*/
export interface IDatabaseInstance extends IResource, ec2.IConnectable, secretsmanager.ISecretAttachmentTarget {
/**
* The instance identifier.
*/
readonly instanceIdentifier: string;
/**
* The instance arn.
*/
readonly instanceArn: string;
/**
* The instance endpoint address.
*
* @attribute EndpointAddress
*/
readonly dbInstanceEndpointAddress: string;
/**
* The instance endpoint port.
*
* @attribute EndpointPort
*/
readonly dbInstanceEndpointPort: string;
/**
* The AWS Region-unique, immutable identifier for the DB instance.
* This identifier is found in AWS CloudTrail log entries whenever the AWS KMS key for the DB instance is accessed.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbinstance.html#aws-resource-rds-dbinstance-return-values
*/
readonly instanceResourceId?: string;
/**
* The instance endpoint.
*/
readonly instanceEndpoint: Endpoint;
/**
* The engine of this database Instance.
* May be not known for imported Instances if it wasn't provided explicitly,
* or for read replicas.
*/
readonly engine?: IInstanceEngine;
/**
* Add a new db proxy to this instance.
*/
addProxy(id: string, options: DatabaseProxyOptions): DatabaseProxy;
/**
* Grant the given identity connection access to the database.
*
* @param grantee the Principal to grant the permissions to
* @param dbUser the name of the database user to allow connecting as to the db instance
*/
grantConnect(grantee: iam.IGrantable, dbUser?: string): iam.Grant;
/**
* Defines a CloudWatch event rule which triggers for instance events. Use
* `rule.addEventPattern(pattern)` to specify a filter.
*/
onEvent(id: string, options?: events.OnEventOptions): events.Rule;
}
/**
* Properties that describe an existing instance
*/
export interface DatabaseInstanceAttributes {
/**
* The instance identifier.
*/
readonly instanceIdentifier: string;
/**
* The endpoint address.
*/
readonly instanceEndpointAddress: string;
/**
* The database port.
*/
readonly port: number;
/**
* The AWS Region-unique, immutable identifier for the DB instance.
* This identifier is found in AWS CloudTrail log entries whenever the AWS KMS key for the DB instance is accessed.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbinstance.html#aws-resource-rds-dbinstance-return-values
*/
readonly instanceResourceId?: string;
/**
* The security groups of the instance.
*/
readonly securityGroups: ec2.ISecurityGroup[];
/**
* The engine of the existing database Instance.
*
* @default - the imported Instance's engine is unknown
*/
readonly engine?: IInstanceEngine;
}
/**
* A new or imported database instance.
*/
export abstract class DatabaseInstanceBase extends Resource implements IDatabaseInstance {
/**
* Import an existing database instance.
*/
public static fromDatabaseInstanceAttributes(scope: Construct, id: string, attrs: DatabaseInstanceAttributes): IDatabaseInstance {
class Import extends DatabaseInstanceBase implements IDatabaseInstance {
public readonly defaultPort = ec2.Port.tcp(attrs.port);
public readonly connections = new ec2.Connections({
securityGroups: attrs.securityGroups,
defaultPort: this.defaultPort,
});
public readonly instanceIdentifier = attrs.instanceIdentifier;
public readonly dbInstanceEndpointAddress = attrs.instanceEndpointAddress;
public readonly dbInstanceEndpointPort = Tokenization.stringifyNumber(attrs.port);
public readonly instanceEndpoint = new Endpoint(attrs.instanceEndpointAddress, attrs.port);
public readonly engine = attrs.engine;
protected enableIamAuthentication = true;
public readonly instanceResourceId = attrs.instanceResourceId;
}
return new Import(scope, id);
}
public abstract readonly instanceIdentifier: string;
public abstract readonly dbInstanceEndpointAddress: string;
public abstract readonly dbInstanceEndpointPort: string;
public abstract readonly instanceResourceId?: string;
public abstract readonly instanceEndpoint: Endpoint;
// only required because of JSII bug: https://github.com/aws/jsii/issues/2040
public abstract readonly engine?: IInstanceEngine;
protected abstract enableIamAuthentication?: boolean;
/**
* Access to network connections.
*/
public abstract readonly connections: ec2.Connections;
/**
* Add a new db proxy to this instance.
*/
public addProxy(id: string, options: DatabaseProxyOptions): DatabaseProxy {
return new DatabaseProxy(this, id, {
proxyTarget: ProxyTarget.fromInstance(this),
...options,
});
}
public grantConnect(grantee: iam.IGrantable, dbUser?: string): iam.Grant {
if (this.enableIamAuthentication === false) {
throw new Error('Cannot grant connect when IAM authentication is disabled');
}
if (!this.instanceResourceId) {
throw new Error('For imported Database Instances, instanceResourceId is required to grantConnect()');
}
if (!dbUser) {
throw new Error('For imported Database Instances, the dbUser is required to grantConnect()');
}
this.enableIamAuthentication = true;
return iam.Grant.addToPrincipal({
grantee,
actions: ['rds-db:connect'],
resourceArns: [
// The ARN of an IAM policy for IAM database access is not the same as the instance ARN, so we cannot use `this.instanceArn`.
// See https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html
Stack.of(this).formatArn({
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
service: 'rds-db',
resource: 'dbuser',
resourceName: [this.instanceResourceId, dbUser].join('/'),
}),
],
});
}
/**
* Defines a CloudWatch event rule which triggers for instance events. Use
* `rule.addEventPattern(pattern)` to specify a filter.
*/
public onEvent(id: string, options: events.OnEventOptions = {}) {
const rule = new events.Rule(this, id, options);
rule.addEventPattern({
source: ['aws.rds'],
resources: [this.instanceArn],
});
rule.addTarget(options.target);
return rule;
}
/**
* The instance arn.
*/
public get instanceArn(): string {
const commonAnComponents: ArnComponents = {
service: 'rds',
resource: 'db',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
};
const localArn = Stack.of(this).formatArn({
...commonAnComponents,
resourceName: this.instanceIdentifier,
});
return this.getResourceArnAttribute(localArn, {
...commonAnComponents,
resourceName: this.physicalName,
});
}
/**
* Renders the secret attachment target specifications.
*/
public asSecretAttachmentTarget(): secretsmanager.SecretAttachmentTargetProps {
return {
targetId: this.instanceIdentifier,
targetType: secretsmanager.AttachmentTargetType.RDS_DB_INSTANCE,
};
}
}
/**
* The license model.
*/
export enum LicenseModel {
/**
* License included.
*/
LICENSE_INCLUDED = 'license-included',
/**
* Bring your own licencse.
*/
BRING_YOUR_OWN_LICENSE = 'bring-your-own-license',
/**
* General public license.
*/
GENERAL_PUBLIC_LICENSE = 'general-public-license',
}
/**
* The processor features.
*/
export interface ProcessorFeatures {
/**
* The number of CPU core.
*
* @default - the default number of CPU cores for the chosen instance class.
*/
readonly coreCount?: number;
/**
* The number of threads per core.
*
* @default - the default number of threads per core for the chosen instance class.
*/
readonly threadsPerCore?: number;
}
/**
* The type of storage.
*
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html
*/
export enum StorageType {
/**
* Standard.
*
* Amazon RDS supports magnetic storage for backward compatibility. It is recommended to use
* General Purpose SSD or Provisioned IOPS SSD for any new storage needs.
*
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html#CHAP_Storage.Magnetic
*/
STANDARD = 'standard',
/**
* General purpose SSD (gp2).
*
* Baseline performance determined by volume size
*
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html#Concepts.Storage.GeneralSSD
*/
GP2 = 'gp2',
/**
* General purpose SSD (gp3).
*
* Performance scales independently from storage
*
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html#Concepts.Storage.GeneralSSD
*/
GP3 = 'gp3',
/**
* Provisioned IOPS SSD (io1).
*
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html#USER_PIOPS
*/
IO1 = 'io1',
/**
* Provisioned IOPS SSD (io2).
*
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html#USER_PIOPS
*/
IO2 = 'io2',
}
/**
* The network type of the DB instance.
*/
export enum NetworkType {
/**
* IPv4 only network type.
*/
IPV4 = 'IPV4',
/**
* Dual-stack network type.
*/
DUAL = 'DUAL',
}
/**
* Construction properties for a DatabaseInstanceNew
*/
export interface DatabaseInstanceNewProps {
/**
* Specifies if the database instance is a multiple Availability Zone deployment.
*
* @default false
*/
readonly multiAz?: boolean;
/**
* The name of the Availability Zone where the DB instance will be located.
*
* @default - no preference
*/
readonly availabilityZone?: string;
/**
* The storage type. Storage types supported are gp2, io1, standard.
*
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html#Concepts.Storage.GeneralSSD
*
* @default GP2
*/
readonly storageType?: StorageType;
/**
* The storage throughput, specified in mebibytes per second (MiBps).
*
* Only applicable for GP3.
*
* @see https://docs.aws.amazon.com//AmazonRDS/latest/UserGuide/CHAP_Storage.html#gp3-storage
*
* @default - 125 MiBps if allocated storage is less than 400 GiB for MariaDB, MySQL, and PostgreSQL,
* less than 200 GiB for Oracle and less than 20 GiB for SQL Server. 500 MiBps otherwise (except for
* SQL Server where the default is always 125 MiBps).
*/
readonly storageThroughput?: number;
/**
* The number of I/O operations per second (IOPS) that the database provisions.
* The value must be equal to or greater than 1000.
*
* @default - no provisioned iops if storage type is not specified. For GP3: 3,000 IOPS if allocated
* storage is less than 400 GiB for MariaDB, MySQL, and PostgreSQL, less than 200 GiB for Oracle and
* less than 20 GiB for SQL Server. 12,000 IOPS otherwise (except for SQL Server where the default is
* always 3,000 IOPS).
*/
readonly iops?: number;
/**
* The number of CPU cores and the number of threads per core.
*
* @default - the default number of CPU cores and threads per core for the
* chosen instance class.
*
* See https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.html#USER_ConfigureProcessor
*/
readonly processorFeatures?: ProcessorFeatures;
/**
* A name for the DB instance. If you specify a name, AWS CloudFormation
* converts it to lowercase.
*
* @default - a CloudFormation generated name
*/
readonly instanceIdentifier?: string;
/**
* The VPC network where the DB subnet group should be created.
*/
readonly vpc: ec2.IVpc;
/**
* The type of subnets to add to the created DB subnet group.
*
* @deprecated use `vpcSubnets`
* @default - private subnets
*/
readonly vpcPlacement?: ec2.SubnetSelection;
/**
* The type of subnets to add to the created DB subnet group.
*
* @default - private subnets
*/
readonly vpcSubnets?: ec2.SubnetSelection;
/**
* The security groups to assign to the DB instance.
*
* @default - a new security group is created
*/
readonly securityGroups?: ec2.ISecurityGroup[];
/**
* The port for the instance.
*
* @default - the default port for the chosen engine.
*/
readonly port?: number;
/**
* The DB parameter group to associate with the instance.
*
* @default - no parameter group
*/
readonly parameterGroup?: IParameterGroup;
/**
* The option group to associate with the instance.
*
* @default - no option group
*/
readonly optionGroup?: IOptionGroup;
/**
* Whether to enable mapping of AWS Identity and Access Management (IAM) accounts
* to database accounts.
*
* @default false
*/
readonly iamAuthentication?: boolean;
/**
* The number of days during which automatic DB snapshots are retained.
* Set to zero to disable backups.
* When creating a read replica, you must enable automatic backups on the source
* database instance by setting the backup retention to a value other than zero.
*
* @default - Duration.days(1) for source instances, disabled for read replicas
*/
readonly backupRetention?: Duration;
/**
* The daily time range during which automated backups are performed.
*
* Constraints:
* - Must be in the format `hh24:mi-hh24:mi`.
* - Must be in Universal Coordinated Time (UTC).
* - Must not conflict with the preferred maintenance window.
* - Must be at least 30 minutes.
*
* @default - a 30-minute window selected at random from an 8-hour block of
* time for each AWS Region. To see the time blocks available, see
* https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html#USER_WorkingWithAutomatedBackups.BackupWindow
*/
readonly preferredBackupWindow?: string;
/**
* Indicates whether to copy all of the user-defined tags from the
* DB instance to snapshots of the DB instance.
*
* @default true
*/
readonly copyTagsToSnapshot?: boolean;
/**
* Indicates whether automated backups should be deleted or retained when
* you delete a DB instance.
*
* @default true
*/
readonly deleteAutomatedBackups?: boolean;
/**
* The interval, in seconds, between points when Amazon RDS collects enhanced
* monitoring metrics for the DB instance.
*
* @default - no enhanced monitoring
*/
readonly monitoringInterval?: Duration;
/**
* Role that will be used to manage DB instance monitoring.
*
* @default - A role is automatically created for you
*/
readonly monitoringRole?: iam.IRole;
/**
* Whether to enable Performance Insights for the DB instance.
*
* @default - false, unless ``performanceInsightRetention`` or ``performanceInsightEncryptionKey`` is set.
*/
readonly enablePerformanceInsights?: boolean;
/**
* The amount of time, in days, to retain Performance Insights data.
*
* @default 7 this is the free tier
*/
readonly performanceInsightRetention?: PerformanceInsightRetention;
/**
* The AWS KMS key for encryption of Performance Insights data.
*
* @default - default master key
*/
readonly performanceInsightEncryptionKey?: kms.IKey;
/**
* The list of log types that need to be enabled for exporting to
* CloudWatch Logs.
*
* @default - no log exports
*/
readonly cloudwatchLogsExports?: string[];
/**
* The number of days log events are kept in CloudWatch Logs. When updating
* this property, unsetting it doesn't remove the log retention policy. To
* remove the retention policy, set the value to `Infinity`.
*
* @default - logs never expire
*/
readonly cloudwatchLogsRetention?: logs.RetentionDays;
/**
* The IAM role for the Lambda function associated with the custom resource
* that sets the retention policy.
*
* @default - a new role is created.
*/
readonly cloudwatchLogsRetentionRole?: iam.IRole;
/**
* Indicates that minor engine upgrades are applied automatically to the
* DB instance during the maintenance window.
*
* @default true
*/
readonly autoMinorVersionUpgrade?: boolean;
/**
* The weekly time range (in UTC) during which system maintenance can occur.
*
* Format: `ddd:hh24:mi-ddd:hh24:mi`
* Constraint: Minimum 30-minute window
*
* @default - a 30-minute window selected at random from an 8-hour block of
* time for each AWS Region, occurring on a random day of the week. To see
* the time blocks available, see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html#Concepts.DBMaintenance
*/
readonly preferredMaintenanceWindow?: string;
/**
* Indicates whether the DB instance should have deletion protection enabled.
*
* @default - true if ``removalPolicy`` is RETAIN, false otherwise
*/
readonly deletionProtection?: boolean;
/**
* The CloudFormation policy to apply when the instance is removed from the
* stack or replaced during an update.
*
* @default - RemovalPolicy.SNAPSHOT (remove the resource, but retain a snapshot of the data)
*/
readonly removalPolicy?: RemovalPolicy;
/**
* Upper limit to which RDS can scale the storage in GiB(Gibibyte).
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIOPS.StorageTypes.html#USER_PIOPS.Autoscaling
* @default - No autoscaling of RDS instance
*/
readonly maxAllocatedStorage?: number;
/**
* The Active Directory directory ID to create the DB instance in.
*
* @default - Do not join domain
*/
readonly domain?: string;
/**
* The IAM role to be used when making API calls to the Directory Service. The role needs the AWS-managed policy
* AmazonRDSDirectoryServiceAccess or equivalent.
*
* @default - The role will be created for you if `DatabaseInstanceNewProps#domain` is specified
*/
readonly domainRole?: iam.IRole;
/**
* Existing subnet group for the instance.
*
* @default - a new subnet group will be created.
*/
readonly subnetGroup?: ISubnetGroup;
/**
* Role that will be associated with this DB instance to enable S3 import.
* This feature is only supported by the Microsoft SQL Server, Oracle, and PostgreSQL engines.
*
* This property must not be used if `s3ImportBuckets` is used.
*
* For Microsoft SQL Server:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/SQLServer.Procedural.Importing.html
* For Oracle:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html
* For PostgreSQL:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL.Procedural.Importing.html
*
* @default - New role is created if `s3ImportBuckets` is set, no role is defined otherwise
*/
readonly s3ImportRole?: iam.IRole;
/**
* S3 buckets that you want to load data from.
* This feature is only supported by the Microsoft SQL Server, Oracle, and PostgreSQL engines.
*
* This property must not be used if `s3ImportRole` is used.
*
* For Microsoft SQL Server:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/SQLServer.Procedural.Importing.html
* For Oracle:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html
* For PostgreSQL:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL.Procedural.Importing.html
*
* @default - None
*/
readonly s3ImportBuckets?: s3.IBucket[];
/**
* Role that will be associated with this DB instance to enable S3 export.
*
* This property must not be used if `s3ExportBuckets` is used.
*
* For Microsoft SQL Server:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/SQLServer.Procedural.Importing.html
* For Oracle:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html
*
* @default - New role is created if `s3ExportBuckets` is set, no role is defined otherwise
*/
readonly s3ExportRole?: iam.IRole;
/**
* S3 buckets that you want to load data into.
*
* This property must not be used if `s3ExportRole` is used.
*
* For Microsoft SQL Server:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/SQLServer.Procedural.Importing.html
* For Oracle:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html
*
* @default - None
*/
readonly s3ExportBuckets?: s3.IBucket[];
/**
* Indicates whether the DB instance is an internet-facing instance. If not specified,
* the instance's vpcSubnets will be used to determine if the instance is internet-facing
* or not.
*
* @default - `true` if the instance's `vpcSubnets` is `subnetType: SubnetType.PUBLIC`, `false` otherwise
*/
readonly publiclyAccessible?: boolean;
/**
* The network type of the DB instance.
*
* @default - IPV4
*/
readonly networkType?: NetworkType;
/**
* The identifier of the CA certificate for this DB instance.
*
* Specifying or updating this property triggers a reboot.
*
* For RDS DB engines:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html
* For Aurora DB engines:
* @see https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/UsingWithRDS.SSL-certificate-rotation.html
*
* @default - RDS will choose a certificate authority
*/
readonly caCertificate?: CaCertificate;
}
/**
* A new database instance.
*/
abstract class DatabaseInstanceNew extends DatabaseInstanceBase implements IDatabaseInstance {
/**
* The VPC where this database instance is deployed.
*/
public readonly vpc: ec2.IVpc;
public readonly connections: ec2.Connections;
/**
* The log group is created when `cloudwatchLogsExports` is set.
*
* Each export value will create a separate log group.
*/
public readonly cloudwatchLogGroups: {[engine: string]: logs.ILogGroup};
protected abstract readonly instanceType: ec2.InstanceType;
protected readonly vpcPlacement?: ec2.SubnetSelection;
protected readonly newCfnProps: CfnDBInstanceProps;
private readonly cloudwatchLogsExports?: string[];
private readonly cloudwatchLogsRetention?: logs.RetentionDays;
private readonly cloudwatchLogsRetentionRole?: iam.IRole;
private readonly domainId?: string;
private readonly domainRole?: iam.IRole;
protected enableIamAuthentication?: boolean;
constructor(scope: Construct, id: string, props: DatabaseInstanceNewProps) {
// RDS always lower-cases the ID of the database, so use that for the physical name
// (which is the name used for cross-environment access, so it needs to be correct,
// regardless of the feature flag that changes it in the template for the L1)
const instancePhysicalName = Token.isUnresolved(props.instanceIdentifier)
? props.instanceIdentifier
: props.instanceIdentifier?.toLowerCase();
super(scope, id, {
physicalName: instancePhysicalName,
});
this.vpc = props.vpc;
if (props.vpcSubnets && props.vpcPlacement) {
throw new Error('Only one of `vpcSubnets` or `vpcPlacement` can be specified');
}
this.vpcPlacement = props.vpcSubnets ?? props.vpcPlacement;
if (props.multiAz === true && props.availabilityZone) {
throw new Error('Requesting a specific availability zone is not valid for Multi-AZ instances');
}
const subnetGroup = props.subnetGroup ?? new SubnetGroup(this, 'SubnetGroup', {
description: `Subnet group for ${this.node.id} database`,
vpc: this.vpc,
vpcSubnets: this.vpcPlacement,
removalPolicy: renderUnless(helperRemovalPolicy(props.removalPolicy), RemovalPolicy.DESTROY),
});
const securityGroups = props.securityGroups || [new ec2.SecurityGroup(this, 'SecurityGroup', {
description: `Security group for ${this.node.id} database`,
vpc: props.vpc,
})];
this.connections = new ec2.Connections({
securityGroups,
defaultPort: ec2.Port.tcp(Lazy.number({ produce: () => this.instanceEndpoint.port })),
});
let monitoringRole;
if (props.monitoringInterval && props.monitoringInterval.toSeconds()) {
monitoringRole = props.monitoringRole || new iam.Role(this, 'MonitoringRole', {
assumedBy: new iam.ServicePrincipal('monitoring.rds.amazonaws.com'),
managedPolicies: [iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonRDSEnhancedMonitoringRole')],
});
}
const storageType = props.storageType ?? StorageType.GP2;
const iops = defaultIops(storageType, props.iops);
if (props.storageThroughput && storageType !== StorageType.GP3) {
throw new Error(`The storage throughput can only be specified with GP3 storage type. Got ${storageType}.`);
}
if (storageType === StorageType.GP3 && props.storageThroughput && iops
&& !Token.isUnresolved(props.storageThroughput) && !Token.isUnresolved(iops)
&& props.storageThroughput/iops > 0.25) {
throw new Error(`The maximum ratio of storage throughput to IOPS is 0.25. Got ${props.storageThroughput/iops}.`);
}
this.cloudwatchLogGroups = {};
this.cloudwatchLogsExports = props.cloudwatchLogsExports;
this.cloudwatchLogsRetention = props.cloudwatchLogsRetention;
this.cloudwatchLogsRetentionRole = props.cloudwatchLogsRetentionRole;
this.enableIamAuthentication = props.iamAuthentication;
const enablePerformanceInsights = props.enablePerformanceInsights
|| props.performanceInsightRetention !== undefined || props.performanceInsightEncryptionKey !== undefined;
if (enablePerformanceInsights && props.enablePerformanceInsights === false) {
throw new Error('`enablePerformanceInsights` disabled, but `performanceInsightRetention` or `performanceInsightEncryptionKey` was set');
}
if (props.domain) {
this.domainId = props.domain;
this.domainRole = props.domainRole || new iam.Role(this, 'RDSDirectoryServiceRole', {
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 maybeLowercasedInstanceId = FeatureFlags.of(this).isEnabled(cxapi.RDS_LOWERCASE_DB_IDENTIFIER)
&& !Token.isUnresolved(props.instanceIdentifier)
? props.instanceIdentifier?.toLowerCase()
: props.instanceIdentifier;
const instanceParameterGroupConfig = props.parameterGroup?.bindToInstance({});
const isInPublicSubnet = this.vpcPlacement && this.vpcPlacement.subnetType === ec2.SubnetType.PUBLIC;
this.newCfnProps = {
autoMinorVersionUpgrade: props.autoMinorVersionUpgrade,
availabilityZone: props.multiAz ? undefined : props.availabilityZone,
backupRetentionPeriod: props.backupRetention?.toDays(),
copyTagsToSnapshot: props.copyTagsToSnapshot ?? true,
dbInstanceClass: Lazy.string({ produce: () => `db.${this.instanceType}` }),
dbInstanceIdentifier: Token.isUnresolved(props.instanceIdentifier)
// if the passed identifier is a Token,
// we need to use the physicalName of the database
// (we cannot change its case anyway),
// as it might be used in a cross-environment fashion
? this.physicalName
: maybeLowercasedInstanceId,
dbSubnetGroupName: subnetGroup.subnetGroupName,
deleteAutomatedBackups: props.deleteAutomatedBackups,
deletionProtection: defaultDeletionProtection(props.deletionProtection, props.removalPolicy),
enableCloudwatchLogsExports: this.cloudwatchLogsExports,
enableIamDatabaseAuthentication: Lazy.any({ produce: () => this.enableIamAuthentication }),
enablePerformanceInsights: enablePerformanceInsights || props.enablePerformanceInsights, // fall back to undefined if not set,
iops,
monitoringInterval: props.monitoringInterval?.toSeconds(),
monitoringRoleArn: monitoringRole?.roleArn,
multiAz: props.multiAz,
dbParameterGroupName: instanceParameterGroupConfig?.parameterGroupName,
optionGroupName: props.optionGroup?.optionGroupName,
performanceInsightsKmsKeyId: props.performanceInsightEncryptionKey?.keyArn,
performanceInsightsRetentionPeriod: enablePerformanceInsights
? (props.performanceInsightRetention || PerformanceInsightRetention.DEFAULT)
: undefined,
port: props.port !== undefined ? Tokenization.stringifyNumber(props.port) : undefined,
preferredBackupWindow: props.preferredBackupWindow,
preferredMaintenanceWindow: props.preferredMaintenanceWindow,
processorFeatures: props.processorFeatures && renderProcessorFeatures(props.processorFeatures),
publiclyAccessible: props.publiclyAccessible ?? isInPublicSubnet,
storageType,
storageThroughput: props.storageThroughput,
vpcSecurityGroups: securityGroups.map(s => s.securityGroupId),
maxAllocatedStorage: props.maxAllocatedStorage,
domain: this.domainId,
domainIamRoleName: this.domainRole?.roleName,
networkType: props.networkType,
caCertificateIdentifier: props.caCertificate ? props.caCertificate.toString() : undefined,
};
}
protected setLogRetention() {
if (this.cloudwatchLogsExports && this.cloudwatchLogsRetention) {
for (const log of this.cloudwatchLogsExports) {
const logGroupName = `/aws/rds/instance/${this.instanceIdentifier}/${log}`;
new logs.LogRetention(this, `LogRetention${log}`, {
logGroupName,
retention: this.cloudwatchLogsRetention,
role: this.cloudwatchLogsRetentionRole,
});
this.cloudwatchLogGroups[log] = logs.LogGroup.fromLogGroupName(this, `LogGroup${this.instanceIdentifier}${log}`, logGroupName);
}
}
}
}
/**
* Construction properties for a DatabaseInstanceSource
*/
export interface DatabaseInstanceSourceProps extends DatabaseInstanceNewProps {
/**
* The database engine.
*/
readonly engine: IInstanceEngine;
/**
* The name of the compute and memory capacity for the instance.
*
* @default - m5.large (or, more specifically, db.m5.large)
*/
readonly instanceType?: ec2.InstanceType;
/**
* The license model.
*
* @default - RDS default license model
*/
readonly licenseModel?: LicenseModel;
/**
* Whether to allow major version upgrades.
*
* @default false
*/
readonly allowMajorVersionUpgrade?: boolean;
/**
* The time zone of the instance. This is currently supported only by Microsoft Sql Server.
*
* @default - RDS default timezone
*/
readonly timezone?: string;
/**
* The allocated storage size, specified in gibibytes (GiB).
*
* @default 100
*/
readonly allocatedStorage?: number;
/**
* The name of the database.
*
* @default - no name
*/
readonly databaseName?: string;
/**
* The parameters in the DBParameterGroup to create automatically
*
* You can only specify parameterGroup or parameters but not both.
* You need to use a versioned engine to auto-generate a DBParameterGroup.
*
* @default - None
*/
readonly parameters?: { [key: string]: string };
}
/**
* A new source database instance (not a read replica)
*/
abstract class DatabaseInstanceSource extends DatabaseInstanceNew implements IDatabaseInstance {
public readonly engine?: IInstanceEngine;
/**
* The AWS Secrets Manager secret attached to the instance.
*/
public abstract readonly secret?: secretsmanager.ISecret;
protected readonly sourceCfnProps: CfnDBInstanceProps;
protected readonly instanceType: ec2.InstanceType;
private readonly singleUserRotationApplication: secretsmanager.SecretRotationApplication;
private readonly multiUserRotationApplication: secretsmanager.SecretRotationApplication;