From b0a1a0128d84b41f1c04d946519368e5fb23ba49 Mon Sep 17 00:00:00 2001 From: Jonathan Goldwasser Date: Mon, 1 Jan 2024 15:59:42 +0000 Subject: [PATCH] feat(ce): cost anomaly monitor and subscription Add L2 constructs for cost anomaly detection. --- packages/@aws-cdk/aws-ce-alpha/.eslintrc.js | 8 + packages/@aws-cdk/aws-ce-alpha/.gitignore | 24 ++ packages/@aws-cdk/aws-ce-alpha/.npmignore | 31 ++ packages/@aws-cdk/aws-ce-alpha/LICENSE | 201 +++++++++++++ packages/@aws-cdk/aws-ce-alpha/NOTICE | 2 + packages/@aws-cdk/aws-ce-alpha/README.md | 54 ++++ packages/@aws-cdk/aws-ce-alpha/awslint.json | 4 + packages/@aws-cdk/aws-ce-alpha/jest.config.js | 2 + .../aws-ce-alpha/lib/anomaly-monitor.ts | 185 ++++++++++++ .../aws-ce-alpha/lib/anomaly-subscription.ts | 264 +++++++++++++++++ packages/@aws-cdk/aws-ce-alpha/lib/index.ts | 2 + packages/@aws-cdk/aws-ce-alpha/package.json | 118 ++++++++ .../aws-ce-alpha/rosetta/default.ts-fixture | 13 + .../aws-ce-alpha/test/anomaly-monitor.test.ts | 69 +++++ .../test/anomaly-subscription.test.ts | 83 ++++++ ...efaultTestDeployAssertDEF6AC0B.assets.json | 19 ++ ...aultTestDeployAssertDEF6AC0B.template.json | 36 +++ .../cdk-integ-ce-anomaly.assets.json | 19 ++ .../cdk-integ-ce-anomaly.template.json | 116 ++++++++ .../test/integ.anomaly.js.snapshot/cdk.out | 1 + .../test/integ.anomaly.js.snapshot/integ.json | 12 + .../integ.anomaly.js.snapshot/manifest.json | 137 +++++++++ .../test/integ.anomaly.js.snapshot/tree.json | 270 ++++++++++++++++++ .../aws-ce-alpha/test/integ.anomaly.ts | 33 +++ 24 files changed, 1703 insertions(+) create mode 100644 packages/@aws-cdk/aws-ce-alpha/.eslintrc.js create mode 100644 packages/@aws-cdk/aws-ce-alpha/.gitignore create mode 100644 packages/@aws-cdk/aws-ce-alpha/.npmignore create mode 100644 packages/@aws-cdk/aws-ce-alpha/LICENSE create mode 100644 packages/@aws-cdk/aws-ce-alpha/NOTICE create mode 100644 packages/@aws-cdk/aws-ce-alpha/README.md create mode 100644 packages/@aws-cdk/aws-ce-alpha/awslint.json create mode 100644 packages/@aws-cdk/aws-ce-alpha/jest.config.js create mode 100644 packages/@aws-cdk/aws-ce-alpha/lib/anomaly-monitor.ts create mode 100644 packages/@aws-cdk/aws-ce-alpha/lib/anomaly-subscription.ts create mode 100644 packages/@aws-cdk/aws-ce-alpha/lib/index.ts create mode 100644 packages/@aws-cdk/aws-ce-alpha/package.json create mode 100644 packages/@aws-cdk/aws-ce-alpha/rosetta/default.ts-fixture create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/anomaly-monitor.test.ts create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/anomaly-subscription.test.ts create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.assets.json create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.template.json create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk-integ-ce-anomaly.assets.json create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk-integ-ce-anomaly.template.json create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk.out create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/integ.json create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/manifest.json create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/tree.json create mode 100644 packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.ts diff --git a/packages/@aws-cdk/aws-ce-alpha/.eslintrc.js b/packages/@aws-cdk/aws-ce-alpha/.eslintrc.js new file mode 100644 index 0000000000000..b284f20df26e9 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/.eslintrc.js @@ -0,0 +1,8 @@ +const baseConfig = require('@aws-cdk/cdk-build-tools/config/eslintrc'); +baseConfig.parserOptions.project = __dirname + '/tsconfig.json'; + +baseConfig.rules['import/no-extraneous-dependencies'] = ['error', { devDependencies: true, peerDependencies: true } ]; +baseConfig.rules['import/order'] = 'off'; +baseConfig.rules['@aws-cdk/invalid-cfn-imports'] = 'off'; + +module.exports = baseConfig; diff --git a/packages/@aws-cdk/aws-ce-alpha/.gitignore b/packages/@aws-cdk/aws-ce-alpha/.gitignore new file mode 100644 index 0000000000000..a103aefa2bfbb --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/.gitignore @@ -0,0 +1,24 @@ +*.js +*.js.map +*.d.ts +tsconfig.json +node_modules +*.generated.ts +dist +.jsii + +.LAST_BUILD +.nyc_output +coverage +.nycrc +.LAST_PACKAGE +*.snk +nyc.config.js +!.eslintrc.js +!jest.config.js +junit.xml + +!**/*.snapshot/**/asset.*/*.js +!**/*.snapshot/**/asset.*/*.d.ts + +!**/*.snapshot/**/asset.*/** diff --git a/packages/@aws-cdk/aws-ce-alpha/.npmignore b/packages/@aws-cdk/aws-ce-alpha/.npmignore new file mode 100644 index 0000000000000..d70611c1df0b0 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/.npmignore @@ -0,0 +1,31 @@ +# Don't include original .ts files when doing `npm pack` +*.ts +!*.d.ts +coverage +.nyc_output +*.tgz + +dist +.LAST_PACKAGE +.LAST_BUILD +!*.js + +# Include .jsii +!.jsii + +*.snk + +*.tsbuildinfo + +tsconfig.json + +.eslintrc.js +jest.config.js + +# exclude cdk artifacts +**/cdk.out +junit.xml +test/ + +!*.lit.ts +**/*.snapshot diff --git a/packages/@aws-cdk/aws-ce-alpha/LICENSE b/packages/@aws-cdk/aws-ce-alpha/LICENSE new file mode 100644 index 0000000000000..dcf28b52a83af --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/@aws-cdk/aws-ce-alpha/NOTICE b/packages/@aws-cdk/aws-ce-alpha/NOTICE new file mode 100644 index 0000000000000..c0b1f046c881a --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/NOTICE @@ -0,0 +1,2 @@ +AWS Cloud Development Kit (AWS CDK) +Copyright 2018-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/packages/@aws-cdk/aws-ce-alpha/README.md b/packages/@aws-cdk/aws-ce-alpha/README.md new file mode 100644 index 0000000000000..c592b77a2f2a8 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/README.md @@ -0,0 +1,54 @@ +# AWS::CE Construct Library + + +--- + +![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge) + +> The APIs of higher level constructs in this module are experimental and under active development. +> They are subject to non-backward compatible changes or removal in any future version. These are +> not subject to the [Semantic Versioning](https://semver.org/) model and breaking changes will be +> announced in the release notes. This means that while you may use them, you may need to update +> your source code when upgrading to a newer version of this package. + +--- + + + +This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project. + +AWS Cost Explorer is a tool that enables you to view and analyze your costs and usage. You +can explore your usage and costs using the main graph, the Cost Explorer cost and usage +reports, or the Cost Explorer RI reports. You can view data for up to the last 13 months, +forecast how much you're likely to spend for the next 12 months, and get recommendations for +what Reserved Instances to purchase. You can use Cost Explorer to identify areas that need +further inquiry and see trends that you can use to understand your costs. + +## Cost Anomaly Detection + +AWS Cost Anomaly Detection is an AWS Cost Management feature. This feature uses machine learning models to detect and alert on anomalous spend patterns in your deployed AWS services. + +To create your cost monitors and alert subscriptions, use the `AnomalyMonitor` +and `AnomalySubscription` constructs: + +```ts +declare const myTopic: sns.Topic; + +// This monitor evaluates all the AWS services that are used by your +// individual AWS account for anomalies. +const servicesMonitor = new ce.AnomalyMonitor(this, 'AwsServicesMonitor', { + type: ce.MonitorType.awsServices(), +}); + +// This monitor evaluates the spend for specific values of a cost allocation tag +const tagsMonitor = new ce.AnomalyMonitor(this, 'TagsMonitor', { + type: ce.MonitorType.costAllocationTag('key', ['value1', 'value2']), +}); + +// Receive alerts on a SNS topic when the spend is 100 USD above the expected spend +new ce.AnomalySubscription(this, 'Subscription', { + anomalyMonitors: [servicesMonitor, tagsMonitor], + subscriber: ce.AnomalySubscriber.sns(myTopic), + thresholdExpression: ce.ThresholdExpression.aboveUsdAmount(100), +}) +``` diff --git a/packages/@aws-cdk/aws-ce-alpha/awslint.json b/packages/@aws-cdk/aws-ce-alpha/awslint.json new file mode 100644 index 0000000000000..2923789192b72 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/awslint.json @@ -0,0 +1,4 @@ +{ + "exclude": [ + ] +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/jest.config.js b/packages/@aws-cdk/aws-ce-alpha/jest.config.js new file mode 100644 index 0000000000000..3a2fd93a1228a --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/jest.config.js @@ -0,0 +1,2 @@ +const baseConfig = require('@aws-cdk/cdk-build-tools/config/jest.config'); +module.exports = baseConfig; diff --git a/packages/@aws-cdk/aws-ce-alpha/lib/anomaly-monitor.ts b/packages/@aws-cdk/aws-ce-alpha/lib/anomaly-monitor.ts new file mode 100644 index 0000000000000..f295bc15dbd66 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/lib/anomaly-monitor.ts @@ -0,0 +1,185 @@ +import { Construct } from 'constructs'; +import { ArnFormat, IResource, Lazy, Names, Resource, Stack } from 'aws-cdk-lib'; +import { CfnAnomalyMonitor } from 'aws-cdk-lib/aws-ce'; + +/** + * An Anomaly Monitor + */ +export interface IAnomalyMonitor extends IResource { + /** + * The ARN of the anomaly monitor + * + * @attribute + */ + readonly anomalyMonitorArn: string; +} + +/** + * Options for an anomaly monitor + */ +export interface AnomalyMonitorProps { + /** + * A name for the anomaly monitor + * + * @default - A name is automatically generated + */ + readonly anomalyMonitorName?: string; + + /** + * The type of anomaly monitor + */ + readonly type: MonitorType; +} + +/** + * Type of anomaly monitor + */ +export abstract class MonitorType { + /** + * Anomaly monitor for AWS services + */ + public static awsServices(): MonitorType { + return { + type: 'DIMENSIONAL', + dimension: 'SERVICE', + }; + } + + /** + * Custom anomaly monitor for a cost allocation tag + */ + public static costAllocationTag(key: string, values: string[]): MonitorType { + return { + type: 'CUSTOM', + specification: { + Tags: { + Key: key, + Values: values, + }, + }, + }; + } + + /** + * Custom anomaly monitor for a cost category + */ + public static costCategory(key: string, value: string): MonitorType { + return { + type: 'CUSTOM', + specification: { + CostCategories: { + Key: key, + Values: [value], + }, + }, + }; + } + + /** + * Custom anomaly monitor with linked accounts + */ + public static linkedAccounts(accounts: string[]): MonitorType { + return { + type: 'CUSTOM', + specification: { + Dimensions: { + Key: 'LINKED_ACCOUNT', + Values: accounts, + }, + }, + }; + } + + /** + * The type of the monitor + */ + public abstract type: string; + + /** + * The dimension of the monitor + */ + public abstract dimension?: string; + + /** + * The specification of the monitor + */ + public readonly specification?: Record; +} + +/** + * An anomaly monitor + */ +export class AnomalyMonitor extends Resource implements IAnomalyMonitor { + /** + * Use an existing anomaly monitor + */ + public static fromAnomalyMonitorArn(scope: Construct, id: string, anomalyMonitorArn: string): IAnomalyMonitor { + const parsedArn = Stack.of(scope).splitArn(anomalyMonitorArn, ArnFormat.SLASH_RESOURCE_NAME); + + class Import extends Resource implements IAnomalyMonitor { + public readonly anomalyMonitorArn = anomalyMonitorArn; + } + + return new Import(scope, id, { + account: parsedArn.account, + region: parsedArn.region, + }); + } + + public readonly anomalyMonitorArn: string; + + /** + * The date when the monitor was created. + * + * @attribute + */ + public readonly anomalyMonitorCreationDate: string; + + /** + * The value for evaluated dimensions. + * + * @attribute + */ + public readonly anomalyMonitorDimensionalValueCount: number; + + /** + * The date when the monitor last evaluated for anomalies. + * + * @attribute + */ + public readonly anomalyMonitorLastEvaluatedDate: string; + + /** + * The date when the monitor was last updated. + * + * @attribute + */ + public readonly anomalyMonitorLastUpdatedDate: string; + + constructor(scope: Construct, id: string, props: AnomalyMonitorProps) { + super(scope, id, { + physicalName: props.anomalyMonitorName ?? Lazy.string({ produce: () => this.generateUniqueId() }), + }); + + const monitor = new CfnAnomalyMonitor(this, 'Resource', { + monitorName: this.physicalName, + monitorType: props.type.type, + monitorDimension: props.type.dimension, + monitorSpecification: props.type.specification ? JSON.stringify(props.type.specification) : undefined, + }); + + this.anomalyMonitorArn = monitor.ref; + this.anomalyMonitorCreationDate = monitor.attrCreationDate; + this.anomalyMonitorDimensionalValueCount = monitor.attrDimensionalValueCount; + this.anomalyMonitorLastEvaluatedDate = monitor.attrLastEvaluatedDate; + this.anomalyMonitorLastUpdatedDate = monitor.attrLastUpdatedDate; + } + + private generateUniqueId(): string { + const name = Names.uniqueId(this); + if (name.length > 50) { + return name.substring(0, 25) + name.substring(name.length - 25); + } + return name; + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/lib/anomaly-subscription.ts b/packages/@aws-cdk/aws-ce-alpha/lib/anomaly-subscription.ts new file mode 100644 index 0000000000000..3dc38ff48f876 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/lib/anomaly-subscription.ts @@ -0,0 +1,264 @@ +import { ArnFormat, IResource, Lazy, Names, Resource, Stack } from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +import { CfnAnomalySubscription } from 'aws-cdk-lib/aws-ce'; +import { IAnomalyMonitor } from './anomaly-monitor'; +import { ITopic } from 'aws-cdk-lib/aws-sns'; +import { ServicePrincipal } from 'aws-cdk-lib/aws-iam'; + +/** + * An anomaly subscription + */ +export interface IAnomalySubscription extends IResource { + /** + * The ARN of the anomaly subscription + * + * @attribute + */ + readonly anomalySubscriptionArn: string; +} + +/** + * Properties for an anomaly subscription + */ +export interface AnomalySubscriptionProps { + /** + * A name for the anomaly subscription + * + * @default - A name is automatically generated + */ + readonly anomalySubscriptionName?: string; + + /** + * A list of anomaly monitors + */ + readonly anomalyMonitors: IAnomalyMonitor[]; + + /** + * The subscriber + */ + readonly subscriber: AnomalySubscriber; + + /** + * An expression used to specify the anomalies that you + * want to generate alerts for. + */ + readonly thresholdExpression: ThresholdExpression; +} + +/** + * Configuration for a subscriber + */ +export interface SubscriberConfig { + /** + * The frequency + */ + readonly frequency: string; + + /** + * The type of subscriber + */ + readonly type: string; + + /** + * The addresses + */ + readonly addresses: string[]; +} + +/** + * A subscriber for an anomaly subscription + */ +export abstract class AnomalySubscriber { + /** + * Use a SNS topic as subscriber + */ + public static sns(topic: ITopic): AnomalySubscriber { + return new SnsSubscriber(topic); + } + + /** + * Use email addresses as subscribers + */ + public static emails(frequency: EmailFrequency, emails: string[]): AnomalySubscriber { + return new EmailsSubscriber(frequency, emails); + } + + /** + * Binds the subscriber to the subscription + */ + public abstract bind(anomalySubscription: AnomalySubscription): SubscriberConfig; +} + +class SnsSubscriber extends AnomalySubscriber { + constructor(private readonly topic: ITopic) { + super(); + } + + public bind(anomalySubscription: AnomalySubscription): SubscriberConfig { + this.topic.grantPublish(new ServicePrincipal('costalerts.amazonaws.com').withConditions({ + StringEquals: { + 'aws:SourceAccount': [Stack.of(anomalySubscription).account], + }, + })); + + return { + type: 'SNS', + frequency: 'IMMEDIATE', + addresses: [this.topic.topicArn], + }; + } +} + +class EmailsSubscriber extends AnomalySubscriber { + constructor(private readonly frequency: EmailFrequency, private readonly emails: string[]) { + super(); + } + + public bind(_: AnomalySubscription): SubscriberConfig { + return { + type: 'EMAIL', + frequency: this.frequency, + addresses: this.emails, + }; + } +} + +/** + * Email frequency + */ +export enum EmailFrequency { + /** + * Daily + */ + DAILY = 'DAILY', + + /** + * Weekly + */ + WEEKLY = 'WEEKLY' +} + +/** + * A threshold expression + */ +export abstract class ThresholdExpression { + /** + * Generate alerts when the spend is above an amount in USD + */ + public static aboveUsdAmount(amount: number): ThresholdExpression { + return { + expression: { + Dimensions: { + Key: 'ANOMALY_TOTAL_IMPACT_ABSOLUTE', + MatchOptions: ['GREATER_THAN_OR_EQUAL'], + Values: [amount.toString()], + }, + }, + }; + } + + /** + * Generate alerts when the spend is above a percentage + */ + public static abovePercentage(percentage: number): ThresholdExpression { + return { + expression: { + Dimensions: { + Key: 'ANOMALY_TOTAL_IMPACT_PERCENTAGE', + MatchOptions: ['GREATER_THAN_OR_EQUAL'], + Values: [percentage.toString()], + }, + }, + }; + } + + /** + * Generate alerts when the spend is above an amount in USD **and** above a percentage + */ + public static aboveUsdAmountAndPercentage(amount: number, percentage: number): ThresholdExpression { + const aboveUsdAMount = this.aboveUsdAmount(amount); + const abovePercentage = this.abovePercentage(percentage); + return { + expression: { + And: [aboveUsdAMount.expression, abovePercentage.expression], + }, + }; + } + + /** + * Generate alerts when the spend is above an amount in USD **or** above a percentage + */ + public static aboveUsdAmountOrPercentage(amount: number, percentage: number): ThresholdExpression { + const aboveUsdAMount = this.aboveUsdAmount(amount); + const abovePercentage = this.abovePercentage(percentage); + return { + expression: { + Or: [aboveUsdAMount.expression, abovePercentage.expression], + }, + }; + } + + /** + * The expression of the threshold + */ + public abstract readonly expression: Record; +} + +/** + * An anomaly subscription + */ +export class AnomalySubscription extends Resource implements IAnomalySubscription { + /** + * Use an existing anomaly subscription + */ + public static fromAnomalySubscriptionArn(scope: Construct, id: string, anomalySubscriptionArn: string): IAnomalySubscription { + const parsedArn = Stack.of(scope).splitArn(anomalySubscriptionArn, ArnFormat.SLASH_RESOURCE_NAME); + + class Import extends Resource implements IAnomalySubscription { + public readonly anomalySubscriptionArn = anomalySubscriptionArn; + } + + return new Import(scope, id, { + account: parsedArn.account, + region: parsedArn.region, + }); + } + public readonly anomalySubscriptionArn: string; + + /** + * Your unique account identifier. + * + * @attribute + */ + public readonly anomalySubscriptionAccountId: string; + + constructor(scope: Construct, id: string, props: AnomalySubscriptionProps) { + super(scope, id, { + physicalName: props.anomalySubscriptionName ?? Lazy.string({ produce: () => this.generateUniqueId() }), + }); + + const subscriberConfig = props.subscriber.bind(this); + + const subscription = new CfnAnomalySubscription(this, 'Resource', { + monitorArnList: props.anomalyMonitors.map((monitor) => monitor.anomalyMonitorArn), + frequency: subscriberConfig.frequency, + subscriptionName: this.physicalName, + subscribers: subscriberConfig.addresses.map((address) => ({ + type: subscriberConfig.type, + address, + })), + thresholdExpression: JSON.stringify(props.thresholdExpression.expression), + }); + + this.anomalySubscriptionArn = subscription.ref; + this.anomalySubscriptionAccountId = subscription.attrAccountId; + } + + private generateUniqueId(): string { + const name = Names.uniqueId(this); + if (name.length > 50) { + return name.substring(0, 25) + name.substring(name.length - 25); + } + return name; + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/lib/index.ts b/packages/@aws-cdk/aws-ce-alpha/lib/index.ts new file mode 100644 index 0000000000000..09b1e62726bbf --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/lib/index.ts @@ -0,0 +1,2 @@ +export * from './anomaly-monitor'; +export * from './anomaly-subscription'; diff --git a/packages/@aws-cdk/aws-ce-alpha/package.json b/packages/@aws-cdk/aws-ce-alpha/package.json new file mode 100644 index 0000000000000..a515fc2f7cfa4 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/package.json @@ -0,0 +1,118 @@ +{ + "name": "@aws-cdk/aws-ce-alpha", + "version": "0.0.0", + "description": "The CDK Construct Library for AWS::CE", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "jsii": { + "outdir": "dist", + "projectReferences": true, + "targets": { + "dotnet": { + "namespace": "Amazon.CDK.AWS.Ce.Alpha", + "packageId": "Amazon.CDK.AWS.Ce.Alpha", + "signAssembly": true, + "assemblyOriginatorKeyFile": "../../key.snk", + "iconUrl": "https://raw.githubusercontent.com/aws/aws-cdk/main/logo/default-256-dark.png" + }, + "java": { + "package": "software.amazon.awscdk.services.ce.alpha", + "maven": { + "groupId": "software.amazon.awscdk", + "artifactId": "ce-alpha" + } + }, + "python": { + "classifiers": [ + "Framework :: AWS CDK", + "Framework :: AWS CDK :: 2" + ], + "distName": "aws-cdk.aws-ce-alpha", + "module": "aws_cdk.aws_ce_alpha" + }, + "go": { + "moduleName": "github.com/aws/aws-cdk-go", + "packageName": "awscdkcealpha" + } + }, + "metadata": { + "jsii": { + "rosetta": { + "strict": true + } + } + } + }, + "repository": { + "type": "git", + "url": "https://github.com/aws/aws-cdk.git", + "directory": "packages/@aws-cdk/aws-ce-alpha" + }, + "homepage": "https://github.com/aws/aws-cdk", + "scripts": { + "build": "cdk-build", + "watch": "cdk-watch", + "lint": "cdk-lint", + "test": "cdk-test", + "integ": "integ-runner", + "pkglint": "pkglint -f", + "package": "cdk-package", + "awslint": "cdk-awslint", + "build+test": "yarn build && yarn test", + "build+test+package": "yarn build+test && yarn package", + "compat": "cdk-compat", + "rosetta:extract": "yarn --silent jsii-rosetta extract", + "build+extract": "yarn build && yarn rosetta:extract", + "build+test+extract": "yarn build+test && yarn rosetta:extract" + }, + "cdk-build": { + "env": { + "AWSLINT_BASE_CONSTRUCT": "true" + } + }, + "keywords": [ + "aws", + "cdk", + "constructs", + "AWS::CE", + "aws-ce" + ], + "author": { + "name": "Amazon Web Services", + "url": "https://aws.amazon.com", + "organization": true + }, + "license": "Apache-2.0", + "devDependencies": { + "@aws-cdk/cdk-build-tools": "0.0.0", + "@aws-cdk/integ-runner": "0.0.0", + "@aws-cdk/pkglint": "0.0.0", + "@types/jest": "^29.5.11", + "aws-cdk-lib": "0.0.0", + "constructs": "^10.0.0", + "@aws-cdk/integ-tests-alpha": "0.0.0" + }, + "dependencies": {}, + "peerDependencies": { + "aws-cdk-lib": "^0.0.0", + "constructs": "^10.0.0" + }, + "engines": { + "node": ">= 14.15.0" + }, + "stability": "experimental", + "maturity": "experimental", + "awscdkio": { + "announce": false + }, + "publishConfig": { + "tag": "latest" + }, + "private": false, + "pkglint": { + "exclude": [ + "naming/package-matches-directory", + "assert/assert-dependency" + ] + } +} diff --git a/packages/@aws-cdk/aws-ce-alpha/rosetta/default.ts-fixture b/packages/@aws-cdk/aws-ce-alpha/rosetta/default.ts-fixture new file mode 100644 index 0000000000000..d9cc60baeb345 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/rosetta/default.ts-fixture @@ -0,0 +1,13 @@ +// Fixture with packages imported, but nothing else +import { Stack } from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +import * as ce from '@aws-cdk/aws-ce-alpha'; +import * as sns from 'aws-cdk-lib/aws-sns'; + +class Fixture extends Stack { + constructor(scope: Construct, id: string) { + super(scope, id); + + /// here + } +} diff --git a/packages/@aws-cdk/aws-ce-alpha/test/anomaly-monitor.test.ts b/packages/@aws-cdk/aws-ce-alpha/test/anomaly-monitor.test.ts new file mode 100644 index 0000000000000..d2d1461e5dfb5 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/anomaly-monitor.test.ts @@ -0,0 +1,69 @@ +import { Template } from 'aws-cdk-lib/assertions'; +import { Stack } from 'aws-cdk-lib'; +import { AnomalyMonitor, MonitorType } from '../lib/anomaly-monitor'; + +let stack: Stack; +beforeEach(() => { + stack = new Stack(); +}); + +test('services monitor', () => { + new AnomalyMonitor(stack, 'Monitor', { + anomalyMonitorName: 'MyMonitor', + type: MonitorType.awsServices(), + }); + + Template.fromStack(stack).hasResourceProperties('AWS::CE::AnomalyMonitor', { + MonitorDimension: 'SERVICE', + MonitorName: 'MyMonitor', + MonitorType: 'DIMENSIONAL', + }); +}); + +test('tags monitor', () => { + new AnomalyMonitor(stack, 'Monitor', { + type: MonitorType.costAllocationTag('key', ['value1', 'value2']), + }); + + Template.fromStack(stack).hasResourceProperties('AWS::CE::AnomalyMonitor', { + MonitorName: 'Monitor', + MonitorType: 'CUSTOM', + MonitorSpecification: '{"Tags":{"Key":"key","Values":["value1","value2"]}}', + }); +}); + +test('cost categories monitor', () => { + new AnomalyMonitor(stack, 'Monitor', { + type: MonitorType.costCategory('key', 'value1'), + }); + + Template.fromStack(stack).hasResourceProperties('AWS::CE::AnomalyMonitor', { + MonitorName: 'Monitor', + MonitorType: 'CUSTOM', + MonitorSpecification: '{"CostCategories":{"Key":"key","Values":["value1"]}}', + }); +}); + +test('linked accounts monitor', () => { + new AnomalyMonitor(stack, 'Monitor', { + type: MonitorType.linkedAccounts(['123456789012', '123456789013']), + }); + + Template.fromStack(stack).hasResourceProperties('AWS::CE::AnomalyMonitor', { + MonitorName: 'Monitor', + MonitorType: 'CUSTOM', + MonitorSpecification: '{"Dimensions":{"Key":"LINKED_ACCOUNT","Values":["123456789012","123456789013"]}}', + }); +}); + +test('import from arn', () => { + const anomalyMonitorArn = stack.formatArn({ + service: 'ce', + resource: 'anomalymonitor', + resourceName: 'monitor', + }); + const anomalyMonitor = AnomalyMonitor.fromAnomalyMonitorArn(stack, 'Monitor', anomalyMonitorArn); + + // THEN + expect(anomalyMonitor.anomalyMonitorArn).toEqual(anomalyMonitorArn); +}); diff --git a/packages/@aws-cdk/aws-ce-alpha/test/anomaly-subscription.test.ts b/packages/@aws-cdk/aws-ce-alpha/test/anomaly-subscription.test.ts new file mode 100644 index 0000000000000..2424a2f8f57a2 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/anomaly-subscription.test.ts @@ -0,0 +1,83 @@ +import { Template } from 'aws-cdk-lib/assertions'; +import { Stack } from 'aws-cdk-lib'; +import { AnomalyMonitor, MonitorType } from '../lib/anomaly-monitor'; +import { AnomalySubscriber, AnomalySubscription, EmailFrequency, ThresholdExpression } from '../lib/anomaly-subscription'; +import { Topic } from 'aws-cdk-lib/aws-sns'; + +let stack: Stack; +let monitor: AnomalyMonitor; +beforeEach(() => { + stack = new Stack(); + monitor = new AnomalyMonitor(stack, 'Monitor', { + type: MonitorType.awsServices(), + }); +}); + +test('SNS subscription', () => { + const topic = new Topic(stack, 'Topic'); + + new AnomalySubscription(stack, 'Subscription', { + anomalySubscriptionName: 'MySubscription', + anomalyMonitors: [monitor], + subscriber: AnomalySubscriber.sns(topic), + thresholdExpression: ThresholdExpression.aboveUsdAmount(100), + }); + + Template.fromStack(stack).hasResourceProperties('AWS::CE::AnomalySubscription', { + Frequency: 'IMMEDIATE', + MonitorArnList: [{ Ref: 'Monitor5337499C' }], + Subscribers: [ + { + Address: { Ref: 'TopicBFC7AF6E' }, + Type: 'SNS', + }, + ], + SubscriptionName: 'MySubscription', + ThresholdExpression: '{"Dimensions":{"Key":"ANOMALY_TOTAL_IMPACT_ABSOLUTE","MatchOptions":["GREATER_THAN_OR_EQUAL"],"Values":["100"]}}', + }); + + Template.fromStack(stack).hasResourceProperties('AWS::SNS::TopicPolicy', { + PolicyDocument: { + Statement: [{ + Action: 'sns:Publish', + Condition: { + StringEquals: { + 'aws:SourceAccount': [{ Ref: 'AWS::AccountId' }], + }, + }, + Effect: 'Allow', + Principal: { Service: 'costalerts.amazonaws.com' }, + Resource: { Ref: 'TopicBFC7AF6E' }, + Sid: '0', + }], + }, + Topics: [{ Ref: 'TopicBFC7AF6E' }], + }); +}); + +test('Emails subscription', () => { + new AnomalySubscription(stack, 'Subscription', { + anomalyMonitors: [monitor], + subscriber: AnomalySubscriber.emails(EmailFrequency.WEEKLY, [ + 'first@example.com', + 'second@example.com', + ]), + thresholdExpression: ThresholdExpression.aboveUsdAmountOrPercentage(500, 20), + }); + + Template.fromStack(stack).hasResourceProperties('AWS::CE::AnomalySubscription', { + Frequency: 'WEEKLY', + Subscribers: [ + { + Address: 'first@example.com', + Type: 'EMAIL', + }, + { + Address: 'second@example.com', + Type: 'EMAIL', + }, + ], + SubscriptionName: 'Subscription', + ThresholdExpression: '{"Or":[{"Dimensions":{"Key":"ANOMALY_TOTAL_IMPACT_ABSOLUTE","MatchOptions":["GREATER_THAN_OR_EQUAL"],"Values":["500"]}},{"Dimensions":{"Key":"ANOMALY_TOTAL_IMPACT_PERCENTAGE","MatchOptions":["GREATER_THAN_OR_EQUAL"],"Values":["20"]}}]}', + }); +}); diff --git a/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.assets.json b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.assets.json new file mode 100644 index 0000000000000..d4ea0e7f26f96 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.assets.json @@ -0,0 +1,19 @@ +{ + "version": "36.0.0", + "files": { + "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22": { + "source": { + "path": "CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.template.json b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.template.json new file mode 100644 index 0000000000000..ad9d0fb73d1dd --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.template.json @@ -0,0 +1,36 @@ +{ + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk-integ-ce-anomaly.assets.json b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk-integ-ce-anomaly.assets.json new file mode 100644 index 0000000000000..5876026195a9b --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk-integ-ce-anomaly.assets.json @@ -0,0 +1,19 @@ +{ + "version": "36.0.0", + "files": { + "acb3ef4ebf037c67c3351eb64506d5c4fd8744b9fc76a2b91e9067ddfc915ab2": { + "source": { + "path": "cdk-integ-ce-anomaly.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "acb3ef4ebf037c67c3351eb64506d5c4fd8744b9fc76a2b91e9067ddfc915ab2.json", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk-integ-ce-anomaly.template.json b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk-integ-ce-anomaly.template.json new file mode 100644 index 0000000000000..ee50bb42cb92f --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk-integ-ce-anomaly.template.json @@ -0,0 +1,116 @@ +{ + "Resources": { + "TagsMonitor11E84F58": { + "Type": "AWS::CE::AnomalyMonitor", + "Properties": { + "MonitorName": "cdkintegceanomalyTagsMonitorCA9FC1C1", + "MonitorSpecification": "{\"Tags\":{\"Key\":\"Key\",\"Values\":[\"Value1\",\"Value2\"]}}", + "MonitorType": "CUSTOM" + } + }, + "CostCategoryMonitorAA4784FA": { + "Type": "AWS::CE::AnomalyMonitor", + "Properties": { + "MonitorName": "cdkintegceanomalyCostCategoryMonitorAEA35A02", + "MonitorSpecification": "{\"CostCategories\":{\"Key\":\"CostCategoryKey\",\"Values\":[\"CostCategoryValue\"]}}", + "MonitorType": "CUSTOM" + } + }, + "TopicBFC7AF6E": { + "Type": "AWS::SNS::Topic" + }, + "TopicPolicyA1747468": { + "Type": "AWS::SNS::TopicPolicy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": "sns:Publish", + "Condition": { + "StringEquals": { + "aws:SourceAccount": [ + { + "Ref": "AWS::AccountId" + } + ] + } + }, + "Effect": "Allow", + "Principal": { + "Service": "costalerts.amazonaws.com" + }, + "Resource": { + "Ref": "TopicBFC7AF6E" + }, + "Sid": "0" + } + ], + "Version": "2012-10-17" + }, + "Topics": [ + { + "Ref": "TopicBFC7AF6E" + } + ] + } + }, + "Subscription391C9821": { + "Type": "AWS::CE::AnomalySubscription", + "Properties": { + "Frequency": "IMMEDIATE", + "MonitorArnList": [ + { + "Ref": "TagsMonitor11E84F58" + }, + { + "Ref": "CostCategoryMonitorAA4784FA" + } + ], + "Subscribers": [ + { + "Address": { + "Ref": "TopicBFC7AF6E" + }, + "Type": "SNS" + } + ], + "SubscriptionName": "cdkintegceanomalySubscriptionC6F77DFD", + "ThresholdExpression": "{\"Dimensions\":{\"Key\":\"ANOMALY_TOTAL_IMPACT_ABSOLUTE\",\"MatchOptions\":[\"GREATER_THAN_OR_EQUAL\"],\"Values\":[\"100\"]}}" + } + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk.out b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk.out new file mode 100644 index 0000000000000..1f0068d32659a --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/cdk.out @@ -0,0 +1 @@ +{"version":"36.0.0"} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/integ.json b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/integ.json new file mode 100644 index 0000000000000..3554f6225e341 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/integ.json @@ -0,0 +1,12 @@ +{ + "version": "36.0.0", + "testCases": { + "CeAnomalyTest/DefaultTest": { + "stacks": [ + "cdk-integ-ce-anomaly" + ], + "assertionStack": "CeAnomalyTest/DefaultTest/DeployAssert", + "assertionStackName": "CeAnomalyTestDefaultTestDeployAssertDEF6AC0B" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/manifest.json b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/manifest.json new file mode 100644 index 0000000000000..facf36d559dd3 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/manifest.json @@ -0,0 +1,137 @@ +{ + "version": "36.0.0", + "artifacts": { + "cdk-integ-ce-anomaly.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "cdk-integ-ce-anomaly.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "cdk-integ-ce-anomaly": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "cdk-integ-ce-anomaly.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/acb3ef4ebf037c67c3351eb64506d5c4fd8744b9fc76a2b91e9067ddfc915ab2.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "cdk-integ-ce-anomaly.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "cdk-integ-ce-anomaly.assets" + ], + "metadata": { + "/cdk-integ-ce-anomaly/TagsMonitor/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "TagsMonitor11E84F58" + } + ], + "/cdk-integ-ce-anomaly/CostCategoryMonitor/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "CostCategoryMonitorAA4784FA" + } + ], + "/cdk-integ-ce-anomaly/Topic/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "TopicBFC7AF6E" + } + ], + "/cdk-integ-ce-anomaly/Topic/Policy/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "TopicPolicyA1747468" + } + ], + "/cdk-integ-ce-anomaly/Subscription/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "Subscription391C9821" + } + ], + "/cdk-integ-ce-anomaly/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/cdk-integ-ce-anomaly/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "cdk-integ-ce-anomaly" + }, + "CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "CeAnomalyTestDefaultTestDeployAssertDEF6AC0B": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "CeAnomalyTestDefaultTestDeployAssertDEF6AC0B.assets" + ], + "metadata": { + "/CeAnomalyTest/DefaultTest/DeployAssert/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/CeAnomalyTest/DefaultTest/DeployAssert/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "CeAnomalyTest/DefaultTest/DeployAssert" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/tree.json b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/tree.json new file mode 100644 index 0000000000000..cfb37cd96863b --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.js.snapshot/tree.json @@ -0,0 +1,270 @@ +{ + "version": "tree-0.1", + "tree": { + "id": "App", + "path": "", + "children": { + "cdk-integ-ce-anomaly": { + "id": "cdk-integ-ce-anomaly", + "path": "cdk-integ-ce-anomaly", + "children": { + "TagsMonitor": { + "id": "TagsMonitor", + "path": "cdk-integ-ce-anomaly/TagsMonitor", + "children": { + "Resource": { + "id": "Resource", + "path": "cdk-integ-ce-anomaly/TagsMonitor/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::CE::AnomalyMonitor", + "aws:cdk:cloudformation:props": { + "monitorName": "cdkintegceanomalyTagsMonitorCA9FC1C1", + "monitorSpecification": "{\"Tags\":{\"Key\":\"Key\",\"Values\":[\"Value1\",\"Value2\"]}}", + "monitorType": "CUSTOM" + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ce.CfnAnomalyMonitor", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/aws-ce-alpha.AnomalyMonitor", + "version": "0.0.0" + } + }, + "CostCategoryMonitor": { + "id": "CostCategoryMonitor", + "path": "cdk-integ-ce-anomaly/CostCategoryMonitor", + "children": { + "Resource": { + "id": "Resource", + "path": "cdk-integ-ce-anomaly/CostCategoryMonitor/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::CE::AnomalyMonitor", + "aws:cdk:cloudformation:props": { + "monitorName": "cdkintegceanomalyCostCategoryMonitorAEA35A02", + "monitorSpecification": "{\"CostCategories\":{\"Key\":\"CostCategoryKey\",\"Values\":[\"CostCategoryValue\"]}}", + "monitorType": "CUSTOM" + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ce.CfnAnomalyMonitor", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/aws-ce-alpha.AnomalyMonitor", + "version": "0.0.0" + } + }, + "Topic": { + "id": "Topic", + "path": "cdk-integ-ce-anomaly/Topic", + "children": { + "Resource": { + "id": "Resource", + "path": "cdk-integ-ce-anomaly/Topic/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::SNS::Topic", + "aws:cdk:cloudformation:props": {} + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_sns.CfnTopic", + "version": "0.0.0" + } + }, + "Policy": { + "id": "Policy", + "path": "cdk-integ-ce-anomaly/Topic/Policy", + "children": { + "Resource": { + "id": "Resource", + "path": "cdk-integ-ce-anomaly/Topic/Policy/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::SNS::TopicPolicy", + "aws:cdk:cloudformation:props": { + "policyDocument": { + "Statement": [ + { + "Action": "sns:Publish", + "Condition": { + "StringEquals": { + "aws:SourceAccount": [ + { + "Ref": "AWS::AccountId" + } + ] + } + }, + "Effect": "Allow", + "Principal": { + "Service": "costalerts.amazonaws.com" + }, + "Resource": { + "Ref": "TopicBFC7AF6E" + }, + "Sid": "0" + } + ], + "Version": "2012-10-17" + }, + "topics": [ + { + "Ref": "TopicBFC7AF6E" + } + ] + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_sns.CfnTopicPolicy", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_sns.TopicPolicy", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_sns.Topic", + "version": "0.0.0" + } + }, + "Subscription": { + "id": "Subscription", + "path": "cdk-integ-ce-anomaly/Subscription", + "children": { + "Resource": { + "id": "Resource", + "path": "cdk-integ-ce-anomaly/Subscription/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::CE::AnomalySubscription", + "aws:cdk:cloudformation:props": { + "frequency": "IMMEDIATE", + "monitorArnList": [ + { + "Ref": "TagsMonitor11E84F58" + }, + { + "Ref": "CostCategoryMonitorAA4784FA" + } + ], + "subscribers": [ + { + "type": "SNS", + "address": { + "Ref": "TopicBFC7AF6E" + } + } + ], + "subscriptionName": "cdkintegceanomalySubscriptionC6F77DFD", + "thresholdExpression": "{\"Dimensions\":{\"Key\":\"ANOMALY_TOTAL_IMPACT_ABSOLUTE\",\"MatchOptions\":[\"GREATER_THAN_OR_EQUAL\"],\"Values\":[\"100\"]}}" + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ce.CfnAnomalySubscription", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/aws-ce-alpha.AnomalySubscription", + "version": "0.0.0" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "cdk-integ-ce-anomaly/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "cdk-integ-ce-anomaly/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" + } + }, + "CeAnomalyTest": { + "id": "CeAnomalyTest", + "path": "CeAnomalyTest", + "children": { + "DefaultTest": { + "id": "DefaultTest", + "path": "CeAnomalyTest/DefaultTest", + "children": { + "Default": { + "id": "Default", + "path": "CeAnomalyTest/DefaultTest/Default", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.3.0" + } + }, + "DeployAssert": { + "id": "DeployAssert", + "path": "CeAnomalyTest/DefaultTest/DeployAssert", + "children": { + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "CeAnomalyTest/DefaultTest/DeployAssert/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "CeAnomalyTest/DefaultTest/DeployAssert/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests-alpha.IntegTestCase", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests-alpha.IntegTest", + "version": "0.0.0" + } + }, + "Tree": { + "id": "Tree", + "path": "Tree", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.3.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.App", + "version": "0.0.0" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.ts b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.ts new file mode 100644 index 0000000000000..8028469aba265 --- /dev/null +++ b/packages/@aws-cdk/aws-ce-alpha/test/integ.anomaly.ts @@ -0,0 +1,33 @@ +import { App, Stack } from 'aws-cdk-lib'; +import * as integ from '@aws-cdk/integ-tests-alpha'; +import { Construct } from 'constructs'; +import { AnomalyMonitor, AnomalySubscriber, AnomalySubscription, MonitorType, ThresholdExpression } from '../lib'; +import { Topic } from 'aws-cdk-lib/aws-sns'; + +class TestStack extends Stack { + constructor(scope: Construct, id: string) { + super(scope, id); + + const tagsMonitor = new AnomalyMonitor(this, 'TagsMonitor', { + type: MonitorType.costAllocationTag('Key', ['Value1', 'Value2']), + }); + + const costCategoryMonitor = new AnomalyMonitor(this, 'CostCategoryMonitor', { + type: MonitorType.costCategory('CostCategoryKey', 'CostCategoryValue'), + }); + + const topic = new Topic(this, 'Topic'); + + new AnomalySubscription(this, 'Subscription', { + anomalyMonitors: [tagsMonitor, costCategoryMonitor], + subscriber: AnomalySubscriber.sns(topic), + thresholdExpression: ThresholdExpression.aboveUsdAmount(100), + }); + } +} + +const app = new App(); + +new integ.IntegTest(app, 'CeAnomalyTest', { + testCases: [new TestStack(app, 'cdk-integ-ce-anomaly')], +});