-
Notifications
You must be signed in to change notification settings - Fork 4k
/
instance.ts
377 lines (331 loc) · 10.5 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
import * as iam from '@aws-cdk/aws-iam';
import { Construct, Duration, Fn, IResource, Lazy, Resource, Tag } from '@aws-cdk/core';
import { Connections, IConnectable } from './connections';
import { CfnInstance } from './ec2.generated';
import { InstanceType } from './instance-types';
import { IMachineImage, OperatingSystemType } from './machine-image';
import { ISecurityGroup, SecurityGroup } from './security-group';
import { UserData } from './user-data';
import { BlockDevice, synthesizeBlockDeviceMappings } from './volume';
import { IVpc, Subnet, SubnetSelection } from './vpc';
/**
* Name tag constant
*/
const NAME_TAG: string = 'Name';
export interface IInstance extends IResource, IConnectable, iam.IGrantable {
/**
* 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.
*/
readonly keyName?: string;
/**
* 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;
/**
* 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;
/**
* 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`:
*
* @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 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
}
/**
* This represents a single EC2 instance
*/
export class Instance extends Resource implements IInstance {
/**
* 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
*/
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);
if (props.securityGroup) {
this.securityGroup = props.securityGroup;
} else {
this.securityGroup = new SecurityGroup(this, 'InstanceSecurityGroup', {
vpc: props.vpc,
allowAllOutbound: props.allowAllOutbound !== false,
});
}
this.connections = new Connections({ securityGroups: [this.securityGroup] });
this.securityGroups.push(this.securityGroup);
Tag.add(this, NAME_TAG, props.instanceName || this.node.path);
this.role = props.role || new iam.Role(this, 'InstanceRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});
this.grantPrincipal = this.role;
const iamProfile = new iam.CfnInstanceProfile(this, 'InstanceProfile', {
roles: [this.role.roleName],
});
// use delayed evaluation
const imageConfig = props.machineImage.getImage(this);
this.userData = props.userData ?? imageConfig.userData;
const userDataToken = Lazy.stringValue({ produce: () => Fn.base64(this.userData.render()) });
const securityGroupsToken = Lazy.listValue({ produce: () => this.securityGroups.map(sg => sg.securityGroupId) });
const { subnets } = 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 {
this.node.addError(`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 {
this.node.addError(`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',
});
}
this.instance = new CfnInstance(this, 'Resource', {
imageId: imageConfig.imageId,
keyName: props.keyName,
instanceType: props.instanceType.toString(),
securityGroupIds: securityGroupsToken,
iamInstanceProfile: iamProfile.ref,
userData: userDataToken,
subnetId: subnet.subnetId,
availabilityZone: subnet.availabilityZone,
sourceDestCheck: props.sourceDestCheck,
blockDeviceMappings: props.blockDevices !== undefined ? synthesizeBlockDeviceMappings(this, props.blockDevices) : undefined,
privateIpAddress: props.privateIpAddress,
});
this.instance.node.addDependency(this.role);
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;
this.applyUpdatePolicies(props);
}
/**
* Add the security group to the instance.
*
* @param securityGroup: The security group to add
*/
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).
*/
public addUserData(...commands: string[]) {
this.userData.addCommands(...commands);
}
/**
* Adds a statement to the IAM role assumed by the instance.
*/
public addToRolePolicy(statement: iam.PolicyStatement) {
this.role.addToPolicy(statement);
}
/**
* Apply CloudFormation update policies for the instance
*/
private applyUpdatePolicies(props: InstanceProps) {
if (props.resourceSignalTimeout !== undefined) {
this.instance.cfnOptions.creationPolicy = {
...this.instance.cfnOptions.creationPolicy,
resourceSignal: {
timeout: props.resourceSignalTimeout && props.resourceSignalTimeout.toISOString(),
},
};
}
}
}