cdk-cost-analyzer 0.1.17 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/.cdk-cost-analyzer-cache/metadata.json +10 -10
  2. package/.kiro/settings/mcp.json +13 -4
  3. package/.kiro/specs/cdk-cost-analyzer-blog/COMPLETION_SUMMARY.md +99 -0
  4. package/.kiro/specs/cdk-cost-analyzer-blog/blog-post-devto.md +466 -0
  5. package/.kiro/specs/cdk-cost-analyzer-blog/blog-post-narrative.md +240 -0
  6. package/.kiro/specs/cdk-cost-analyzer-blog/blog-post.md +456 -0
  7. package/.kiro/specs/cdk-cost-analyzer-blog/design.md +507 -0
  8. package/.kiro/specs/cdk-cost-analyzer-blog/metadata.md +37 -0
  9. package/.kiro/specs/cdk-cost-analyzer-blog/output-examples/CI_CD_INTEGRATION.md +872 -0
  10. package/.kiro/specs/cdk-cost-analyzer-blog/output-examples/README.md +131 -0
  11. package/.kiro/specs/cdk-cost-analyzer-blog/output-examples/SUPPORTED_SERVICES.md +515 -0
  12. package/.kiro/specs/cdk-cost-analyzer-blog/output-examples/TASK_SUMMARY.md +153 -0
  13. package/.kiro/specs/cdk-cost-analyzer-blog/output-examples/USAGE_EXAMPLES.md +319 -0
  14. package/.kiro/specs/cdk-cost-analyzer-blog/output-examples/diff-mode-text.txt +31 -0
  15. package/.kiro/specs/cdk-cost-analyzer-blog/output-examples/single-template-text.txt +72 -0
  16. package/.kiro/specs/cdk-cost-analyzer-blog/requirements.md +117 -0
  17. package/.kiro/specs/cdk-cost-analyzer-blog/tasks.md +97 -0
  18. package/.kiro/specs/fix-dynamodb-pricing-detection/design.md +473 -0
  19. package/.kiro/specs/fix-dynamodb-pricing-detection/requirements.md +105 -0
  20. package/.kiro/specs/fix-dynamodb-pricing-detection/tasks.md +178 -0
  21. package/README.md +1 -1
  22. package/dist/config/ConfigManager.js +5 -1
  23. package/dist/config/types.d.ts +16 -0
  24. package/dist/config/types.js +1 -1
  25. package/dist/pricing/PricingService.js +4 -2
  26. package/dist/pricing/calculators/DynamoDBCalculator.d.ts +4 -0
  27. package/dist/pricing/calculators/DynamoDBCalculator.js +57 -28
  28. package/dist/releasetag.txt +1 -1
  29. package/docs/CALCULATORS.md +23 -27
  30. package/docs/CONFIGURATION.md +14 -0
  31. package/examples/.cdk-cost-analyzer.yml +7 -0
  32. package/examples/single-stack/.cdk-cost-analyzer.yml +5 -3
  33. package/package.json +1 -1
