-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
run-task.ts
461 lines (406 loc) · 15 KB
/
run-task.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
import { Construct } from 'constructs';
import { ContainerOverride } from '..';
import * as ec2 from '../../../aws-ec2';
import * as ecs from '../../../aws-ecs';
import * as iam from '../../../aws-iam';
import * as sfn from '../../../aws-stepfunctions';
import * as cdk from '../../../core';
import * as cxapi from '../../../cx-api';
import { integrationResourceArn, validatePatternSupported } from '../private/task-utils';
/**
* Properties for ECS Tasks
*/
export interface EcsRunTaskProps extends sfn.TaskStateBaseProps {
/**
* The ECS cluster to run the task on
*/
readonly cluster: ecs.ICluster;
/**
* [disable-awslint:ref-via-interface]
* Task Definition used for running tasks in the service.
*
* Note: this must be TaskDefinition, and not ITaskDefinition,
* as it requires properties that are not known for imported task definitions
* If you want to run a RunTask with an imported task definition,
* consider using CustomState
*/
readonly taskDefinition: ecs.TaskDefinition;
/**
* The revision number of ECS task definition family
*
* @default - '$latest'
*/
readonly revisionNumber?: number;
/**
* Container setting overrides
*
* Specify the container to use and the overrides to apply.
*
* @default - No overrides
*/
readonly containerOverrides?: ContainerOverride[];
/**
* Subnets to place the task's ENIs
*
* @default - Public subnets if assignPublicIp is set. Private subnets otherwise.
*/
readonly subnets?: ec2.SubnetSelection;
/**
* Existing security groups to use for the tasks
*
* @default - A new security group is created
*/
readonly securityGroups?: ec2.ISecurityGroup[];
/**
* Assign public IP addresses to each task
*
* @default false
*/
readonly assignPublicIp?: boolean;
/**
* An Amazon ECS launch type determines the type of infrastructure on which your
* tasks and services are hosted.
*
* @see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html
*/
readonly launchTarget: IEcsLaunchTarget;
/**
* Specifies whether to propagate the tags from the task definition to the task.
* An error will be received if you specify the SERVICE option when running a task.
*
* @see https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html#ECS-RunTask-request-propagateTags
*
* @default - No tags are propagated.
*/
readonly propagatedTagSource?: ecs.PropagatedTagSource;
/**
* Whether ECS Exec should be enabled
*
* @see https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html#ECS-RunTask-request-enableExecuteCommand
*
* @default false
*/
readonly enableExecuteCommand?: boolean;
}
/**
* An Amazon ECS launch type determines the type of infrastructure on which your tasks and services are hosted.
* @see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html
*/
export interface IEcsLaunchTarget {
/**
* called when the ECS launch target is configured on RunTask
*/
bind(task: EcsRunTask, launchTargetOptions: LaunchTargetBindOptions): EcsLaunchTargetConfig;
}
/**
* Options for binding a launch target to an ECS run job task
*/
export interface LaunchTargetBindOptions {
/**
* Task definition to run Docker containers in Amazon ECS
*/
readonly taskDefinition: ecs.ITaskDefinition;
/**
* A regional grouping of one or more container instances on which you can run
* tasks and services.
*
* @default - No cluster
*/
readonly cluster?: ecs.ICluster;
}
/**
* Configuration options for the ECS launch type
*/
export interface EcsLaunchTargetConfig {
/**
* Additional parameters to pass to the base task
*
* @default - No additional parameters passed
*/
readonly parameters?: { [key: string]: any };
}
/**
* Properties to define an ECS service
*/
export interface EcsFargateLaunchTargetOptions {
/**
* Refers to a specific runtime environment for Fargate task infrastructure.
* Fargate platform version is a combination of the kernel and container runtime versions.
*
* @see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html
*/
readonly platformVersion: ecs.FargatePlatformVersion;
}
/**
* Options to run an ECS task on EC2 in StepFunctions and ECS
*/
export interface EcsEc2LaunchTargetOptions {
/**
* Placement constraints
*
* @default - None
*/
readonly placementConstraints?: ecs.PlacementConstraint[];
/**
* Placement strategies
*
* @default - None
*/
readonly placementStrategies?: ecs.PlacementStrategy[];
}
/**
* Configuration for running an ECS task on Fargate
*
* @see https://docs.aws.amazon.com/AmazonECS/latest/userguide/launch_types.html#launch-type-fargate
*/
export class EcsFargateLaunchTarget implements IEcsLaunchTarget {
constructor(private readonly options?: EcsFargateLaunchTargetOptions) {}
/**
* Called when the Fargate launch type configured on RunTask
*/
public bind(_task: EcsRunTask, launchTargetOptions: LaunchTargetBindOptions): EcsLaunchTargetConfig {
if (!launchTargetOptions.taskDefinition.isFargateCompatible) {
throw new Error('Supplied TaskDefinition is not compatible with Fargate');
}
return {
parameters: {
LaunchType: 'FARGATE',
PlatformVersion: this.options?.platformVersion,
},
};
}
}
/**
* Configuration for running an ECS task on EC2
*
* @see https://docs.aws.amazon.com/AmazonECS/latest/userguide/launch_types.html#launch-type-ec2
*/
export class EcsEc2LaunchTarget implements IEcsLaunchTarget {
constructor(private readonly options?: EcsEc2LaunchTargetOptions) {}
/**
* Called when the EC2 launch type is configured on RunTask
*/
public bind(_task: EcsRunTask, launchTargetOptions: LaunchTargetBindOptions): EcsLaunchTargetConfig {
if (!launchTargetOptions.taskDefinition.isEc2Compatible) {
throw new Error('Supplied TaskDefinition is not compatible with EC2');
}
if (!launchTargetOptions.cluster?.hasEc2Capacity) {
throw new Error('Cluster for this service needs Ec2 capacity. Call addCapacity() on the cluster.');
}
return {
parameters: {
LaunchType: 'EC2',
// takes an array of placement constraints each of which contain a single item array of constraints, flattens it
// and renders the Json to be passed as a parameter in the state machine.
// input: [ecs.PlacementConstraint.distinctInstances()] - distinctInstances() returns [{ type: 'distinctInstance' }]
// output: {Type: 'distinctInstance'}
PlacementConstraints: noEmpty(flatten((this.options?.placementConstraints ?? []).map((c) => c.toJson().map(uppercaseKeys)))),
PlacementStrategy: noEmpty(flatten((this.options?.placementStrategies ?? []).map((c) => c.toJson().map(uppercaseKeys)))),
},
};
function uppercaseKeys(obj: { [key: string]: any }): { [key: string]: any } {
const ret: { [key: string]: any } = {};
for (const key of Object.keys(obj)) {
ret[key.slice(0, 1).toUpperCase() + key.slice(1)] = obj[key];
}
return ret;
}
function flatten<A>(xs: A[][]): A[] {
return Array.prototype.concat([], ...xs);
}
function noEmpty<A>(xs: A[]): A[] | undefined {
if (xs.length === 0) {
return undefined;
}
return xs;
}
}
}
/**
* Run a Task on ECS or Fargate
*/
export class EcsRunTask extends sfn.TaskStateBase implements ec2.IConnectable {
private static readonly SUPPORTED_INTEGRATION_PATTERNS: sfn.IntegrationPattern[] = [
sfn.IntegrationPattern.REQUEST_RESPONSE,
sfn.IntegrationPattern.RUN_JOB,
sfn.IntegrationPattern.WAIT_FOR_TASK_TOKEN,
];
/**
* Manage allowed network traffic for this service
*/
public readonly connections: ec2.Connections = new ec2.Connections();
protected readonly taskMetrics?: sfn.TaskMetricsConfig;
protected readonly taskPolicies?: iam.PolicyStatement[];
private securityGroups: ec2.ISecurityGroup[] = [];
private networkConfiguration?: any;
private readonly integrationPattern: sfn.IntegrationPattern;
constructor(scope: Construct, id: string, private readonly props: EcsRunTaskProps) {
super(scope, id, props);
this.integrationPattern = props.integrationPattern ?? sfn.IntegrationPattern.REQUEST_RESPONSE;
validatePatternSupported(this.integrationPattern, EcsRunTask.SUPPORTED_INTEGRATION_PATTERNS);
if (this.integrationPattern === sfn.IntegrationPattern.WAIT_FOR_TASK_TOKEN
&& !sfn.FieldUtils.containsTaskToken(props.containerOverrides?.map(override => override.environment))) {
throw new Error('Task Token is required in at least one `containerOverrides.environment` for callback. Use JsonPath.taskToken to set the token.');
}
if (!this.props.taskDefinition.defaultContainer) {
throw new Error('A TaskDefinition must have at least one essential container');
}
if (this.props.taskDefinition.networkMode === ecs.NetworkMode.AWS_VPC) {
this.configureAwsVpcNetworking();
} else {
// Either None, Bridge or Host networking. Copy SecurityGroup from ASG.
this.validateNoNetworkingProps();
this.connections.addSecurityGroup(...this.props.cluster.connections.securityGroups);
}
for (const override of this.props.containerOverrides ?? []) {
const name = override.containerDefinition.containerName;
if (!cdk.Token.isUnresolved(name)) {
const cont = this.props.taskDefinition.findContainer(name);
if (!cont) {
throw new Error(`Overrides mention container with name '${name}', but no such container in task definition`);
}
}
}
this.taskPolicies = this.makePolicyStatements();
}
/**
* @internal
*/
protected _renderTask(): any {
return {
Resource: integrationResourceArn('ecs', 'runTask', this.integrationPattern),
Parameters: sfn.FieldUtils.renderObject({
Cluster: this.props.cluster.clusterArn,
TaskDefinition: this.props.revisionNumber === undefined ? this.props.taskDefinition.family : `${this.props.taskDefinition.family}:${this.props.revisionNumber.toString()}`,
NetworkConfiguration: this.networkConfiguration,
Overrides: renderOverrides(this.props.containerOverrides),
PropagateTags: this.props.propagatedTagSource,
...this.props.launchTarget.bind(this, { taskDefinition: this.props.taskDefinition, cluster: this.props.cluster }).parameters,
EnableExecuteCommand: this.props.enableExecuteCommand,
}),
};
}
private configureAwsVpcNetworking() {
const subnetSelection = this.props.subnets ??
{ subnetType: this.props.assignPublicIp ? ec2.SubnetType.PUBLIC : ec2.SubnetType.PRIVATE_WITH_EGRESS };
this.networkConfiguration = {
AwsvpcConfiguration: {
AssignPublicIp: this.props.assignPublicIp ? (this.props.assignPublicIp ? 'ENABLED' : 'DISABLED') : undefined,
Subnets: this.props.cluster.vpc.selectSubnets(subnetSelection).subnetIds,
SecurityGroups: cdk.Lazy.list({ produce: () => this.securityGroups?.map(sg => sg.securityGroupId) }),
},
};
// Make sure we have a security group if we're using AWSVPC networking
this.securityGroups = this.props.securityGroups ?? [new ec2.SecurityGroup(this, 'SecurityGroup', { vpc: this.props.cluster.vpc })];
this.connections.addSecurityGroup(...this.securityGroups);
}
private validateNoNetworkingProps() {
if (this.props.subnets !== undefined || this.props.securityGroups !== undefined) {
throw new Error(
`Supplied TaskDefinition must have 'networkMode' of 'AWS_VPC' to use 'vpcSubnets' and 'securityGroup'. Received: ${this.props.taskDefinition.networkMode}`,
);
}
}
private makePolicyStatements(): iam.PolicyStatement[] {
const stack = cdk.Stack.of(this);
const taskDefinitionFamilyArn = this.getTaskDefinitionFamilyArn();
const reduceRunTaskPermissions = cdk.FeatureFlags.of(this).isEnabled(cxapi.ECS_REDUCE_RUN_TASK_PERMISSIONS);
let policyStatements = [];
// https://docs.aws.amazon.com/step-functions/latest/dg/ecs-iam.html
if (reduceRunTaskPermissions) {
policyStatements.push(
new iam.PolicyStatement({
actions: ['ecs:RunTask'],
resources: [`${taskDefinitionFamilyArn}:*`],
}),
);
} else {
policyStatements.push(
new iam.PolicyStatement({
actions: ['ecs:RunTask'],
resources: [
taskDefinitionFamilyArn,
`${taskDefinitionFamilyArn}:*`,
],
}),
);
}
policyStatements.push(
new iam.PolicyStatement({
actions: ['ecs:StopTask', 'ecs:DescribeTasks'],
resources: ['*'],
}),
new iam.PolicyStatement({
actions: ['iam:PassRole'],
resources: this.taskExecutionRoles().map((r) => r.roleArn),
}),
);
if (this.integrationPattern === sfn.IntegrationPattern.RUN_JOB) {
policyStatements.push(
new iam.PolicyStatement({
actions: ['events:PutTargets', 'events:PutRule', 'events:DescribeRule'],
resources: [
stack.formatArn({
service: 'events',
resource: 'rule',
resourceName: 'StepFunctionsGetEventsForECSTaskRule',
}),
],
}),
);
}
return policyStatements;
}
/**
* Returns the ARN of the task definition family by removing the
* revision from the task definition ARN
* Before - arn:aws:ecs:us-west-2:123456789012:task-definition/hello_world:8
* After - arn:aws:ecs:us-west-2:123456789012:task-definition/hello_world
*/
private getTaskDefinitionFamilyArn(): string {
const arnComponents = cdk.Stack.of(this).splitArn(this.props.taskDefinition.taskDefinitionArn, cdk.ArnFormat.SLASH_RESOURCE_NAME);
let { resourceName } = arnComponents;
if (resourceName) {
resourceName = resourceName.split(':')[0];
}
return cdk.Stack.of(this).formatArn({
partition: arnComponents.partition,
service: arnComponents.service,
account: arnComponents.account,
region: arnComponents.region,
resource: arnComponents.resource,
arnFormat: arnComponents.arnFormat,
resourceName,
});
}
private taskExecutionRoles(): iam.IRole[] {
// Need to be able to pass both Task and Execution role, apparently
const ret = new Array<iam.IRole>();
ret.push(this.props.taskDefinition.taskRole);
if (this.props.taskDefinition.executionRole) {
ret.push(this.props.taskDefinition.executionRole);
}
return ret;
}
}
function renderOverrides(containerOverrides?: ContainerOverride[]) {
if (!containerOverrides || containerOverrides.length === 0) {
return undefined;
}
const ret = new Array<any>();
for (const override of containerOverrides) {
ret.push({
Name: override.containerDefinition.containerName,
Command: override.command,
Cpu: override.cpu,
Memory: override.memoryLimit,
MemoryReservation: override.memoryReservation,
Environment:
override.environment?.map((e) => ({
Name: e.name,
Value: e.value,
})),
});
}
return { ContainerOverrides: ret };
}