Skip to content

Instantly share code, notes, and snippets.

@hassaku63
Created April 9, 2025 02:26
Show Gist options
  • Save hassaku63/dbb74ebd3b51397a99003a07c94de6aa to your computer and use it in GitHub Desktop.
Save hassaku63/dbb74ebd3b51397a99003a07c94de6aa to your computer and use it in GitHub Desktop.
Enable GuardDuty Runtime Monitoring for ECS Fargate
import * as cdk from 'aws-cdk-lib';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ecr from 'aws-cdk-lib/aws-ecr';
import * as iam from 'aws-cdk-lib/aws-iam';
import { Construct } from 'constructs';
interface MyStackProps extends cdk.StackProps {}
export class MyStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: MyStackProps) {
super(scope, id, props);
const taskExecutionRole = new iam.Role(this, 'TaskExecutionRole', {
assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
});
// https://docs.aws.amazon.com/guardduty/latest/ug/runtime-monitoring-ecr-repository-gdu-agent.html
// > 533107202818.dkr.ecr.ap-northeast-1.amazonaws.com/aws-guardduty-agent-fargate
const gaurddutyAgentRepoArn = cdk.Arn.format({
partition: 'aws',
service: 'ecr',
account: '533107202818',
region: 'ap-northeast-1',
resource: 'repository',
resourceName: 'aws-guardduty-agent-fargate',
}, this);
const guarddutyAgentRepo = ecr.Repository.fromRepositoryArn(this, 'GuardDutyAgentRepo', gaurddutyAgentRepoArn);
// Grant pull access to Task Execution Role for retrieving GuardDuty Agent
guarddutyAgentRepo.grantPull(taskExecutionRole);
}
}
const app = new cdk.App();
new MyStack(app, 'MyStack', {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
});
// Enable GuardDuty Runtime Monitoring for all ECS Cluster in this app
cdk.Tags.of(app).add('GuardDutyManaged', 'true', {
includeResourceTypes: ['AWS::ECS::Cluster'],
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment