Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(scheduler-targets): EcsRunTask scheduler target #33697

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

gracelu0
Copy link
Contributor

@gracelu0 gracelu0 commented Mar 6, 2025

Issue # (if applicable)

Closes #27456

Reason for this change

Currently the module supports all templated targets for EventBridge scheduler except for EcsRunTask.

Description of changes

  • Added new base class EcsRunTask with public static methods onFargate and onEc2 depending on where user wants to schedule their ECS task. Decided on this design since some of the parameters in EcsParameters only apply one of Fargate or EC2.

Describe any new or updated permissions being added

  • Grant ecs:RunTask to the schedule execution role for the task definition
  this.props.taskDefinition.grantRun(role);

// TaskDefinition grant method 
  public grantRun(grantee: iam.IGrantable) {
    grantee.grantPrincipal.addToPrincipalPolicy(this.passRoleStatement);
    return iam.Grant.addToPrincipal({
      grantee,
      actions: ['ecs:RunTask'],
      resourceArns: [this.taskDefinitionArn],
    });
  }
  • If tags are defined, grant ecs:TagResourceto the schedule execution tole for tasks in the cluster
    if (this.props.propagateTags === true || this.props.tags) {
      role.addToPrincipalPolicy(new PolicyStatement({
        actions: ['ecs:TagResource'],
        resources: [`arn:${this.cluster.stack.partition}:ecs:${this.cluster.env.region}:${this.props.taskDefinition.env.account}:task/${this.cluster.clusterName}/*`],
      }));
    }
  • iam:PassRole permissions to the schedule execution role for each task execution role (docs)
    if (this.props.taskDefinition.executionRole !== undefined) {
      role.addToPrincipalPolicy(new PolicyStatement({
        actions: ['iam:PassRole'],
        resources: [this.props.taskDefinition.executionRole.roleArn],
      }));
    }
  • for fargate, iam:PassRole permissions to the schedule execution role for the task role
    if (this.props.taskDefinition.isFargateCompatible) {
      role.addToPrincipalPolicy(new PolicyStatement({
        actions: ['iam:PassRole'],
        resources: [this.props.taskDefinition.taskRole.roleArn],
      }));
    }

Description of how you validated changes

Added unit tests and integration tests with assertions.

Checklist


By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license

@aws-cdk-automation aws-cdk-automation requested a review from a team March 6, 2025 01:04
@github-actions github-actions bot added effort/medium Medium work item – several days of effort feature-request A feature should be added or improved. p2 labels Mar 6, 2025
@mergify mergify bot added the contribution/core This is a PR that came from AWS. label Mar 6, 2025
Copy link

codecov bot commented Mar 6, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 82.24%. Comparing base (7f5bf4e) to head (109b25f).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #33697   +/-   ##
=======================================
  Coverage   82.24%   82.24%           
=======================================
  Files         119      119           
  Lines        6875     6875           
  Branches     1161     1161           
=======================================
  Hits         5654     5654           
  Misses       1118     1118           
  Partials      103      103           
Flag Coverage Δ
suite.unit 82.24% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
packages/aws-cdk ∅ <ø> (∅)
packages/aws-cdk-lib/core 82.24% <ø> (ø)
🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@godwingrs22 godwingrs22 self-assigned this Mar 6, 2025
@gracelu0 gracelu0 force-pushed the ecs-run-task-scheduler-target branch from 435019c to e97c70c Compare March 6, 2025 19:15
@gracelu0 gracelu0 force-pushed the ecs-run-task-scheduler-target branch from e97c70c to 109b25f Compare March 6, 2025 19:48
@aws-cdk-automation
Copy link
Collaborator

AWS CodeBuild CI Report

  • CodeBuild project: AutoBuildv2Project1C6BFA3F-wQm2hXv2jqQv
  • Commit ID: 109b25f
  • Result: SUCCEEDED
  • Build Logs (available for 30 days)

Powered by github-codebuild-logs, available on the AWS Serverless Application Repository

@aws-cdk-automation aws-cdk-automation added the pr/needs-maintainer-review This PR needs a review from a Core Team Member label Mar 6, 2025
@gracelu0 gracelu0 changed the title feat(scheduler-targets): ECSRunTask scheduler target feat(scheduler-targets): EcsRunTask scheduler target Mar 6, 2025
Copy link
Member

@godwingrs22 godwingrs22 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @gracelu0 for this great work. LGTM overall. Left few nits and comments for my understanding.

*
* @default - all private subnets of the VPC are selected.
*/
readonly subnetSelection?: ec2.SubnetSelection;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: May be it would be good to rename the property like vpcSubnets or subnets

Comment on lines +184 to +188
if (this.props.taskDefinition.executionRole !== undefined) {
role.addToPrincipalPolicy(new PolicyStatement({
actions: ['iam:PassRole'],
resources: [this.props.taskDefinition.executionRole.roleArn],
}));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

qq: For my understanding, do we need to add PassRole statement to the executionRole?

grantRun already provides the passRole statement required to run this task defintion. Usually ExecutionRole grants the ECS Fargate agent to make AWS API calls on behalf. I'm not sure if we need to add PassRole statement to it. From the unit test, I could see two times the PassRole is added for the same ARN

Comment on lines +241 to +242
actions: ['iam:PassRole'],
resources: [this.props.taskDefinition.taskRole.roleArn],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here not sure if we need to add PassRole statement to the task role.

target: targets.EcsRunTask.onFargate(cluster, {
taskDefinition,
subnetSelection: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS },
assignPublicIp: false,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we have one test case for assignPublicIp: true with public subnet?

stack = new cdk.Stack();
vpc = new ec2.Vpc(stack, 'Vpc');
cluster = new ecs.Cluster(stack, 'Cluster', { vpc });
taskDefinition = new ecs.TaskDefinition(stack, 'TaskDef', {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: since this taskDefinition is for Fargate, would be good to rename to fargateTaskDefinition ?

Comment on lines +64 to +71
new scheduler.Schedule(stack, 'Schedule', {
schedule: scheduler.ScheduleExpression.rate(cdk.Duration.minutes(5)),
target: targets.EcsRunTask.onFargate(cluster, {
taskDefinition,
subnetSelection: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS },
securityGroups: [securityGroup],
}),
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we a unit test for both fargate and ec2 task by calling like below also?

new scheduler.Schedule(stack, 'Schedule', {
        schedule: scheduler.ScheduleExpression.rate(cdk.Duration.minutes(5)),
        target: new targets.FargateTask(...)
      });

new scheduler.Schedule(stack, 'Schedule', {
        schedule: scheduler.ScheduleExpression.rate(cdk.Duration.minutes(5)),
        target: new targets.EC2Task(...)
      });

Comment on lines +161 to +164
PlacementConstraints: [{
Type: 'memberOf',
Expression: 'task:group == databases',
}],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also assert PlacementStrategy?


// Only one of capacityProviderStrategy or launchType can be set
// See https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html#ECS-RunTask-request-launchType
const launchType = this.capacityProviderStrategies ? undefined : ecs.LaunchType.EC2;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Good to have a test case for this capacityProviderStrategies and launchType behaviour.

@aws-cdk-automation aws-cdk-automation removed the pr/needs-maintainer-review This PR needs a review from a Core Team Member label Mar 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
contribution/core This is a PR that came from AWS. effort/medium Medium work item – several days of effort feature-request A feature should be added or improved. p2
Projects
None yet
Development

Successfully merging this pull request may close these issues.

(aws-scheduler-targets-alpha): Add EcsRunTask Target
3 participants