はじめに
ECS execでログを有効化した際のメモです。
手順
1. ECSクラスターでロギングを有効化
ecs_cluster.ts
import { Construct } from 'constructs';
import * as logs from 'aws-cdk-lib/aws-logs';
import * as ecs from 'aws-cdk-lib/aws-ecs';
export class EcsCluster {
private scope: Construct;
public readonly cluster: ecs.CfnCluster;
constructor(_scope: Construct, clusterName: string) {
this.scope = _scope;
const env = this.scope.node.tryGetContext('env');
// ロググループを作成
const ecsExecLogGroupName = `/ecs/ecs-exec/logs/${env}-log-group`;
const ecsExecLogGroup = new logs.CfnLogGroup(this.scope, 'EcsExecLog', {
logGroupName: ecsExecLogGroupName,
retentionInDays: 30
});
// クラスターでログを有効化
this.cluster = new ecs.CfnCluster(this.scope, `Cluster`, {
clusterName,
configuration: {
executeCommandConfiguration: {
logging: ecs.ExecuteCommandLogging.OVERRIDE,
logConfiguration: { cloudWatchLogGroupName: ecsExecLogGroupName }
}
}
});
this.cluster.addDependency(ecsExecLogGroup);
}
}
2. ECSタスクロールを追加
task-role.ts
...
const ecsTaskRole = new iam.CfnRole(
this.scope,
'EcsTaskRole',
{
assumeRolePolicyDocument: new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
principals: [new iam.ServicePrincipal('ecs-tasks.amazonaws.com')],
actions: ['sts:AssumeRole']
})
]
}),
policies: [
{
policyDocument: new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
'ssmmessages:CreateControlChannel',
'ssmmessages:CreateDataChannel',
'ssmmessages:OpenControlChannel',
'ssmmessages:OpenDataChannel',
'ssm:UpdateInstanceInformation',
'logs:DescribeLogGroups',
'logs:CreateLogStream',
'logs:DescribeLogStreams',
'logs:PutLogEvents'
],
resources: ['*']
})
]
}),
policyName: `EcsTaskRolePolicy`
}
],
roleName: `${env}-ecs-task-role`
}
);
...
参考