-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathinstance.ts
More file actions
1002 lines (900 loc) · 35.6 KB
/
instance.ts
File metadata and controls
1002 lines (900 loc) · 35.6 KB
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 type { Construct } from 'constructs';
import { InstanceRequireImdsv2Aspect } from './aspects';
import type { CloudFormationInit } from './cfn-init';
import type { IConnectable } from './connections';
import { Connections } from './connections';
import type { IInstanceRef, InstanceReference, IPlacementGroupRef } from './ec2.generated';
import { CfnInstance } from './ec2.generated';
import type { InstanceType } from './instance-types';
import type { IKeyPair } from './key-pair';
import type { CpuCredits, InstanceInitiatedShutdownBehavior } from './launch-template';
import type { IMachineImage, OperatingSystemType } from './machine-image';
import { instanceBlockDeviceMappings } from './private/ebs-util';
import type { ISecurityGroup } from './security-group';
import { SecurityGroup } from './security-group';
import type { UserData } from './user-data';
import type { BlockDevice } from './volume';
import type { IVpc, SubnetSelection } from './vpc';
import { Subnet } from './vpc';
import * as iam from '../../aws-iam';
import type { IResource } from '../../core';
import {
Annotations,
Aspects,
Duration,
FeatureFlags,
Fn,
Lazy,
Resource,
Stack,
Tags,
Token,
ValidationError,
} from '../../core';
import { md5hash } from '../../core/lib/helpers-internal';
import { addConstructMetadata, MethodMetadata } from '../../core/lib/metadata-resource';
import { mutatingAspectPrio32333 } from '../../core/lib/private/aspect-prio';
import { propertyInjectable } from '../../core/lib/prop-injectable';
import * as cxapi from '../../cx-api';
/**
* The state of token usage for your instance metadata requests.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-metadataoptions.html#cfn-ec2-instance-metadataoptions-httptokens
*/
export enum HttpTokens {
/**
* If the state is optional, you can choose to retrieve instance metadata with or without a signed token header on your request.
*/
OPTIONAL = 'optional',
/**
* If the state is required, you must send a signed token header with any instance metadata retrieval requests. In this state,
* retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available.
*/
REQUIRED = 'required',
}
/**
* Name tag constant
*/
const NAME_TAG: string = 'Name';
export interface IInstance extends IResource, IConnectable, iam.IGrantable, IInstanceRef {
/**
* The instance's ID
*
* @attribute
*/
readonly instanceId: string;
/**
* The availability zone the instance was launched in
*
* @attribute
*/
readonly instanceAvailabilityZone: string;
/**
* Private DNS name for this instance
* @attribute
*/
readonly instancePrivateDnsName: string;
/**
* Private IP for this instance
*
* @attribute
*/
readonly instancePrivateIp: string;
/**
* Publicly-routable DNS name for this instance.
*
* (May be an empty string if the instance does not have a public name).
*
* @attribute
*/
readonly instancePublicDnsName: string;
/**
* Publicly-routable IP address for this instance.
*
* (May be an empty string if the instance does not have a public IP).
*
* @attribute
*/
readonly instancePublicIp: string;
}
/**
* Properties of an EC2 Instance
*/
export interface InstanceProps {
/**
* Name of SSH keypair to grant access to instance
*
* @default - No SSH access will be possible.
* @deprecated - Use `keyPair` instead - https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2-readme.html#using-an-existing-ec2-key-pair
*/
readonly keyName?: string;
/**
* The SSH keypair to grant access to the instance.
*
* @default - No SSH access will be possible.
*/
readonly keyPair?: IKeyPair;
/**
* Where to place the instance within the VPC
*
* @default - Private subnets.
*/
readonly vpcSubnets?: SubnetSelection;
/**
* In which AZ to place the instance within the VPC
*
* @default - Random zone.
*/
readonly availabilityZone?: string;
/**
* Whether the instance could initiate connections to anywhere by default.
* This property is only used when you do not provide a security group.
*
* @default true
*/
readonly allowAllOutbound?: boolean;
/**
* Whether the instance could initiate IPv6 connections to anywhere by default.
* This property is only used when you do not provide a security group.
*
* @default false
*/
readonly allowAllIpv6Outbound?: boolean;
/**
* The length of time to wait for the resourceSignalCount
*
* The maximum value is 43200 (12 hours).
*
* @default Duration.minutes(5)
*/
readonly resourceSignalTimeout?: Duration;
/**
* VPC to launch the instance in.
*/
readonly vpc: IVpc;
/**
* Security Group to assign to this instance
*
* @default - create new security group
*/
readonly securityGroup?: ISecurityGroup;
/**
* Type of instance to launch
*/
readonly instanceType: InstanceType;
/**
* AMI to launch
*/
readonly machineImage: IMachineImage;
/**
* Specific UserData to use
*
* The UserData may still be mutated after creation.
*
* @default - A UserData object appropriate for the MachineImage's
* Operating System is created.
*/
readonly userData?: UserData;
/**
* Changes to the UserData force replacement
*
* Depending the EC2 instance type, changing UserData either
* restarts the instance or replaces the instance.
*
* - Instance store-backed instances are replaced.
* - EBS-backed instances are restarted.
*
* By default, restarting does not execute the new UserData so you
* will need a different mechanism to ensure the instance is restarted.
*
* Setting this to `true` will make the instance's Logical ID depend on the
* UserData, which will cause CloudFormation to replace it if the UserData
* changes.
*
* @default - true if `initOptions` is specified, false otherwise.
*/
readonly userDataCausesReplacement?: boolean;
/**
* An IAM role to associate with the instance profile assigned to this Auto Scaling Group.
*
* The role must be assumable by the service principal `ec2.amazonaws.com`:
* Note: You can provide an instanceProfile or a role, but not both.
*
* @example
* const role = new iam.Role(this, 'MyRole', {
* assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
* });
*
* @default - A role will automatically be created, it can be accessed via the `role` property
*/
readonly role?: iam.IRole;
/**
* The instance profile used to pass role information to EC2 instances.
*
* Note: You can provide an instanceProfile or a role, but not both.
*
* @default - No instance profile
*/
readonly instanceProfile?: iam.IInstanceProfile;
/**
* The name of the instance
*
* @default - CDK generated name
*/
readonly instanceName?: string;
/**
* Specifies whether to enable an instance launched in a VPC to perform NAT.
* This controls whether source/destination checking is enabled on the instance.
* A value of true means that checking is enabled, and false means that checking is disabled.
* The value must be false for the instance to perform NAT.
*
* @default true
*/
readonly sourceDestCheck?: boolean;
/**
* Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes.
*
* Each instance that is launched has an associated root device volume,
* either an Amazon EBS volume or an instance store volume.
* You can use block device mappings to specify additional EBS volumes or
* instance store volumes to attach to an instance when it is launched.
*
* @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html
*
* @default - Uses the block device mapping of the AMI
*/
readonly blockDevices?: BlockDevice[];
/**
* Defines a private IP address to associate with an instance.
*
* Private IP should be available within the VPC that the instance is build within.
*
* @default - no association
*/
readonly privateIpAddress?: string;
/**
* Propagate the EC2 instance tags to the EBS volumes.
*
* @default - false
*/
readonly propagateTagsToVolumeOnCreation?: boolean;
/**
* Apply the given CloudFormation Init configuration to the instance at startup
*
* @default - no CloudFormation init
*/
readonly init?: CloudFormationInit;
/**
* Use the given options for applying CloudFormation Init
*
* Describes the configsets to use and the timeout to wait
*
* @default - default options
*/
readonly initOptions?: ApplyCloudFormationInitOptions;
/**
* Whether IMDSv2 should be required on this instance.
*
* This is a simple boolean flag that enforces IMDSv2 by creating a Launch Template
* with `httpTokens: 'required'`. Use this for straightforward IMDSv2 enforcement.
*
* For more granular control over metadata options (like disabling the metadata endpoint,
* configuring hop limits, or enabling instance tags), use the individual metadata option properties instead.
*
* @default - false
*/
readonly requireImdsv2?: boolean;
/**
* Enables or disables the HTTP metadata endpoint on your instances.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-metadataoptions.html#cfn-ec2-instance-metadataoptions-httpendpoint
*
* @default true
*/
readonly httpEndpoint?: boolean;
/**
* Enables or disables the IPv6 endpoint for the instance metadata service.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-metadataoptions.html#cfn-ec2-instance-metadataoptions-httpprotocolipv6
*
* @default false
*/
readonly httpProtocolIpv6?: boolean;
/**
* The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel.
*
* Possible values: Integers from 1 to 64
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-metadataoptions.html#cfn-ec2-instance-metadataoptions-httpputresponsehoplimit
*
* @default - No default value specified by CloudFormation
*/
readonly httpPutResponseHopLimit?: number;
/**
* The state of token usage for your instance metadata requests.
*
* Set to 'required' to enforce IMDSv2. This is equivalent to using `requireImdsv2: true`,
* but allows you to configure other metadata options alongside IMDSv2 enforcement.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-metadataoptions.html#cfn-ec2-instance-metadataoptions-httptokens
*
* @default - The default is conditional based on the AMI and account-level settings:
* - If the AMI's `ImdsSupport` is `v2.0` and the account level default is `no-preference`, the default is `HttpTokens.REQUIRED`
* - If the AMI's `ImdsSupport` is `v2.0` and the account level default is `V1 or V2`, the default is `HttpTokens.OPTIONAL`
* - See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-options.html#instance-metadata-options-order-of-precedence
*/
readonly httpTokens?: HttpTokens;
/**
* Set to enabled to allow access to instance tags from the instance metadata. Set to disabled to turn off access to instance tags from the instance metadata.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-metadataoptions.html#cfn-ec2-instance-metadataoptions-instancemetadatatags
*
* @default false
*/
readonly instanceMetadataTags?: boolean;
/**
* Whether "Detailed Monitoring" is enabled for this instance
* Keep in mind that Detailed Monitoring results in extra charges
*
* @see https://aws.amazon.com/cloudwatch/pricing/
* @default - false
*/
readonly detailedMonitoring?: boolean;
/**
* Add SSM session permissions to the instance role
*
* Setting this to `true` adds the necessary permissions to connect
* to the instance using SSM Session Manager. You can do this
* from the AWS Console.
*
* NOTE: Setting this flag to `true` may not be enough by itself.
* You must also use an AMI that comes with the SSM Agent, or install
* the SSM Agent yourself. See
* [Working with SSM Agent](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html)
* in the SSM Developer Guide.
*
* @default false
*/
readonly ssmSessionPermissions?: boolean;
/**
* Whether to associate a public IP address to the primary network interface attached to this instance.
*
* You cannot specify this property and `ipv6AddressCount` at the same time.
*
* @default - public IP address is automatically assigned based on default behavior
*/
readonly associatePublicIpAddress?: boolean;
/**
* Specifying the CPU credit type for burstable EC2 instance types (T2, T3, T3a, etc).
* The unlimited CPU credit option is not supported for T3 instances with a dedicated host.
*
* @default - T2 instances are standard, while T3, T4g, and T3a instances are unlimited.
*/
readonly creditSpecification?: CpuCredits;
/**
* Indicates whether the instance is optimized for Amazon EBS I/O.
*
* This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance.
* This optimization isn't available with all instance types.
* Additional usage charges apply when using an EBS-optimized instance.
*
* @default false
*/
readonly ebsOptimized?: boolean;
/**
* If true, the instance will not be able to be terminated using the Amazon EC2 console, CLI, or API.
*
* To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html).
* Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate, you can terminate the instance
* by running the shutdown command from the instance.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-instance.html#cfn-ec2-instance-disableapitermination
*
* @default false
*/
readonly disableApiTermination?: boolean;
/**
* Indicates whether an instance stops or terminates when you initiate shutdown from the instance
* (using the operating system command for system shutdown).
*
* @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#Using_ChangingInstanceInitiatedShutdownBehavior
*
* @default InstanceInitiatedShutdownBehavior.STOP
*/
readonly instanceInitiatedShutdownBehavior?: InstanceInitiatedShutdownBehavior;
/**
* The placement group that you want to launch the instance into.
*
* @default - no placement group will be used for this instance.
*/
readonly placementGroup?: IPlacementGroupRef;
/**
* Whether the instance is enabled for AWS Nitro Enclaves.
*
* Nitro Enclaves requires a Nitro-based virtualized parent instance with specific Intel/AMD with at least 4 vCPUs
* or Graviton with at least 2 vCPUs instance types and Linux/Windows host OS,
* while the enclave itself supports only Linux OS.
*
* You can't set both `enclaveEnabled` and `hibernationEnabled` to true on the same instance.
*
* @see https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html#nitro-enclave-reqs
*
* @default - false
*/
readonly enclaveEnabled?: boolean;
/**
* Whether the instance is enabled for hibernation.
*
* You can't set both `enclaveEnabled` and `hibernationEnabled` to true on the same instance.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-hibernationoptions.html
*
* @default - false
*/
readonly hibernationEnabled?: boolean;
/**
* The number of IPv6 addresses to associate with the primary network interface.
*
* Amazon EC2 chooses the IPv6 addresses from the range of your subnet.
*
* You cannot specify this property and `associatePublicIpAddress` at the same time.
*
* @default - For instances associated with an IPv6 subnet, use 1; otherwise, use 0.
*/
readonly ipv6AddressCount?: number;
}
/**
* This represents a single EC2 instance
*/
@propertyInjectable
export class Instance extends Resource implements IInstance {
/**
* Uniquely identifies this class.
*/
public static readonly PROPERTY_INJECTION_ID: string = 'aws-cdk-lib.aws-ec2.Instance';
/**
* The type of OS the instance is running.
*/
public readonly osType: OperatingSystemType;
/**
* Allows specify security group connections for the instance.
*/
public readonly connections: Connections;
/**
* The IAM role assumed by the instance.
*/
public readonly role: iam.IRole;
/**
* The principal to grant permissions to
*/
public readonly grantPrincipal: iam.IPrincipal;
/**
* UserData for the instance
*/
public readonly userData: UserData;
/**
* the underlying instance resource
*
* @jsii suppress JSII5019 For historic reasons
*/
public readonly instance: CfnInstance;
/**
* @attribute
*/
public readonly instanceId: string;
/**
* @attribute
*/
public readonly instanceAvailabilityZone: string;
/**
* @attribute
*/
public readonly instancePrivateDnsName: string;
/**
* @attribute
*/
public readonly instancePrivateIp: string;
/**
* @attribute
*/
public readonly instancePublicDnsName: string;
/**
* @attribute
*/
public readonly instancePublicIp: string;
private readonly securityGroup: ISecurityGroup;
private readonly securityGroups: ISecurityGroup[] = [];
constructor(scope: Construct, id: string, props: InstanceProps) {
super(scope, id);
// Enhanced CDK Analytics Telemetry
addConstructMetadata(this, props);
if (props.initOptions && !props.init) {
throw new ValidationError('RequiresSettingInitoptionsRequires', 'Setting \'initOptions\' requires that \'init\' is also set', this);
}
if (props.keyName && props.keyPair) {
throw new ValidationError('CannotSpecifyKeyNameKey', 'Cannot specify both of \'keyName\' and \'keyPair\'; prefer \'keyPair\'', this);
}
// if credit specification is set, then the instance type must be burstable
if (props.creditSpecification && !props.instanceType.isBurstable()) {
throw new ValidationError('CreditSpecificationSupportedInstanceType', `creditSpecification is supported only for T4g, T3a, T3, T2 instance type, got: ${props.instanceType.toString()}`, this);
}
if (props.securityGroup) {
this.securityGroup = props.securityGroup;
} else {
this.securityGroup = new SecurityGroup(this, 'InstanceSecurityGroup', {
vpc: props.vpc,
allowAllOutbound: props.allowAllOutbound !== false,
allowAllIpv6Outbound: props.allowAllIpv6Outbound,
});
}
this.connections = new Connections({ securityGroups: [this.securityGroup] });
this.securityGroups.push(this.securityGroup);
Tags.of(this).add(NAME_TAG, props.instanceName || this.node.path);
if (props.instanceProfile && props.role) {
throw new ValidationError('CannotProvideInstanceProfileRole', 'You cannot provide both instanceProfile and role', this);
}
let iamInstanceProfile: string | undefined = undefined;
if (props.instanceProfile?.role) {
this.role = props.instanceProfile.role;
iamInstanceProfile = props.instanceProfile.instanceProfileName;
} else {
this.role = props.role || new iam.Role(this, 'InstanceRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});
const iamProfile = new iam.CfnInstanceProfile(this, 'InstanceProfile', {
roles: [this.role.roleName],
});
iamInstanceProfile = iamProfile.ref;
}
this.grantPrincipal = this.role;
if (props.ssmSessionPermissions) {
this.role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMManagedInstanceCore'));
}
// use delayed evaluation
const imageConfig = props.machineImage.getImage(this);
this.userData = props.userData ?? imageConfig.userData;
const userDataToken = Lazy.string({ produce: () => Fn.base64(this.userData.render()) });
const securityGroupsToken = Lazy.list({ produce: () => this.securityGroups.map(sg => sg.securityGroupId) });
const { subnets, hasPublic } = props.vpc.selectSubnets(props.vpcSubnets);
let subnet;
if (props.availabilityZone) {
const selected = subnets.filter(sn => sn.availabilityZone === props.availabilityZone);
if (selected.length === 1) {
subnet = selected[0];
} else {
Annotations.of(this)._addTrackableError('AmbiguousSubnetForAz', `Need exactly 1 subnet to match AZ '${props.availabilityZone}', found ${selected.length}. Use a different availabilityZone.`);
}
} else {
if (subnets.length > 0) {
subnet = subnets[0];
} else {
Annotations.of(this)._addTrackableError('NoMatchingSubnets', `Did not find any subnets matching '${JSON.stringify(props.vpcSubnets)}', please use a different selection.`);
}
}
if (!subnet) {
// We got here and we don't have a subnet because of validation errors.
// Invent one on the spot so the code below doesn't fail.
subnet = Subnet.fromSubnetAttributes(this, 'DummySubnet', {
subnetId: 's-notfound',
availabilityZone: 'az-notfound',
});
}
// network interfaces array is set to configure the primary network interface if associatePublicIpAddress is true or false
const networkInterfaces = props.associatePublicIpAddress !== undefined
? [{
deviceIndex: '0',
associatePublicIpAddress: props.associatePublicIpAddress,
subnetId: subnet.subnetId,
groupSet: securityGroupsToken,
privateIpAddress: props.privateIpAddress,
}] : undefined;
if (props.keyPair && !props.keyPair._isOsCompatible(imageConfig.osType)) {
throw new ValidationError('IncompatibleKeyPairType', `${props.keyPair.type} keys are not compatible with the chosen AMI`, this);
}
if (props.enclaveEnabled && props.hibernationEnabled) {
throw new ValidationError('CanTBothTrueSame', 'You can\'t set both `enclaveEnabled` and `hibernationEnabled` to true on the same instance', this);
}
if (
props.ipv6AddressCount !== undefined &&
!Token.isUnresolved(props.ipv6AddressCount) &&
(props.ipv6AddressCount < 0 || !Number.isInteger(props.ipv6AddressCount))
) {
throw new ValidationError('MustBeIpv6addresscountNonNegativeInteger', `\'ipv6AddressCount\' must be a non-negative integer, got: ${props.ipv6AddressCount}`, this);
}
if (
props.ipv6AddressCount !== undefined &&
props.associatePublicIpAddress !== undefined) {
throw new ValidationError('SetIpvAddressCountAssociate', 'You can\'t set both \'ipv6AddressCount\' and \'associatePublicIpAddress\'', this);
}
// if network interfaces array is configured then subnetId, securityGroupIds,
// and privateIpAddress are configured on the network interface level and
// there is no need to configure them on the instance level
this.instance = new CfnInstance(this, 'Resource', {
imageId: imageConfig.imageId,
keyName: props.keyPair?.keyPairName ?? props?.keyName,
instanceType: props.instanceType.toString(),
subnetId: networkInterfaces ? undefined : subnet.subnetId,
securityGroupIds: networkInterfaces ? undefined : securityGroupsToken,
networkInterfaces,
iamInstanceProfile,
userData: userDataToken,
availabilityZone: subnet.availabilityZone,
sourceDestCheck: props.sourceDestCheck,
blockDeviceMappings: props.blockDevices !== undefined ? instanceBlockDeviceMappings(this, props.blockDevices) : undefined,
privateIpAddress: networkInterfaces ? undefined : props.privateIpAddress,
propagateTagsToVolumeOnCreation: props.propagateTagsToVolumeOnCreation,
monitoring: props.detailedMonitoring,
creditSpecification: props.creditSpecification ? { cpuCredits: props.creditSpecification } : undefined,
ebsOptimized: props.ebsOptimized,
disableApiTermination: props.disableApiTermination,
instanceInitiatedShutdownBehavior: props.instanceInitiatedShutdownBehavior,
placementGroupName: props.placementGroup?.placementGroupRef.groupName,
enclaveOptions: props.enclaveEnabled !== undefined ? { enabled: props.enclaveEnabled } : undefined,
hibernationOptions: props.hibernationEnabled !== undefined ? { configured: props.hibernationEnabled } : undefined,
ipv6AddressCount: props.ipv6AddressCount,
metadataOptions: this.renderMetadataOptions(props),
});
this.instance.node.addDependency(this.role);
// if associatePublicIpAddress is true, then there must be a dependency on internet connectivity
if (props.associatePublicIpAddress !== undefined && props.associatePublicIpAddress) {
const internetConnected = props.vpc.selectSubnets(props.vpcSubnets).internetConnectivityEstablished;
this.instance.node.addDependency(internetConnected);
}
if (!hasPublic && props.associatePublicIpAddress) {
throw new ValidationError('SetAssociatePublicIpAddress', "To set 'associatePublicIpAddress: true' you must select Public subnets (vpcSubnets: { subnetType: SubnetType.PUBLIC })", this);
}
this.osType = imageConfig.osType;
this.node.defaultChild = this.instance;
this.instanceId = this.instance.ref;
this.instanceAvailabilityZone = this.instance.attrAvailabilityZone;
this.instancePrivateDnsName = this.instance.attrPrivateDnsName;
this.instancePrivateIp = this.instance.attrPrivateIp;
this.instancePublicDnsName = this.instance.attrPublicDnsName;
this.instancePublicIp = this.instance.attrPublicIp;
// When feature flag is true, if both the resourceSignalTimeout and initOptions.timeout are set,
// the timeout is summed together. This logic is done in applyCloudFormationInit.
// This is because applyUpdatePolicies overwrites the timeout when both timeout fields are specified.
if (FeatureFlags.of(this).isEnabled(cxapi.EC2_SUM_TIMEOUT_ENABLED)) {
this.applyUpdatePolicies(props);
if (props.init) {
this.applyCloudFormationInit(props.init, props.initOptions);
}
} else {
if (props.init) {
this.applyCloudFormationInit(props.init, props.initOptions);
}
this.applyUpdatePolicies(props);
}
// Trigger replacement (via new logical ID) on user data change, if specified or cfn-init is being used.
//
// This is slightly tricky -- we need to resolve the UserData string (in order to get at actual Asset hashes,
// instead of the Token stringifications of them ('${Token[1234]}'). However, in the case of CFN Init usage,
// a UserData is going to contain the logicalID of the resource itself, which means infinite recursion if we
// try to naively resolve. We need a recursion breaker in this.
const originalLogicalId = Stack.of(this).getLogicalId(this.instance);
let recursing = false;
this.instance.overrideLogicalId(Lazy.uncachedString({
produce: (context) => {
if (recursing) { return originalLogicalId; }
if (!(props.userDataCausesReplacement ?? props.initOptions)) { return originalLogicalId; }
const fragments = new Array<string>();
recursing = true;
try {
fragments.push(JSON.stringify(context.resolve(this.userData.render())));
} finally {
recursing = false;
}
const digest = md5hash(fragments.join('')).slice(0, 16);
return `${originalLogicalId}${digest}`;
},
}));
if (props.requireImdsv2) {
Aspects.of(this).add(new InstanceRequireImdsv2Aspect(), {
priority: mutatingAspectPrio32333(this),
});
}
}
public get instanceRef(): InstanceReference {
return {
instanceId: this.instanceId,
};
}
/**
* Add the security group to the instance.
*
* @param securityGroup: The security group to add
*/
@MethodMetadata()
public addSecurityGroup(securityGroup: ISecurityGroup): void {
this.securityGroups.push(securityGroup);
}
/**
* Add command to the startup script of the instance.
* The command must be in the scripting language supported by the instance's OS (i.e. Linux/Windows).
*/
@MethodMetadata()
public addUserData(...commands: string[]) {
this.userData.addCommands(...commands);
}
/**
* Adds a statement to the IAM role assumed by the instance.
*/
@MethodMetadata()
public addToRolePolicy(statement: iam.PolicyStatement) {
this.role.addToPrincipalPolicy(statement);
}
/**
* Use a CloudFormation Init configuration at instance startup
*
* This does the following:
*
* - Attaches the CloudFormation Init metadata to the Instance resource.
* - Add commands to the instance UserData to run `cfn-init` and `cfn-signal`.
* - Update the instance's CreationPolicy to wait for the `cfn-signal` commands.
*/
@MethodMetadata()
public applyCloudFormationInit(init: CloudFormationInit, options: ApplyCloudFormationInitOptions = {}) {
init.attach(this.instance, {
platform: this.osType,
instanceRole: this.role,
userData: this.userData,
configSets: options.configSets,
embedFingerprint: options.embedFingerprint,
printLog: options.printLog,
ignoreFailures: options.ignoreFailures,
includeRole: options.includeRole,
includeUrl: options.includeUrl,
});
this.waitForResourceSignal(options.timeout ?? Duration.minutes(5));
}
/**
* Wait for a single additional resource signal
*
* Add 1 to the current ResourceSignal Count and add the given timeout to the current timeout.
*
* Use this to pause the CloudFormation deployment to wait for the instances
* in the AutoScalingGroup to report successful startup during
* creation and updates. The UserData script needs to invoke `cfn-signal`
* with a success or failure code after it is done setting up the instance.
*/
private waitForResourceSignal(timeout: Duration) {
const oldResourceSignal = this.instance.cfnOptions.creationPolicy?.resourceSignal;
this.instance.cfnOptions.creationPolicy = {
...this.instance.cfnOptions.creationPolicy,
resourceSignal: {
count: (oldResourceSignal?.count ?? 0) + 1,
timeout: (oldResourceSignal?.timeout ? Duration.parse(oldResourceSignal?.timeout).plus(timeout) : timeout).toIsoString(),
},
};
}
/**
* Apply CloudFormation update policies for the instance
*/
private applyUpdatePolicies(props: InstanceProps) {
if (props.resourceSignalTimeout !== undefined) {
this.instance.cfnOptions.creationPolicy = {
...this.instance.cfnOptions.creationPolicy,
resourceSignal: {
...this.instance.cfnOptions.creationPolicy?.resourceSignal,
timeout: props.resourceSignalTimeout && props.resourceSignalTimeout.toIsoString(),
},
};
}
}
/**
* Render the metadata options for the instance
*/
private renderMetadataOptions(props: InstanceProps): CfnInstance.MetadataOptionsProperty | undefined {
// Check if any metadata options are actually specified
// This matches the LaunchTemplate behavior
if (props.httpEndpoint === undefined &&
props.httpProtocolIpv6 === undefined &&
props.httpPutResponseHopLimit === undefined &&
props.httpTokens === undefined &&
props.instanceMetadataTags === undefined) {
return undefined;
}
// CloudFormation constraint: An EC2 instance cannot have metadata options specified both
// directly on the instance AND in an associated Launch Template. The requireImdsv2 property
// works by creating a Launch Template with httpTokens='required', while metadata options
// are set directly on the instance. Using both would result in a CloudFormation
// deployment error, so we prevent this combination at synthesis time.
if (props.requireImdsv2) {
throw new ValidationError('CannotRequireImdsvMetadataOptions', 'Cannot use both requireImdsv2 and metadata options. Use requireImdsv2 for simple IMDSv2 enforcement or individual metadata option properties for advanced configuration, but not both.', this);
}
// Validate httpPutResponseHopLimit range
if (props.httpPutResponseHopLimit !== undefined &&
(props.httpPutResponseHopLimit < 1 || props.httpPutResponseHopLimit > 64)) {
throw new ValidationError('HttpPutResponseHopLimit', 'httpPutResponseHopLimit must be between 1 and 64', this);
}
return {
httpEndpoint: props.httpEndpoint === true ? 'enabled' :
props.httpEndpoint === false ? 'disabled' : undefined,
httpProtocolIpv6: props.httpProtocolIpv6 === true ? 'enabled' :
props.httpProtocolIpv6 === false ? 'disabled' : undefined,
httpPutResponseHopLimit: props.httpPutResponseHopLimit,
httpTokens: props.httpTokens,
instanceMetadataTags: props.instanceMetadataTags === true ? 'enabled' :
props.instanceMetadataTags === false ? 'disabled' : undefined,
};
}
}
/**
* Options for applying CloudFormation init to an instance or instance group
*/
export interface ApplyCloudFormationInitOptions {
/**
* ConfigSet to activate
*
* @default ['default']
*/
readonly configSets?: string[];
/**
* Timeout waiting for the configuration to be applied
*
* @default Duration.minutes(5)
*/
readonly timeout?: Duration;
/**
* Force instance replacement by embedding a config fingerprint
*
* If `true` (the default), a hash of the config will be embedded into the
* UserData, so that if the config changes, the UserData changes.
*
* - If the EC2 instance is instance-store backed or
* `userDataCausesReplacement` is set, this will cause the instance to be
* replaced and the new configuration to be applied.
* - If the instance is EBS-backed and `userDataCausesReplacement` is not
* set, the change of UserData will make the instance restart but not be
* replaced, and the configuration will not be applied automatically.
*
* If `false`, no hash will be embedded, and if the CloudFormation Init
* config changes nothing will happen to the running instance. If a
* config update introduces errors, you will not notice until after the
* CloudFormation deployment successfully finishes and the next instance
* fails to launch.
*
* @default true
*/
readonly embedFingerprint?: boolean;
/**
* Print the results of running cfn-init to the Instance System Log
*
* By default, the output of running cfn-init is written to a log file
* on the instance. Set this to `true` to print it to the System Log
* (visible from the EC2 Console), `false` to not print it.
*
* (Be aware that the system log is refreshed at certain points in
* time of the instance life cycle, and successful execution may
* not always show up).
*
* @default true
*/
readonly printLog?: boolean;
/**
* Don't fail the instance creation when cfn-init fails
*
* You can use this to prevent CloudFormation from rolling back when
* instances fail to start up, to help in debugging.
*
* @default false
*/
readonly ignoreFailures?: boolean;
/**
* Include --url argument when running cfn-init and cfn-signal commands
*
* This will be the cloudformation endpoint in the deployed region
* e.g. https://cloudformation.us-east-1.amazonaws.com
*
* @default false
*/
readonly includeUrl?: boolean;
/**
* Include --role argument when running cfn-init and cfn-signal commands
*
* This will be the IAM instance profile attached to the EC2 instance
*
* @default false
*/