@@ -0,0 +1,240 @@
1
+ # CDK Cost Analyzer: How I Learned to Stop Worrying and Love Infrastructure Costs
2
+
3
+ ## Background: My CDK Cost Problem
4
+
5
+ I've been working with AWS CDK for a while now, and I love it. Define infrastructure in TypeScript, run `cdk deploy`, and boom—everything's provisioned. It's elegant, it's powerful, and it makes infrastructure feel like just another part of my codebase.
6
+
7
+ But there's this one question that kept nagging me during every project: "How much is this going to cost?"
8
+
9
+ At my current project, I'm building a new microservices platform. We're using ECS Fargate, Application Load Balancers, NAT Gateways—the usual suspects. My team lead kept asking about monthly costs, and honestly? I had no idea. I'd mumble something about "checking the AWS Pricing Calculator" and hope the conversation moved on.
10
+
11
+ Here's the thing: budget constraints are real. When you're pitching a new feature to stakeholders, "I don't know what it'll cost" isn't a great answer. And when the monthly AWS bill arrives and it's $500 more than expected? That's a conversation nobody wants to have.
12
+
13
+ ## Here's Where My Problem Started
14
+
15
+ So there I was, reviewing a pull request from a colleague. The code looked fine—adding a NAT Gateway to enable private subnet internet access. Standard stuff. I approved it, we merged it, deployed to production.
16
+
17
+ Fast forward to the end of the month. Our AWS bill showed an extra $43 for... a NAT Gateway? I had to look it up. Turns out, NAT Gateways cost about $32 per month just for existing, plus data processing fees. Nobody mentioned this. Nobody knew.
18
+
19
+ The worst part? This wasn't even a mistake. We needed that NAT Gateway. But I should have known about the cost before deployment, not after.
20
+
21
+ ## The Manual Approach (That I Hated)
22
+
23
+ I tried doing this properly. For the next infrastructure change, I sat down with the CloudFormation template CDK generated and started manually calculating costs:
24
+
25
+ 1. Open the template, find all the resources
26
+ 2. Look up each service in the AWS Pricing Calculator
27
+ 3. Make assumptions about usage (how many Lambda invocations? how much S3 storage?)
28
+ 4. Add it all up in a spreadsheet
29
+
30
+ This took me two hours. Two hours I could have spent actually building features. And I still wasn't confident in my numbers because I had to guess at usage patterns.
31
+
32
+ The AWS Pricing Calculator is great, but it doesn't integrate with my workflow. I can't automatically check if my infrastructure changes increase costs. I can't enforce cost thresholds in CI/CD. I can't compare costs between different versions of my stack.
33
+
34
+ There had to be a better way.
35
+
36
+ ## The Solution I Built
37
+
38
+ That's when I started working on cdk-cost-analyzer. The idea was simple: analyze CloudFormation templates and calculate estimated monthly costs automatically. Query the AWS Pricing API for current pricing, apply reasonable usage assumptions, and give me a number I can actually work with.
39
+
40
+ I wanted three things:
41
+
42
+ **Single Template Analysis**: Just tell me what this stack will cost.
43
+
44
+ **Diff Mode**: Show me the cost difference between two versions.
45
+
46
+ **CI/CD Integration**: Catch cost increases automatically in my pipeline.
47
+
48
+ ### What It Supports
49
+
50
+ Right now, the tool handles 13 AWS services—the ones I use most often:
51
+
52
+ **Compute**: Lambda, EC2, ECS (both Fargate and EC2)
53
+
54
+ **Storage**: S3
55
+
56
+ **Database**: RDS (MySQL, PostgreSQL, Aurora, etc.) and DynamoDB
57
+
58
+ **Networking**: NAT Gateway, ALB, NLB, VPC Endpoints
59
+
60
+ **Content Delivery**: CloudFront
61
+
62
+ **API Management**: API Gateway (REST, HTTP, WebSocket)
63
+
64
+ **Caching**: ElastiCache
65
+
66
+ It queries the AWS Pricing API for real, current pricing in your region. No hardcoded prices that go stale.
67
+
68
+ ## How I Use It
69
+
70
+ ### Installation
71
+
72
+ I keep it simple:
73
+
74
+ ```bash
75
+ # Global installation
76
+ npm install -g cdk-cost-analyzer
77
+
78
+ # Or just use npx
79
+ npx cdk-cost-analyzer --help
80
+ ```
81
+
82
+ ### My First Analysis
83
+
84
+ After synthesizing my CDK app, I ran:
85
+
86
+ ```bash
87
+ npx cdk-cost-analyzer analyze cdk.out/MyStack.template.json
88
+ ```
89
+
90
+ And got this:
91
+
92
+ ```text
93
+ Total Monthly Cost: $89.43 USD
94
+ Region: eu-central-1
95
+
96
+ Cost Breakdown:
97
+ - NAT Gateway: $43.16 (48.3%)
98
+ - Application Load Balancer: $25.55 (28.6%)
99
+ - ECS Fargate Service: $20.72 (23.2%)
100
+
101
+ Total Resources: 36
102
+ Supported Resources: 3
103
+ Unsupported Resources: 33
104
+ ```
105
+
106
+ That NAT Gateway? Nearly half my monthly cost. Suddenly, that $43 surprise from before made sense. And now I could see it before deploying.
107
+
108
+ ### The Game-Changer: Diff Mode
109
+
110
+ This is where it gets really useful. Before merging any infrastructure PR, I run:
111
+
112
+ ```bash
113
+ npx cdk-cost-analyzer compare \
114
+ cdk.out.before/MyStack.template.json \
115
+ cdk.out.after/MyStack.template.json
116
+ ```
117
+
118
+ Output:
119
+
120
+ ```text
121
+ Total Cost Delta: +$2.08
122
+
123
+ ADDED RESOURCES:
124
+ • Lambda Function: +$2.08/month [medium confidence]
125
+ - 1,000,000 invocations per month
126
+ - 128MB memory allocation
127
+ - 1000ms average duration
128
+
129
+ • DynamoDB Table: $0.00 [unknown - not yet supported]
130
+ • API Gateway: $0.00 [unknown - not yet supported]
131
+ ```
132
+
133
+ Now when I review PRs, I can ask: "Is this $2 per month worth it?" instead of "What does this do?" It changes the conversation from technical implementation to business value.
134
+
135
+ ### Automating It in CI/CD
136
+
137
+ I added this to my GitLab CI pipeline:
138
+
139
+ ```yaml
140
+ cost-analysis:
141
+ stage: cost-analysis
142
+ image: node:18
143
+ before_script:
144
+ - npm install -g cdk-cost-analyzer
145
+ script:
146
+ - |
147
+ cdk-cost-analyzer pipeline \
148
+ --synth \
149
+ --cdk-app-path ./infrastructure \
150
+ --region us-east-1 \
151
+ --format markdown \
152
+ --post-to-gitlab
153
+ only:
154
+ - merge_requests
155
+ ```
156
+
157
+ Now every merge request gets a cost analysis comment automatically. My team sees cost implications during code review, not after deployment.
158
+
159
+ ### Setting Cost Thresholds
160
+
161
+ I configured thresholds to fail the pipeline if costs get out of hand:
162
+
163
+ ```yaml
164
+ # .cdk-cost-analyzer.yml
165
+ thresholds:
166
+ environments:
167
+ production:
168
+ warning: 25 # USD per month
169
+ error: 100 # Fails the pipeline
170
+ development:
171
+ warning: 100
172
+ error: 500
173
+ ```
174
+
175
+ If someone tries to add infrastructure that increases production costs by more than $100/month, the pipeline fails. They need to justify it before we merge.
176
+
177
+ ### Customizing for My Usage
178
+
179
+ The default assumptions didn't match my actual usage, so I customized them:
180
+
181
+ ```yaml
182
+ # .kiro/specs/cdk-cost-analyzer-blog/blog-post-narrative.md
183
+ region: eu-central-1
184
+ assumptions:
185
+ natGateway:
186
+ dataProcessingGB: 500 # We process way more than the default
187
+ lambda:
188
+ monthlyInvocations: 5000000 # High traffic API
189
+ averageDurationMs: 200
190
+ alb:
191
+ newConnectionsPerSecond: 100
192
+ processedBytesGB: 2000
193
+ ```
194
+
195
+ This gave me much more accurate estimates for my specific workload.
196
+
197
+ ## What I've Learned
198
+
199
+ ### Cost Visibility Changes Everything
200
+
201
+ Knowing that a NAT Gateway costs $43/month before adding it changes the decision-making process. Maybe we don't need it. Maybe VPC endpoints are cheaper. Maybe we do need it, but at least we know what we're signing up for.
202
+
203
+ ### Diff Mode Transforms Code Review
204
+
205
+ I used to review infrastructure PRs by reading the CDK code and trying to understand what resources would be created. Now I just look at the cost diff. If it says "+$50/month," I know to ask questions. If it says "+$2/month," I probably don't need to dig deep.
206
+
207
+ ### Automation Prevents Surprises
208
+
209
+ Since adding this to CI/CD, we haven't had a single surprise cost increase. Every change is analyzed, every cost increase is visible, and nothing slips through.
210
+
211
+ ### Custom Assumptions Matter
212
+
213
+ The default assumptions are reasonable, but they're not your assumptions. I spent an hour customizing mine based on CloudWatch metrics from our existing infrastructure. Now my estimates are much more accurate.
214
+
215
+ ### It's Not Perfect, But It's Better
216
+
217
+ The tool doesn't support every AWS service. It doesn't include data transfer costs. It doesn't account for Reserved Instances or Savings Plans. But you know what? It's still way better than manually calculating costs or, worse, not calculating them at all.
218
+
219
+ ## Try It Yourself
220
+
221
+ I've open-sourced the tool:
222
+
223
+ - **GitHub**: [github.com/yvovanzee/cdk-cost-analyzer](https://github.com/yvovanzee/cdk-cost-analyzer)
224
+ - **npm**: [npmjs.com/package/cdk-cost-analyzer](https://www.npmjs.com/package/cdk-cost-analyzer)
225
+
226
+ Install it and analyze your infrastructure:
227
+
228
+ ```bash
229
+ npx cdk-cost-analyzer analyze cdk.out/YourStack.template.json
230
+ ```
231
+
232
+ If you find bugs or want to add support for more AWS services, PRs are welcome. I built this to solve my own problem, but I'm hoping it helps others too.
233
+
234
+ ## Final Thoughts
235
+
236
+ I'm not saying you should obsess over every dollar of infrastructure cost. But you should know what you're spending. You should be able to answer when someone asks "How much will this cost?" And you should catch expensive changes before they hit production.
237
+
238
+ CDK Cost Analyzer helps me do that. Maybe it'll help you too.
239
+
240
+ Give it a try on your next CDK project. Let me know how it goes.
@@ -0,0 +1,456 @@
1
+ # CDK Cost Analyzer: Understanding Your AWS Infrastructure Costs Before Deployment
2
+
3
+ ## Background
4
+
5
+ Working with AWS CDK makes infrastructure deployment straightforward. You define your infrastructure in code, run `cdk deploy`, and AWS provisions the resources. However, one question consistently arises during development: "How much will this cost?"
6
+
7
+ This question matters. Budget constraints are real, stakeholders need cost estimates, and unexpected infrastructure costs can derail projects. A NAT Gateway that costs $32 per month just for being active, an Application Load Balancer at $16 per month base cost, or an RDS instance that ranges from $50 to $500+ per month—these costs add up quickly.
8
+
9
+ CDK abstracts infrastructure details effectively, but this abstraction hides cost implications. You might add a NAT Gateway to enable private subnet internet access without realizing the monthly cost impact. You could deploy an Application Load Balancer for a development environment when a simpler solution would suffice. These decisions, made without cost visibility, lead to budget surprises.
10
+
11
+ ## The Challenge
12
+
13
+ CDK generates CloudFormation templates that define your infrastructure. While these templates specify every resource in detail, they provide no cost information. To estimate costs, you must:
14
+
15
+ 1. Identify each resource in the template
16
+ 2. Look up pricing for each service in your region
17
+ 3. Calculate monthly costs based on usage assumptions
18
+ 4. Sum the total across all resources
19
+
20
+ This manual process is time-consuming and error-prone. The AWS Pricing Calculator helps, but it does not integrate with your CDK workflow. You cannot automatically check if infrastructure changes increase costs. You cannot enforce cost thresholds in your CI/CD pipeline. You cannot compare costs between different versions of your stack.
21
+
22
+ Consider a specific scenario: You add a NAT Gateway to your VPC to enable private subnet internet access. You commit the change, create a pull request, and deploy to production. Only when the monthly AWS bill arrives do you discover the NAT Gateway costs approximately $43 per month—$32 for the hourly charge plus data processing fees. This cost might be justified, but you should know about it before deployment, not after.
23
+
24
+ ## Solution: CDK Cost Analyzer
25
+
26
+ The cdk-cost-analyzer tool addresses this challenge by analyzing CloudFormation templates and calculating estimated monthly costs. The tool queries the AWS Pricing API for current, region-specific pricing and applies usage assumptions to generate cost estimates.
27
+
28
+ ### How It Works
29
+
30
+ The tool operates in three modes:
31
+
32
+ **Single Template Analysis**: Analyze one CloudFormation template to understand baseline infrastructure costs.
33
+
34
+ **Diff Mode**: Compare two templates to identify cost changes between versions.
35
+
36
+ **CI/CD Integration**: Automate cost analysis in your deployment pipeline with configurable cost thresholds.
37
+
38
+ ### Supported AWS Services
39
+
40
+ The tool currently supports 13 AWS services across major categories:
41
+
42
+ **Compute**:
43
+ - AWS Lambda
44
+ - Amazon EC2
45
+ - Amazon ECS (Fargate and EC2)
46
+
47
+ **Storage**:
48
+ - Amazon S3
49
+
50
+ **Database**:
51
+ - Amazon RDS (MySQL, PostgreSQL, MariaDB, Oracle, SQL Server, Aurora)
52
+ - Amazon DynamoDB
53
+
54
+ **Networking**:
55
+ - NAT Gateway
56
+ - Application Load Balancer
57
+ - Network Load Balancer
58
+ - VPC Endpoint
59
+
60
+ **Content Delivery**:
61
+ - Amazon CloudFront
62
+
63
+ **API Management**:
64
+ - Amazon API Gateway (REST, HTTP, WebSocket)
65
+
66
+ **Caching**:
67
+ - Amazon ElastiCache (Redis, Memcached)
68
+
69
+ The tool uses the AWS Pricing API to fetch current pricing data for your specified region, ensuring estimates reflect actual AWS pricing.
70
+
71
+ ## Getting Started
72
+
73
+ ### Installation
74
+
75
+ Install the tool globally via npm or use npx to run it without installation:
76
+
77
+ ```bash
78
+ # Global installation
79
+ npm install -g cdk-cost-analyzer
80
+
81
+ # Or use with npx (no installation required)
82
+ npx cdk-cost-analyzer --help
83
+ ```
84
+
85
+ ### Prerequisites
86
+
87
+ - Node.js 18 or later
88
+ - AWS credentials configured (for AWS Pricing API access)
89
+ - CloudFormation templates generated by CDK
90
+
91
+ The tool requires AWS credentials to query the Pricing API. Configure credentials using environment variables, AWS CLI configuration, or IAM roles. The required IAM permissions are:
92
+
93
+ ```json
94
+ {
95
+ "Version": "2012-10-17",
96
+ "Statement": [
97
+ {
98
+ "Effect": "Allow",
99
+ "Action": [
100
+ "pricing:GetProducts",
101
+ "pricing:DescribeServices"
102
+ ],
103
+ "Resource": "*"
104
+ }
105
+ ]
106
+ }
107
+ ```
108
+
109
+ ### Basic Usage
110
+
111
+ First, synthesize your CDK application to generate CloudFormation templates:
112
+
113
+ ```bash
114
+ cd your-cdk-project
115
+ npx cdk synth
116
+ ```
117
+
118
+ Then analyze the generated template:
119
+
120
+ ```bash
121
+ npx cdk-cost-analyzer analyze cdk.out/YourStack.template.json
122
+ ```
123
+
124
+ ### Example Output
125
+
126
+ ```text
127
+ Total Monthly Cost: $89.43 USD
128
+ Region: eu-central-1
129
+
130
+ Cost Breakdown:
131
+ - NAT Gateway: $43.16 (48.3%)
132
+ - Application Load Balancer: $25.55 (28.6%)
133
+ - ECS Fargate Service: $20.72 (23.2%)
134
+
135
+ Total Resources: 36
136
+ Supported Resources: 3
137
+ Unsupported Resources: 33
138
+ ```
139
+
140
+ ### Interpreting Results
141
+
142
+ The output shows:
143
+
144
+ **Total Monthly Cost**: Estimated monthly cost for all supported resources in the template.
145
+
146
+ **Cost Breakdown**: Individual resource costs sorted by expense, with percentage of total cost.
147
+
148
+ **Resource Counts**: Total resources in the template, how many are supported by the tool, and how many are not yet supported.
149
+
150
+ The example reveals that the NAT Gateway accounts for nearly half the monthly infrastructure cost. This information helps you make informed decisions about whether a NAT Gateway is necessary or if alternatives like VPC endpoints could reduce costs.
151
+
152
+ ## Practical Examples
153
+
154
+ ### Single Template Analysis
155
+
156
+ Analyze a template to understand baseline costs:
157
+
158
+ ```bash
159
+ npx cdk-cost-analyzer analyze demo/cdk.out/demo-dev.template.json
160
+ ```
161
+
162
+ Output:
163
+
164
+ ```text
165
+ Total Monthly Cost: $89.43 USD
166
+ Region: eu-central-1
167
+
168
+ Cost Breakdown:
169
+ - NAT Gateway: $43.16 (48.3%)
170
+ Hourly rate: $0.0520/hour × 730 hours = $37.96/month
171
+ Data processing: $0.0520/GB × 100 GB = $5.20/month
172
+
173
+ - Application Load Balancer: $25.55 (28.6%)
174
+ Hourly rate: $0.0252/hour × 730 hours = $18.40/month
175
+ LCU charges: 25 new connections/sec, 3000 active connections/min
176
+
177
+ - ECS Fargate Service: $20.72 (23.2%)
178
+ vCPU: 0.25 vCPU × $0.04656/hour × 730 hours = $8.50/month
179
+ Memory: 0.5 GB × $0.00511/GB-hour × 730 hours = $1.87/month
180
+
181
+ Total Resources: 36
182
+ Supported Resources: 3
183
+ Unsupported Resources: 33
184
+ ```
185
+
186
+ The detailed breakdown shows pricing assumptions for each resource. The NAT Gateway cost includes both the hourly charge and data processing fees. The ALB cost includes the base hourly rate plus Load Balancer Capacity Unit (LCU) charges based on traffic assumptions.
187
+
188
+ ### Diff Mode: Comparing Infrastructure Changes
189
+
190
+ Before deploying infrastructure changes, compare costs between versions:
191
+
192
+ ```bash
193
+ npx cdk-cost-analyzer compare \
194
+ demo/cdk.out.1/demo-dev.template.json \
195
+ demo/cdk.out.2/demo-dev.template.json
196
+ ```
197
+
198
+ Output:
199
+
200
+ ```text
201
+ Total Cost Delta: +$2.08
202
+
203
+ ADDED RESOURCES:
204
+ • Lambda Function: +$2.08/month [medium confidence]
205
+ - 1,000,000 invocations per month
206
+ - 128MB memory allocation
207
+ - 1000ms average duration
208
+
209
+ • DynamoDB Table: $0.00 [unknown - not yet supported]
210
+ • API Gateway: $0.00 [unknown - not yet supported]
211
+ • 17 new resources total
212
+
213
+ REMOVED RESOURCES:
214
+ None
215
+
216
+ MODIFIED RESOURCES:
217
+ None
218
+ ```
219
+
220
+ This comparison shows that adding a Lambda function increases monthly costs by approximately $2.08. While DynamoDB and API Gateway costs are not yet calculated, the tool identifies these resources so you can manually estimate their costs.
221
+
222
+ Diff mode proves invaluable during code review. When reviewing a pull request that adds infrastructure, you can immediately see the cost impact. This visibility enables informed discussions about whether the cost is justified and whether alternatives exist.
223
+
224
+ ### CI/CD Integration
225
+
226
+ Automate cost analysis in your deployment pipeline to catch cost increases before they reach production.
227
+
228
+ #### GitLab CI Example
229
+
230
+ ```yaml
231
+ stages:
232
+ - build
233
+ - cost-analysis
234
+ - deploy
235
+
236
+ cost-analysis:
237
+ stage: cost-analysis
238
+ image: node:18
239
+ before_script:
240
+ - npm install -g cdk-cost-analyzer
241
+ script:
242
+ - |
243
+ cdk-cost-analyzer pipeline \
244
+ --synth \
245
+ --cdk-app-path ./infrastructure \
246
+ --region us-east-1 \
247
+ --format markdown \
248
+ --post-to-gitlab
249
+ only:
250
+ - merge_requests
251
+ ```
252
+
253
+ This configuration:
254
+ - Runs cost analysis on every merge request
255
+ - Automatically synthesizes CDK templates
256
+ - Posts results as a comment on the merge request
257
+ - Provides cost visibility before merging changes
258
+
259
+ #### GitHub Actions Example
260
+
261
+ ```yaml
262
+ name: Cost Analysis
263
+
264
+ on:
265
+ pull_request:
266
+ branches: [main]
267
+
268
+ permissions:
269
+ contents: read
270
+ pull-requests: write
271
+
272
+ jobs:
273
+ analyze-costs:
274
+ runs-on: ubuntu-latest
275
+ steps:
276
+ - uses: actions/checkout@v4
277
+
278
+ - uses: actions/setup-node@v4
279
+ with:
280
+ node-version: '20.x'
281
+ cache: 'npm'
282
+
283
+ - name: Install dependencies
284
+ run: npm ci
285
+
286
+ - name: Install CDK Cost Analyzer
287
+ run: npm install -g cdk-cost-analyzer
288
+
289
+ - name: Configure AWS credentials
290
+ uses: aws-actions/configure-aws-credentials@v4
291
+ with:
292
+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
293
+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
294
+ aws-region: us-east-1
295
+
296
+ - name: Run cost analysis
297
+ run: |
298
+ cdk-cost-analyzer pipeline \
299
+ --synth \
300
+ --cdk-app-path ./infrastructure \
301
+ --region us-east-1 \
302
+ --format markdown > cost-report.md
303
+
304
+ - name: Comment PR
305
+ uses: actions/github-script@v7
306
+ with:
307
+ script: |
308
+ const fs = require('fs');
309
+ const report = fs.readFileSync('cost-report.md', 'utf8');
310
+
311
+ github.rest.issues.createComment({
312
+ issue_number: context.issue.number,
313
+ owner: context.repo.owner,
314
+ repo: context.repo.repo,
315
+ body: report
316
+ });
317
+ ```
318
+
319
+ #### Cost Threshold Enforcement
320
+
321
+ Configure cost thresholds to fail the pipeline if costs exceed defined limits:
322
+
323
+ ```yaml
324
+ # .cdk-cost-analyzer.yml
325
+ thresholds:
326
+ environments:
327
+ production:
328
+ warning: 25 # USD per month - warning only
329
+ error: 100 # USD per month - fails pipeline
330
+ development:
331
+ warning: 100
332
+ error: 500
333
+ ```
334
+
335
+ When the cost increase exceeds the error threshold, the pipeline fails, preventing deployment until the cost increase is reviewed and approved.
336
+
337
+ Benefits of CI/CD integration:
338
+
339
+ - **Automatic cost checks**: Every infrastructure change is analyzed
340
+ - **Cost visibility**: Team members see cost implications during code review
341
+ - **Cost governance**: Enforce cost thresholds to prevent unexpected increases
342
+ - **Cost awareness**: Developers consider costs when making infrastructure decisions
343
+
344
+ ### Custom Assumptions
345
+
346
+ The tool uses default usage assumptions for cost calculations. Customize these assumptions to match your specific usage patterns:
347
+
348
+ ```yaml
349
+ # .cdk-cost-analyzer.yml
350
+ region: eu-central-1
351
+ assumptions:
352
+ natGateway:
353
+ dataProcessingGB: 500 # Higher data processing than default
354
+ lambda:
355
+ monthlyInvocations: 1000000
356
+ averageDurationMs: 200
357
+ ecs:
358
+ taskCount: 4 # More tasks than default
359
+ alb:
360
+ newConnectionsPerSecond: 50
361
+ activeConnectionsPerMinute: 5000
362
+ processedBytesGB: 1000
363
+ ```
364
+
365
+ Use the configuration file with the analyze command:
366
+
367
+ ```bash
368
+ npx cdk-cost-analyzer analyze \
369
+ cdk.out/YourStack.template.json \
370
+ --config .cdk-cost-analyzer.yml
371
+ ```
372
+
373
+ Custom assumptions provide more accurate cost estimates when your usage patterns differ significantly from the defaults.
374
+
375
+ ## Understanding Cost Estimates
376
+
377
+ ### Confidence Levels
378
+
379
+ The tool assigns confidence levels to cost estimates:
380
+
381
+ **High**: Based on actual AWS Pricing API data with minimal assumptions. Examples: EC2 instances with specified instance types, RDS instances with defined instance classes.
382
+
383
+ **Medium**: Based on AWS Pricing API data with standard usage assumptions. Examples: Lambda functions, NAT Gateways, Load Balancers.
384
+
385
+ **Low**: Estimated based on typical usage patterns with significant assumptions. Examples: ECS on EC2 (depends on underlying instance costs).
386
+
387
+ **Unknown**: Resource type not yet supported by the tool.
388
+
389
+ ### Limitations
390
+
391
+ Cost estimates are based on assumptions and have limitations:
392
+
393
+ - **Usage patterns**: Actual costs depend on traffic, data transfer, and usage patterns
394
+ - **Data transfer**: Most calculators do not include data transfer costs between regions or to the internet
395
+ - **Reserved Instances**: Only on-demand pricing is calculated; Reserved Instance or Savings Plans discounts are not included
396
+ - **Free Tier**: AWS Free Tier benefits are not calculated or deducted
397
+ - **Tiered pricing**: Some services have tiered pricing that is simplified in the tool
398
+ - **Unsupported resources**: Resources not yet supported by the tool are not included in cost estimates
399
+
400
+ Despite these limitations, the tool provides valuable cost visibility for infrastructure decisions. Use the estimates as a starting point for cost discussions and budget planning.
401
+
402
+ ## Summary
403
+
404
+ CDK Cost Analyzer provides cost visibility for AWS CDK infrastructure before deployment. The tool analyzes CloudFormation templates, queries the AWS Pricing API, and generates estimated monthly costs for your infrastructure.
405
+
406
+ Key capabilities:
407
+
408
+ - **Single template analysis**: Understand baseline infrastructure costs
409
+ - **Diff mode**: Compare costs between infrastructure versions
410
+ - **CI/CD integration**: Automate cost analysis in deployment pipelines
411
+ - **Cost thresholds**: Enforce cost limits to prevent unexpected increases
412
+ - **Custom assumptions**: Tailor cost estimates to your usage patterns
413
+
414
+ The tool supports 13 AWS services across compute, storage, database, networking, content delivery, API management, and caching categories. While not all AWS services are supported, the tool covers the most common infrastructure components used in CDK applications.
415
+
416
+ Use CDK Cost Analyzer when:
417
+
418
+ - Planning new infrastructure deployments
419
+ - Reviewing infrastructure changes in pull requests
420
+ - Optimizing infrastructure costs
421
+ - Enforcing cost governance in CI/CD pipelines
422
+ - Communicating infrastructure costs to stakeholders
423
+
424
+ Cost estimates are based on AWS Pricing API data and usage assumptions. Actual costs will vary based on your specific usage patterns, but the estimates provide valuable guidance for infrastructure decisions.
425
+
426
+ ## Lessons Learned
427
+
428
+ Working with CDK Cost Analyzer has reinforced several important principles:
429
+
430
+ **Cost visibility early prevents surprises later**: Understanding infrastructure costs during development enables better decisions. When you know a NAT Gateway costs $43 per month, you can evaluate whether it is necessary or if VPC endpoints provide a more cost-effective alternative.
431
+
432
+ **Diff mode is invaluable for code review**: Seeing cost changes in pull requests transforms infrastructure review. Instead of asking "What does this change do?", you can ask "Is this $50 per month cost increase justified?" This shifts the conversation from technical implementation to business value.
433
+
434
+ **CI/CD integration catches cost increases automatically**: Automated cost analysis in deployment pipelines prevents unexpected cost increases from reaching production. Cost thresholds enforce governance without requiring manual review of every change.
435
+
436
+ **Custom assumptions enable accurate modeling**: Default assumptions provide reasonable estimates, but customizing assumptions to match your usage patterns improves accuracy. If your Lambda functions receive 10 million invocations per month instead of 1 million, custom assumptions reflect this reality.
437
+
438
+ **Open source enables community contributions**: The tool is open source, allowing the community to add support for additional AWS services, improve pricing calculations, and fix issues. If a service you need is not supported, you can contribute the implementation.
439
+
440
+ ## Try It Yourself
441
+
442
+ CDK Cost Analyzer is available on npm and GitHub:
443
+
444
+ - **GitHub Repository**: [github.com/yvovanzee/cdk-cost-analyzer](https://github.com/yvovanzee/cdk-cost-analyzer)
445
+ - **npm Package**: [npmjs.com/package/cdk-cost-analyzer](https://www.npmjs.com/package/cdk-cost-analyzer)
446
+ - **Documentation**: See the GitHub repository README for detailed documentation
447
+
448
+ Install the tool and analyze your CDK infrastructure:
449
+
450
+ ```bash
451
+ npx cdk-cost-analyzer analyze cdk.out/YourStack.template.json
452
+ ```
453
+
454
+ Contributions are welcome. If you encounter issues, have feature requests, or want to add support for additional AWS services, open an issue or submit a pull request on GitHub.
455
+
456
+ Understanding infrastructure costs before deployment enables better decisions, prevents budget surprises, and promotes cost-aware development practices. Give CDK Cost Analyzer a try on your next CDK project.