Skip to content

(aws-cloudwatch): AlarmRule static methods can synth into an invalid template #34662

@jacklin213

Description

@jacklin213

Describe the bug

AlarmRule.anyOf(...alarms) or AlarmRule.allOf(...alarms) where alarms is empty will result in alarmRule: "()" in the synth'ed CFN template which is not a valid alarm rule.

Expected Behavior

Users should be able to cdk synth if Alarm Rule is invalid

Current Behavior

cdk synth passes and users will only find out the alarm rule is invalid during deployment time in CloudFormation with a not so straight forward error message

Resource handler returned message: "Error in AlarmRule [Unsupported token ')' at char 1] (Service: AmazonCloudWatch ...)

Reproduction Steps

const alarms: Alarm[] = [];
new CompositeAlarm(this, 'CompositeAlarm', {
  compositeAlarmName: "CompositeAlarm",
  alarmRule: AlarmRule.anyOf(...alarms),
});

Possible Solution

Both AlarmRule.anyOf(...alarms) and AlarmRule.allOf(...alarms) calls the concat function below

private static concat(operator: Operator, ...operands: IAlarmRule[]): IAlarmRule {
return new class implements IAlarmRule {
public renderAlarmRule(): string {
const expression = operands
.map(operand => `${operand.renderAlarmRule()}`)
.join(` ${operator} `);
return `(${expression})`;
}
};
}
}

We could consider having CDK throw an error if expression is undefined so users don't need to wait till deployment time to find out the alarm rule is invalid. Maybe something like

private static concat(operator: Operator, ...operands: IAlarmRule[]): IAlarmRule {
    return new class implements IAlarmRule {
      public renderAlarmRule(): string {
        const expression = operands
          .map(operand => `${operand.renderAlarmRule()}`)
          .join(` ${operator} `);
        if (!expression) {
            // Throw exception here
        }
        return `(${expression})`;
      }
    };
}

Additional Information/Context

Originally reported in #14387 but was closed for staleness. It is still an issue with the latest cdk version

AWS CDK Library version (aws-cdk-lib)

2.181.1

AWS CDK CLI version

2.1007.0

Node.js Version

20.18.0

OS

Amazon Linux 2

Language

TypeScript

Language Version

5.8.2

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    @aws-cdk/aws-cloudwatchRelated to Amazon CloudWatchbugThis issue is a bug.effort/smallSmall work item – less than a day of effortp2

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions