forked from brodjeski/aws-account-credits-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CFNAccountCreditTracking.yaml
545 lines (503 loc) · 23.5 KB
/
CFNAccountCreditTracking.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
AWSTemplateFormatVersion: 2010-09-09
Description: >-
This template builds an AWS account credit tracking stack with a DynamoDB
table, SNS notifications, and a scheduled Lambda function. Customizable
parameters include the credit award name, effective and expiry dates, credit
amount, and alert threshold.
Parameters:
SNSNotificationTopicName:
Type: String
Description: >-
Name of the SNS topic that will be used to send notifications when the
utilization threshold is reached.
Default: aws-credit-status
SNSNotificationEmail:
Type: String
Description: >-
Email address for receiving alerts when the credit balance falls below the
utilization threshold.
CreditsTableName:
Type: String
Description: Name of the DynamoDB table that will store credit status information.
Default: aws-credit-status
CreditAwardName:
Type: String
Description: Name of the credit award to track.
CreditEffectiveDate:
Type: String
Description: >-
Date on which the credit award becomes effective. This parameter should be
a string in the format 'YYYY-MM-DD'.
CreditExpiry:
Type: String
Description: >-
The date on which the credit award expires. This parameter should be a
string in the format 'YYYY-MM-DD'.
CreditAmount:
Type: Number
Description: Amount of credit awarded.
Default: '500.0'
AlertThreshold:
Type: Number
Description: >-
The threshold at which an alert is triggered when the credit balance falls
below this amount.
Default: '400'
LambdaEventTriggerCron:
Type: String
Description: >-
Cron expression for scheduling the Lambda function to be triggered. This
parameter should be a valid cron expression that specifies the frequency
at which the function should be triggered. The default value is set to
trigger the function every day at midnight (12:00 AM UTC).
Default: cron(0 0 * * ? *)
Metadata:
'AWS::CloudFormation::Interface':
ParameterGroups:
- Label:
default: AWS Credits Table
Parameters:
- CreditsTableName
- CreditAwardName
- CreditEffectiveDate
- CreditExpiry
- CreditAmount
- Label:
default: Alert Parameters
Parameters:
- AlertThreshold
- LambdaEventTriggerCron
- Label:
default: Notification Parameters
Parameters:
- SNSNotificationTopicName
- SNSNotificationEmail
Resources:
CreditsTable:
Type: 'AWS::DynamoDB::Table'
Properties:
AttributeDefinitions:
- AttributeName: credit_name
AttributeType: S
BillingMode: PAY_PER_REQUEST
KeySchema:
- AttributeName: credit_name
KeyType: HASH
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: true
TableName: !Ref CreditsTableName
Tags:
- Key: Project
Value: AWS Sandbox
AlarmAlertTargetSNS:
Type: 'AWS::SNS::Topic'
Properties:
DisplayName: AWS Credits Utilization Notification
TopicName: !Ref SNSNotificationTopicName
AlarmSNSSubscription:
Type: 'AWS::SNS::Subscription'
Properties:
Endpoint: !Ref SNSNotificationEmail
Protocol: email
TopicArn: !Ref AlarmAlertTargetSNS
InitializeCreditTable:
Type: 'AWS::CloudFormation::CustomResource'
DependsOn: CreditsTable
Properties:
TableName: !Ref CreditsTableName
ServiceToken: !GetAtt
- CreditsTableLambdaInitializer
- Arn
NameField: !Ref CreditAwardName
EffectiveDate: !Ref CreditEffectiveDate
ExpiryDate: !Ref CreditExpiry
CreditAmount: !Ref CreditAmount
AlertThreshold: !Ref AlertThreshold
AlertNotificationTopic: !Ref AlarmAlertTargetSNS
AWSCreditsTrackingCustomPolicy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
Description: >-
Policy allowing Lambda function to call Cost Explorer and access
DynamoDB
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: VisualEditor0
Effect: Allow
Action:
- 'sns:Publish'
- 'dynamodb:GetItem'
- 'ce:GetCostAndUsage'
- 'dynamodb:UpdateItem'
Resource: '*'
CreditTrackingLambdaRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: CreditTrackingTLambdaRole
Description: >-
Role to execute Lambda function to query Cost Explorer Server, calculate
credits used, and send notification
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
- !Ref AWSCreditsTrackingCustomPolicy
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: 'sts:AssumeRole'
CreditTrackingTableInitializerLambdaRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: CreditTrackingTableInitializerLambdaRole
Description: Role to execute Lambda function to initialize credit tracking table
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
- 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess'
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: 'sts:AssumeRole'
CreditsTableLambdaInitializer:
Type: 'AWS::Lambda::Function'
Properties:
Description: Lambda function to populate credits table with one record
Role: !GetAtt
- CreditTrackingTableInitializerLambdaRole
- Arn
FunctionName: aws_credit_table_initializer
Handler: index.lambda_handler
Runtime: python3.8
Code:
ZipFile: !Join
- '\n'
- - |
# MIT License
#
# Copyright (c) 2022 Allen Brodjeski
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import json
import urllib.request
import boto3
from botocore.exceptions import ClientError
def lambda_handler(event, context):
# Log some information about the event and context
print('Initializing DynamoDB table')
print(json.dumps(event))
print(context)
# Get the request type and response URL from the event
request_type = event['RequestType']
response_url = event['ResponseURL']
# Get the resource properties and logical resource ID from the event
properties = event['ResourceProperties']
logical_resource_id = event['LogicalResourceId']
# Initialize an empty dictionary to store the response data
responseData = {}
if request_type == 'Create':
# Set default values for the response data
responseData['Status'] = 'SUCCESS'
responseData['Reason'] = 'SUCCESS'
responseData['PhysicalResourceId'] = 'InitializedTable'
responseData['StackId'] = event['StackId']
responseData['RequestId'] = event['RequestId']
responseData['LogicalResourceId'] = logical_resource_id
# Try to create the DynamoDB table
try:
# Get the DynamoDB client
ddb_client = boto3.client('dynamodb')
# Log the resource properties
print(properties['NameField'])
print(properties['EffectiveDate'])
print(properties['ExpiryDate'])
print(properties['CreditAmount'])
print(properties['AlertThreshold'])
print(properties['AlertNotificationTopic'])
# Put the item in the DynamoDB table
response = ddb_client.put_item(
TableName=properties['TableName'],
Item={
'credit_name': {'S': properties['NameField']},
'credit_start': {'S': properties['EffectiveDate']},
'credit_expiry': {'S': properties['ExpiryDate']},
'credit_limit': {'N': str(properties['CreditAmount'])},
'credit_threshold': {'N': str(properties['AlertThreshold'])},
'credit_notification_topic': {'S': properties['AlertNotificationTopic']}
}
)
print(response)
# Catch any errors that occur
except ClientError as e:
# Log the error
logging.error(e)
# Set the status and reason in the response data
responseData['Status'] = 'FAILED'
responseData['Reason'] = e.response['Error']['Message']
# Convert the response data to JSON
json_response = json.dumps(responseData)
print('SENDING RESPONSE')
print(json_response)
# Send the response
try:
print('Response URL = ' + response_url)
response = urllib.request.urlopen(urllib.request.Request(
url=response_url,
data=bytes(json_response, 'utf-8'),
method='PUT'
),
timeout=5
)
except Exception as e:
print('send failed executing urllib.request: {e}')
# If the request type is 'Update', then update the DynamoDB table
elif request_type == 'Update':
# Set default values for the response data
responseData['Status'] = 'SUCCESS'
responseData['Reason'] = 'SUCCESS'
responseData['PhysicalResourceId'] = 'InitializedTable'
responseData['StackId'] = event['StackId']
responseData['RequestId'] = event['RequestId']
responseData['LogicalResourceId'] = logical_resource_id
try:
# Get the DynamoDB client
ddb_client = boto3.client('dynamodb')
# Log the resource properties
print(properties['NameField'])
print(properties['EffectiveDate'])
print(properties['ExpiryDate'])
print(properties['CreditAmount'])
print(properties['AlertThreshold'])
print(properties['AlertNotificationTopic'])
# Put the item in the DynamoDB table
response = ddb_client.put_item(
TableName=properties['TableName'],
Item={
'credit_name': {'S': properties['NameField']},
'credit_start': {'S': properties['EffectiveDate']},
'credit_expiry': {'S': properties['ExpiryDate']},
'credit_limit': {'N': str(properties['CreditAmount'])},
'credit_threshold': {'N': str(properties['AlertThreshold'])},
'credit_notification_topic': {'S': properties['AlertNotificationTopic']}
}
)
print(response)
except ClientError as e:
# Log the error
logging.error(e)
# Set the status and reason in the response data
responseData['Status'] = 'FAILED'
responseData['Reason'] = e.response['Error']['Message']
# Convert the response data to JSON
json_response = json.dumps(responseData)
# Send the response
try:
response = urllib.request.urlopen(urllib.request.Request(
url=response_url,
data=bytes(json_response, 'utf-8'),
method='PUT'
),
timeout=5
)
except Exception as e:
logging.error('send failed executing urllib.request: {e}')
# If the request type is 'Delete'
elif request_type == 'Delete':
# Set default values for the response data
responseData['Status'] = 'SUCCESS'
responseData['Reason'] = 'SUCCESS'
responseData['PhysicalResourceId'] = 'InitializedTable'
responseData['StackId'] = event['StackId']
responseData['RequestId'] = event['RequestId']
responseData['LogicalResourceId'] = logical_resource_id
json_response = json.dumps(responseData)
# Send the response
try:
response = urllib.request.urlopen(urllib.request.Request(
url=response_url,
data=bytes(json_response, 'utf-8'),
method='PUT'
),
timeout=5
)
except Exception as e:
logging.error('send failed executing urllib.request: {e}')
return responseData
CreditsTableLambdaTracker:
Type: 'AWS::Lambda::Function'
Properties:
Description: >-
Lambda function to query Cost Explorer API, sum up credits used and send
notification if threshold is reached
Role: !GetAtt
- CreditTrackingLambdaRole
- Arn
FunctionName: aws-account-credits-tracking
Handler: index.lambda_handler
Runtime: python3.8
Environment:
Variables:
AWS_CREDITS_NAME: !Ref CreditAwardName
AWS_CREDITS_TABLE_NAME: !Ref CreditsTableName
Code:
ZipFile: !Join
- '\n'
- - |
#MIT License
#
#Copyright (c) 2022 Allen Brodjeski
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
import os
import boto3
from datetime import datetime
from botocore.exceptions import ClientError
# Get the required environment variables
AWS_CREDITS_NAME = os.environ.get('AWS_CREDITS_NAME')
AWS_CREDITS_TABLE_NAME = os.environ.get('AWS_CREDITS_TABLE_NAME')
# Check if the required environment variables are set
if not AWS_CREDITS_NAME:
raise ValueError("Missing required environment variable 'AWS_CREDITS_NAME'")
if not AWS_CREDITS_TABLE_NAME:
raise ValueError("Missing required environment variable 'AWS_CREDITS_TABLE_NAME'")
class Credit:
def __init__(self, credit_name: str) -> None:
print('Building Credit from DynamoDB')
self.ddb_client = boto3.client('dynamodb')
self.credit_start = ''
self.credit_expiry = ''
self.credit_threshold = 0
self.credit_limit = 0
self.credit_notification_topic = ''
print(f'Credit Name: {credit_name}')
try:
# Get the credit data from the DynamoDB table
response = self.ddb_client.get_item(
TableName=AWS_CREDITS_TABLE_NAME,
Key={'credit_name': {'S': credit_name}},
AttributesToGet=[
'credit_start',
'credit_expiry',
'credit_limit',
'credit_threshold',
'credit_notification_topic'
]
)
# Extract the credit data from the response
self.credit_start = response['Item']['credit_start']['S']
self.credit_expiry = response['Item']['credit_expiry']['S']
self.credit_limit = float(response['Item']['credit_limit']['N'])
self.credit_threshold = float(response['Item']['credit_threshold']['N'])
self.credit_notification_topic = response['Item']['credit_notification_topic']['S']
except ClientError as e:
if e.response['Error']['Code'] == 'ResourceNotFoundException':
# If the DynamoDB table does not exist, raise a ValueError
raise ValueError(f"DynamoDB table '{AWS_CREDITS_TABLE_NAME}' does not exist")
else:
raise
except ValueError as e:
logging.error(e)
raise
def lambda_handler(event, context):
total_cost = 0.0
credit_table = Credit(AWS_CREDITS_NAME)
cost_client = boto3.client('ce')
account_id = boto3.client('sts').get_caller_identity().get('Account')
today = datetime.today().strftime('%Y-%m-%d')
print(f'Today: {today}')
print(f'Start time: {credit_table.credit_start}')
response = cost_client.get_cost_and_usage(
TimePeriod={
'Start': credit_table.credit_start,
'End': today
},
Granularity='DAILY',
Filter={
'Dimensions': {
'Key': 'RECORD_TYPE',
'Values': ['Credit'],
'MatchOptions': ['EQUALS']
}
},
Metrics=['UnblendedCost']
)
print(response)
for credit in response['ResultsByTime']:
total_cost += float(credit['Total']['UnblendedCost']['Amount'])
print(f'Total cost: {total_cost}')
credit_remaining = credit_table.credit_limit + total_cost
print(f'Credit threshold: {credit_table.credit_threshold}')
utilization = total_cost / credit_table.credit_limit * -100.0
if credit_remaining < credit_table.credit_threshold:
print('Sending utilization alert')
sns_client = boto3.client('sns')
response = sns_client.publish(
TopicArn=credit_table.credit_notification_topic,
Subject='AWS Account Credits Utilization Alert. Please see information below:',
Message=f'Account ID: {account_id}'
f"\n\nCredits remaining: {credit_remaining:.2f}"
f"\n\nUtilization: {utilization:.2f}%"
)
print(f'SNS response: {response}')
else:
print(f'Credit remaining: {credit_remaining}')
return {
'utilization': utilization,
'credit_remainning' : credit_remaining
}
CreditTrackingLambdaEventPermission:
Type: 'AWS::Lambda::Permission'
Properties:
Action: 'lambda:InvokeFunction'
FunctionName: aws-account-credits-tracking
Principal: events.amazonaws.com
SourceArn: !GetAtt
- CreditThresholdLambdaTimedTriggerEvent
- Arn
CreditThresholdLambdaTimedTriggerEvent:
Type: 'AWS::Events::Rule'
Properties:
Description: Event that triggers the credit threshold Lambda function
Name: aws-account-credits-tracking-trigger
ScheduleExpression: !Ref LambdaEventTriggerCron
State: ENABLED
Targets:
- Arn: !Sub >-
arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:aws-account-credits-tracking
Id: CreditThresholdLambdaFunction