You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CDK脚本配置Glue Job故障告警报错:Rule需在Stack作用域创建

问题修复:CDK中CloudWatch Rule/Alarm不在Stack作用域报错

错误原因

你创建Rule和CloudWatch Alarm时,传入的作用域是构造函数的scope参数,而非当前的InfraStack实例(this)。CDK要求所有资源必须归属到某个Stack的作用域下,否则会抛出找不到Stack的错误。

修复方案

把创建Rule和cloudwatch.Alarm的第一个参数从scope改为this,让资源挂载到当前InfraStack的作用域内:

修改后的完整代码

export interface InfraStackProps extends VpcStackProps {
  stageName?: string;
}

export class InfraStack extends VpcStack {
  constructor(scope: Construct, id: string, props: InfraStackProps ) {
    super(scope, id, props);
    // jobName. This is our AWS Glue script to monitor
    const jobFailedRule = new Rule(this, '{DVRD replication} JobFailureRule', {
      eventPattern: {
        source: ['aws.glue'],
        detailType: ['Glue Job State Change'],
        detail: {
          state: ['FAILED', 'TIMEOUT', 'ERROR'],
          jobName: ['DVRD replication'],
        },
      },
    })
    
    //cloudwatch metric
    const numFailedJobsMetric = new cloudwatch.Metric({
      namespace: 'AWS/Events',
      metricName: 'TriggeredRules',
      statistic: 'Sum',
      dimensionsMap: {
        RuleName: jobFailedRule.ruleName,
      },
    })
    
    //cloudwatch alarm
    const numFailedJobsAlarm = new cloudwatch.Alarm(this, '{DVRD replication} numFailedJobsAlarm', {
      metric: numFailedJobsMetric,
      threshold: 1,
      evaluationPeriods: 1,
    });
    
    
    // Adding an SNS action and an email registration 
    const notificationsTopic = new Topic(this, 'Topic'); 
    numFailedJobsAlarm.addAlarmAction(new SnsAction(notificationsTopic));
    notificationsTopic.addSubscription(new EmailSubscription('trst@gmail.com'));
}

说明

  • this在当前类中代表InfraStack实例,而InfraStack继承自VpcStack(最终继承CDK的Stack类),所以将资源挂载到this下,CDK就能正确识别它们属于当前Stack,解决报错问题。
  • 你创建SNS Topic时已经用了this,这部分是正确的,只需要修正Rule和Alarm的作用域参数即可。

内容的提问来源于stack exchange,提问作者Marcus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:33:25