CDK 中的 ECS 角色无法访问 RoleArn

RoleArn not accessible for ECS Role in CDK

在下面的代码片段中,我在构建项目时遇到了错误。尽管我在使用上面的一些行中定义了 ecs 服务,但为什么该角色显示为未定义?

TypeError: Cannot read property 'roleArn' of undefined

我看到roleArn是Role的可访问字段。我在这里做错了什么?

    let ecsService: FargateStack;
    
    .... (lines of code)

    const service = target.serviceDefinition;
    const serviceName = generateResourceName(service.shortName, stageName, airportCode, account, cell);
    ecsService = new FargateStack(app, serviceName, {
      softwareType: SoftwareType.LONG_RUNNING_SERVICE,
      ...(other params)
      httpsListener: cluster.httpsListner,
    });
    ecsService.addDependency(cluster);
    servicesStacks.push(ecsService);

    if (!awsAccountsWithOpenSearchCreated.has(accountRegion) && ecsService.serviceName == ServiceName.CONFIG_STORE){
      const openSearchStackName = generateResourceName('opensearch', stageName, airportCode, account, cell);
      const openSearchStack = new OpenSearchStack(app, openSearchStackName, {
        env: deploymentEnvironment,
        ... (other params)
        role: ecsService.role.roleArn
      });
      regionalResources.push(openSearchStack);

    }

FargateStack 定义如下,并在构造函数中初始化

export class FargateServiceStack extends DeploymentStack {
  public readonly role: Role;

  public readonly alarms: Alarm[];

  .....(lines of code)
}

您的 ecsService 变量是 FargateStack 类型。它大概扩展了 cdk.Stack,它没有 role 属性.

您可能正在 FargateStack 中寻找 ecs.[Fargate | Ec2 ]Servicetask definition. If so, expose the ECS Service as a public instance field 中的角色:

// FargateStack.ts
export class FargateStack extends cdk.Stack {
  readonly service: ecs.FargateService;

  constructor(scope: Construct, id: string, props: MyFargateStackProps) {
    // ... code ...
    this.service = new ecs.FargateService(...)

该角色在服务的任务定义中可用:

const { service } = new FargateStack(...)

const role: iam.Role = service.taskDefinition.taskRole