-
Notifications
You must be signed in to change notification settings - Fork 34
/
aws_reserved_instance_recommendations.pt
812 lines (727 loc) · 30.4 KB
/
aws_reserved_instance_recommendations.pt
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
name "AWS Reserved Instances Recommendations"
rs_pt_ver 20180301
type "policy"
short_description "A policy that sends email notifications when AWS Reserved Instance Recommendations are identified. NOTE: These Purchase Recommendations are generated by AWS. See the [README](https://github.com/flexera-public/policy_templates/tree/master/cost/aws/reserved_instances/recommendations) and [docs.flexera.com/flexera/EN/Automation](https://docs.flexera.com/flexera/EN/Automation/AutomationGS.htm) to learn more."
long_description ""
severity "medium"
category "Cost"
default_frequency "weekly"
info(
version: "3.6.2",
provider: "AWS",
service: "Compute",
policy_set: "Reserved Instances",
recommendation_type: "Rate Reduction",
hide_skip_approvals: "true"
)
###############################################################################
# Parameters
###############################################################################
parameter "param_email" do
type "list"
category "Policy Settings"
label "Email Addresses"
description "Email addresses of the recipients you wish to notify when new incidents are created."
default []
end
parameter "param_aws_account_number" do
type "string"
category "Policy Settings"
label "Account Number"
description "Leave blank; this is for automated use with Meta Policies. See README for more details."
default ""
end
parameter "param_min_savings" do
type "number"
category "Policy Settings"
label "Minimum Savings Threshold"
description "Specify the minimum estimated monthly savings that should result in a recommendation"
min_value 0
default 0
end
parameter "param_days" do
type "string"
category "Reservation Settings"
label "Look Back Period"
description "Number of days of prior usage to analyze."
allowed_values "Last 7 Days", "Last 30 Days", "Last 60 Days"
default "Last 30 Days"
end
parameter "param_service" do
type "list"
category "Reservation Settings"
label "Service"
description "AWS Services to scan for recommendations. Items can be removed by clicking X to the right of the name."
allowed_values ["ElastiCache", "Elastic Compute Cloud (EC2)", "OpenSearch Service (ES)", "Redshift", "Relational Database Service (RDS)", "DynamoDB", "MemoryDB"]
default ["ElastiCache", "Elastic Compute Cloud (EC2)", "OpenSearch Service (ES)", "Redshift", "Relational Database Service (RDS)", "DynamoDB", "MemoryDB"]
end
parameter "param_service_spec" do
type "string"
category "Reservation Settings"
label "EC2 Reservation Type"
description "The type of reservation recommendations to produce for EC2. Standard reservations are less flexible than convertible ones but provide a higher discount."
allowed_values "Standard", "Convertible"
default "Standard"
end
parameter "param_scope" do
type "string"
category "Reservation Settings"
label "Account Scope"
description "The account scope that you want your recommendations for. Select Payer to produce results only for a Master Payer account, or Linked to produce results for all linked accounts as well."
allowed_values "Payer", "Linked"
default "Payer"
end
parameter "param_term" do
type "string"
category "Reservation Settings"
label "Reservation Term"
description "Length of reservation term to provide recommendations for."
allowed_values "Any", "1 Year", "3 Year"
default "1 Year"
end
parameter "param_payment_option" do
type "string"
category "Reservation Settings"
label "Payment Option"
description "Reservation purchase option to provide recommendations for. Select 'Everything' to produce recommendations for all three."
allowed_values "No Upfront", "Partial Upfront", "All Upfront", "Everything"
default "No Upfront"
end
###############################################################################
# Authentication
###############################################################################
credentials "auth_aws" do
schemes "aws", "aws_sts"
label "AWS"
description "Select the AWS Credential from the list"
tags "provider=aws"
aws_account_number $param_aws_account_number
end
credentials "auth_flexera" do
schemes "oauth2"
label "Flexera"
description "Select FlexeraOne OAuth2 credentials"
tags "provider=flexera"
end
###############################################################################
# Pagination
###############################################################################
pagination "pagination_aws" do
get_page_marker do
body_path "NextPageToken"
end
set_page_marker do
body_field "NextPageToken"
end
end
###############################################################################
# Datasources & Scripts
###############################################################################
# Get applied policy metadata for use later
datasource "ds_applied_policy" do
request do
auth $auth_flexera
host rs_governance_host
path join(["/api/governance/projects/", rs_project_id, "/applied_policies/", policy_id])
header "Api-Version", "1.0"
end
end
# Gather local currency info
datasource "ds_currency_reference" do
request do
host "raw.githubusercontent.com"
path "/flexera-public/policy_templates/master/data/currency/currency_reference.json"
header "User-Agent", "RS Policies"
end
end
datasource "ds_currency_code" do
request do
auth $auth_flexera
host rs_optima_host
path join(["/bill-analysis/orgs/", rs_org_id, "/settings/currency_code"])
header "Api-Version", "0.1"
header "User-Agent", "RS Policies"
ignore_status [403]
end
result do
encoding "json"
field "id", jmes_path(response, "id")
field "value", jmes_path(response, "value")
end
end
datasource "ds_currency_target" do
run_script $js_currency_target, $ds_currency_reference, $ds_currency_code
end
script "js_currency_target", type:"javascript" do
parameters "ds_currency_reference", "ds_currency_code"
result "result"
code <<-EOS
// Default to USD if currency is not found
result = ds_currency_reference['USD']
if (ds_currency_code['value'] != undefined && ds_currency_reference[ds_currency_code['value']] != undefined) {
result = ds_currency_reference[ds_currency_code['value']]
}
EOS
end
# Get region-specific Flexera API endpoints
datasource "ds_flexera_api_hosts" do
run_script $js_flexera_api_hosts, rs_optima_host
end
script "js_flexera_api_hosts", type: "javascript" do
parameters "rs_optima_host"
result "result"
code <<-EOS
host_table = {
"api.optima.flexeraeng.com": {
flexera: "api.flexera.com",
fsm: "api.fsm.flexeraeng.com"
},
"api.optima-eu.flexeraeng.com": {
flexera: "api.flexera.eu",
fsm: "api.fsm-eu.flexeraeng.com"
},
"api.optima-apac.flexeraeng.com": {
flexera: "api.flexera.au",
fsm: "api.fsm-apac.flexeraeng.com"
}
}
result = host_table[rs_optima_host]
EOS
end
# Get AWS account info
datasource "ds_cloud_vendor_accounts" do
request do
auth $auth_flexera
host val($ds_flexera_api_hosts, 'flexera')
path join(["/finops-analytics/v1/orgs/", rs_org_id, "/cloud-vendor-accounts"])
header "Api-Version", "1.0"
end
result do
encoding "json"
collect jmes_path(response, "values[*]") do
field "id", jmes_path(col_item, "aws.accountId")
field "name", jmes_path(col_item, "name")
field "tags", jmes_path(col_item, "tags")
end
end
end
datasource "ds_vendor_account_table" do
run_script $js_vendor_account_table, $ds_cloud_vendor_accounts
end
script "js_vendor_account_table", type:"javascript" do
parameters "ds_cloud_vendor_accounts"
result "result"
code <<-EOS
result = {}
_.each(ds_cloud_vendor_accounts, function(account) {
result[account['id']] = account['name']
})
EOS
end
datasource "ds_ri_types" do
run_script $js_ri_types, $param_service
end
script "js_ri_types", type: "javascript" do
parameters "param_service"
result "result"
code <<-EOS
if (param_service.length == 0) {
services = [
"ElastiCache",
"Elastic Compute Cloud (EC2)",
"Elasticsearch Service (ES)",
"Redshift",
"Relational Database Service (RDS)",
"DynamoDB",
"MemoryDB"
]
} else {
services = []
_.each(param_service, function(service) {
if (service == "OpenSearch Service (ES)") {
services.push("Elasticsearch Service (ES)")
} else {
services.push(service)
}
})
}
result = _.map(services, function(service) {
return { service: service }
})
EOS
end
datasource "ds_ri_recommendations" do
iterate $ds_ri_types
request do
run_script $js_ri_recommendations, val(iter_item, 'service'), $param_days, $param_payment_option, $param_service_spec, $param_term, $param_scope
end
result do
encoding "json"
collect jmes_path(response, "Recommendations[*]") do
field "accountScope", jmes_path(col_item, "AccountScope")
field "lookbackPeriodInDays", jmes_path(col_item, "LookbackPeriodInDays")
field "paymentOption", jmes_path(col_item, "PaymentOption")
field "termInYears", jmes_path(col_item, "TermInYears")
field "service", val(iter_item, "service")
field "recommendationDetails" do
collect jmes_path(col_item, "RecommendationDetails[*]") do
field "accountID", jmes_path(col_item, "AccountId")
field "averageNormalizedUnitsUsedPerHour", jmes_path(col_item, "AverageNormalizedUnitsUsedPerHour")
field "averageNumberOfInstancesUsedPerHour", jmes_path(col_item, "AverageNumberOfInstancesUsedPerHour")
field "averageUtilization", jmes_path(col_item, "AverageUtilization")
field "currency", jmes_path(col_item, "CurrencyCode")
field "estimatedBreakEvenInMonths", jmes_path(col_item, "EstimatedBreakEvenInMonths")
field "estimatedMonthlyOnDemandCost", jmes_path(col_item, "EstimatedMonthlyOnDemandCost")
field "estimatedMonthlySavingsAmount", jmes_path(col_item, "EstimatedMonthlySavingsAmount")
field "estimatedMonthlySavingsPercentage", jmes_path(col_item, "EstimatedMonthlySavingsPercentage")
field "estimatedReservationCostForLookbackPeriod", jmes_path(col_item, "EstimatedReservationCostForLookbackPeriod")
field "availabilityZone", jmes_path(col_item, "InstanceDetails.*.AvailabilityZone")
field "currentGeneration", jmes_path(col_item, "InstanceDetails.*.CurrentGeneration")
field "family", jmes_path(col_item, "InstanceDetails.*.Family")
field "instanceType", jmes_path(col_item, "InstanceDetails.*.InstanceType")
field "platform", jmes_path(col_item, "InstanceDetails.*.Platform")
field "region", jmes_path(col_item, "InstanceDetails.*.Region")
field "sizeFlexEligible", jmes_path(col_item, "InstanceDetails.*.SizeFlexEligible")
field "tenancy", jmes_path(col_item, "InstanceDetails.*.Tenancy")
field "nodeType", jmes_path(col_item, "InstanceDetails.*.NodeType")
field "productDescription", jmes_path(col_item, "InstanceDetails.*.ProductDescription")
field "instanceClass", jmes_path(col_item, "InstanceDetails.*.InstanceClass")
field "instanceSize", jmes_path(col_item, "InstanceDetails.*.InstanceSize")
field "databaseEngine", jmes_path(col_item, "InstanceDetails.*.DatabaseEngine")
field "databaseEdition", jmes_path(col_item, "InstanceDetails.*.DatabaseEdition")
field "deploymentOption", jmes_path(col_item, "InstanceDetails.*.DeploymentOption")
field "licenseModel", jmes_path(col_item, "InstanceDetails.*.LicenseModel")
field "maximumNormalizedUnitsUsedPerHour", jmes_path(col_item, "MaximumNormalizedUnitsUsedPerHour")
field "maximumNumberOfInstancesUsedPerHour", jmes_path(col_item, "MaximumNumberOfInstancesUsedPerHour")
field "minimumNormalizedUnitsUsedPerHour", jmes_path(col_item, "MinimumNormalizedUnitsUsedPerHour")
field "minimumNumberOfInstancesUsedPerHour", jmes_path(col_item, "MinimumNumberOfInstancesUsedPerHour")
field "recommendedNormalizedUnitsToPurchase", jmes_path(col_item, "RecommendedNormalizedUnitsToPurchase")
field "recommendedNumberOfInstancesToPurchase", jmes_path(col_item, "RecommendedNumberOfInstancesToPurchase")
field "recurringStandardMonthlyCost", jmes_path(col_item, "RecurringStandardMonthlyCost")
field "upfrontCost", jmes_path(col_item, "UpfrontCost")
end
end
end
end
end
script "js_ri_recommendations", type: "javascript" do
parameters "service", "param_days", "param_payment_option", "param_service_spec", "param_term", "param_scope"
result "request"
code <<-EOS
// Tables to convert human-readable parameter values to their API equivalents
period_table = {
"Last 7 Days": "SEVEN_DAYS",
"Last 30 Days": "THIRTY_DAYS",
"Last 60 Days": "SIXTY_DAYS"
}
service_table = {
"Elastic Compute Cloud (EC2)": "Amazon Elastic Compute Cloud - Compute",
"Relational Database Service (RDS)": "Amazon Relational Database Service",
"ElastiCache": "Amazon ElastiCache",
"Redshift": "Amazon Redshift",
"Elasticsearch Service (ES)": "Amazon OpenSearch Service",
"DynamoDB": "Amazon DynamoDB Service",
"MemoryDB": "Amazon MemoryDB Service"
}
term_table = {
"1 Year": "ONE_YEAR",
"3 Year": "THREE_YEARS"
}
// Build out the body of the request based on parameters
body_fields = {
LookbackPeriodInDays: period_table[param_days],
AccountScope: param_scope.toUpperCase(),
Service: service_table[service]
}
if (param_payment_option != "Everything") {
body_fields['PaymentOption'] = param_payment_option.replace(' ', '_').toUpperCase()
}
if (service == "Elastic Compute Cloud (EC2)") {
body_fields['ServiceSpecification'] = {
EC2Specification: { OfferingClass: param_service_spec.toUpperCase() }
}
}
if (param_term != "Any") {
body_fields['TermInYears'] = term_table[param_term]
}
var request = {
auth: "auth_aws",
pagination: "pagination_aws",
host: "ce.us-east-1.amazonaws.com",
path: "/",
verb: "POST",
body_fields: body_fields,
headers: {
"User-Agent": "RS Policies",
"X-Amz-Target": "AWSInsightsIndexService.GetReservationPurchaseRecommendation",
"Content-Type": "application/x-amz-json-1.1",
}
}
EOS
end
# Branching logic:
# This datasource returns an empty array if the target currency is USD.
# This prevents ds_currency_conversion from running if it's not needed.
datasource "ds_conditional_currency_conversion" do
run_script $js_conditional_currency_conversion, $ds_currency_target, $ds_ri_recommendations
end
script "js_conditional_currency_conversion", type: "javascript" do
parameters "ds_currency_target", "ds_ri_recommendations"
result "result"
code <<-EOS
result = []
from_currency = "USD"
if (ds_ri_recommendations.length > 0) {
if (ds_ri_recommendations[0]['recommendationDetails'].length > 0) {
if (typeof(ds_ri_recommendations[0]['recommendationDetails'][0]['currency']) == 'string') {
from_currency = ds_ri_recommendations[0]['recommendationDetails'][0]['currency']
}
}
}
// Make the request only if the target currency is not USD
if (ds_currency_target['code'] != from_currency) {
result = [{ from: from_currency }]
}
EOS
end
datasource "ds_currency_conversion" do
# Only make a request if the target currency is not USD
iterate $ds_conditional_currency_conversion
request do
host "api.xe-auth.flexeraeng.com"
path "/prod/{proxy+}"
query "from", val(iter_item, 'from')
query "to", val($ds_currency_target, 'code')
query "amount", "1"
# Ignore currency conversion if API has issues
ignore_status [400, 404, 502]
end
result do
encoding "json"
field "from", jmes_path(response, "from")
field "to", jmes_path(response, "to")
field "amount", jmes_path(response, "amount")
field "year", jmes_path(response, "year")
end
end
datasource "ds_currency" do
run_script $js_currency, $ds_currency_target, $ds_currency_conversion
end
script "js_currency", type:"javascript" do
parameters "ds_currency_target", "ds_currency_conversion"
result "result"
code <<-EOS
result = ds_currency_target
result['exchange_rate'] = 1
if (ds_currency_conversion.length > 0) {
currency_code = ds_currency_target['code']
current_month = parseInt(new Date().toISOString().split('-')[1])
conversion_block = _.find(ds_currency_conversion[0]['to'][currency_code], function(item) {
return item['month'] == current_month
})
if (conversion_block != undefined) {
result['exchange_rate'] = conversion_block['monthlyAverage']
}
}
EOS
end
datasource "ds_ri_normalization" do
run_script $js_ri_normalization, $ds_ri_recommendations, $ds_applied_policy, $ds_vendor_account_table, $ds_currency, $ds_currency_conversion, $ds_conditional_currency_conversion, $param_days, $param_service, $param_service_spec, $param_scope, $param_term, $param_payment_option, $param_min_savings
end
script "js_ri_normalization", type: "javascript" do
parameters "ds_ri_recommendations", "ds_applied_policy", "ds_vendor_account_table", "ds_currency", "ds_currency_conversion", "ds_conditional_currency_conversion", "param_days", "param_service", "param_service_spec", "param_scope", "param_term", "param_payment_option", "param_min_savings"
result "result"
code <<-'EOS'
// Used for formatting numbers to look pretty
function formatNumber(number, separator) {
formatted_number = "0"
if (number) {
formatted_number = (Math.round(number * 100) / 100).toString().split(".")[0]
if (separator) {
withSeparator = ""
for (var i = 0; i < formatted_number.length; i++) {
if (i > 0 && (formatted_number.length - i) % 3 == 0) { withSeparator += separator }
withSeparator += formatted_number[i]
}
formatted_number = withSeparator
}
decimal = (Math.round(number * 100) / 100).toString().split(".")[1]
if (decimal) { formatted_number += "." + decimal }
}
return formatted_number
}
result = []
total_savings = 0.0
exchange_rate = ds_currency['exchange_rate']
_.each(ds_ri_recommendations, function(item) {
term = item["termInYears"].toString() + " year"
if (item["termInYears"] > 1) { term += "s" }
_.each(item["recommendationDetails"], function(recommendation) {
if (recommendation["estimatedMonthlySavingsAmount"] >= param_min_savings) {
total_savings += recommendation["estimatedMonthlySavingsAmount"] * exchange_rate
// Set blank values for fields where the value is N/A for the recommendation in question
averageNumberOfInstancesUsedPerHour = Math.round(recommendation["averageNumberOfInstancesUsedPerHour"] * 100) / 100
maximumNumberOfInstancesUsedPerHour = Math.round(recommendation["maximumNumberOfInstancesUsedPerHour"] * 100) / 100
minimumNumberOfInstancesUsedPerHour = Math.round(recommendation["minimumNumberOfInstancesUsedPerHour"] * 100) / 100
averageNormalizedUnitsUsedPerHour = Math.round(recommendation["averageNormalizedUnitsUsedPerHour"] * 100) / 100
maximumNormalizedUnitsUsedPerHour = Math.round(recommendation["maximumNormalizedUnitsUsedPerHour"] * 100) / 100
minimumNormalizedUnitsUsedPerHour = Math.round(recommendation["minimumNormalizedUnitsUsedPerHour"] * 100) / 100
recommendedNormalizedUnitsToPurchase = parseFloat(recommendation["recommendedNormalizedUnitsToPurchase"])
recommendedNumberOfInstancesToPurchase = parseFloat(recommendation["recommendedNumberOfInstancesToPurchase"])
if (isNaN(averageNumberOfInstancesUsedPerHour)) { averageNumberOfInstancesUsedPerHour = "" }
if (isNaN(maximumNumberOfInstancesUsedPerHour)) { maximumNumberOfInstancesUsedPerHour = "" }
if (isNaN(minimumNumberOfInstancesUsedPerHour)) { minimumNumberOfInstancesUsedPerHour = "" }
if (isNaN(averageNormalizedUnitsUsedPerHour)) { averageNormalizedUnitsUsedPerHour = "" }
if (isNaN(maximumNormalizedUnitsUsedPerHour)) { maximumNormalizedUnitsUsedPerHour = "" }
if (isNaN(minimumNormalizedUnitsUsedPerHour)) { minimumNormalizedUnitsUsedPerHour = "" }
if (isNaN(recommendedNormalizedUnitsToPurchase)) { recommendedNormalizedUnitsToPurchase = "" }
if (isNaN(recommendedNumberOfInstancesToPurchase)) { recommendedNumberOfInstancesToPurchase = "" }
// Calculate values while including currency calculation when needed
averageUtilization = Math.round(recommendation["averageUtilization"] * 100) / 100
estimatedBreakEvenInMonths = Math.round(recommendation["estimatedBreakEvenInMonths"] * exchange_rate * 100) / 100
estimatedMonthlyOnDemandCost = Math.round(recommendation["estimatedMonthlyOnDemandCost"] * exchange_rate * 100) / 100
estimatedMonthlySavingsAmount = Math.round(recommendation["estimatedMonthlySavingsAmount"] * exchange_rate * 100) / 100
estimatedMonthlySavingsPercentage = Math.round(recommendation["estimatedMonthlySavingsPercentage"] * 100) / 100
estimatedReservationCostForLookbackPeriod = Math.round(recommendation["estimatedReservationCostForLookbackPeriod"] * exchange_rate) / 100
recurringStandardMonthlyCost = Math.round(recommendation["recurringStandardMonthlyCost"] * exchange_rate * 100) / 100
upfrontCost = Math.round(recommendation["upfrontCost"] * exchange_rate * 100) / 100
// Set misc values
platform = recommendation["platform"].toString() || recommendation["databaseEngine"].toString()
resourceType = recommendation["instanceType"].toString() || recommendation["instanceSize"].toString() || recommendation["nodeType"].toString()
paymentOption = item["paymentOption"].replace('_', ' ')
result.push({
accountID: recommendation["accountID"],
accountName: ds_vendor_account_table[recommendation["accountID"]],
service: item["service"],
scope: item["accountScope"],
lookbackPeriod: item["lookbackPeriodInDays"],
paymentOption: paymentOption,
availabilityZone: recommendation["availabilityZone"].toString(),
averageNormalizedUnitsUsedPerHour: averageNormalizedUnitsUsedPerHour,
averageNumberOfInstancesUsedPerHo: averageNumberOfInstancesUsedPerHour,
averageUtilization: averageUtilization,
databaseEdition: recommendation["databaseEdition"].toString(),
databaseEngine: recommendation["databaseEngine"].toString(),
deploymentOption: recommendation["deploymentOption"].toString(),
estimatedBreakEvenInMonths: estimatedBreakEvenInMonths,
estimatedMonthlyOnDemandCost: estimatedMonthlyOnDemandCost,
savings: estimatedMonthlySavingsAmount,
savingsCurrency: ds_currency['symbol'],
estimatedMonthlySavingsPercentage: estimatedMonthlySavingsPercentage,
estimatedReservationCostForLookbackPeriod: estimatedReservationCostForLookbackPeriod,
family: recommendation["family"].toString(),
instanceClass: recommendation["instanceClass"].toString(),
instanceSize: recommendation["instanceSize"].toString(),
instanceType: recommendation["instanceType"].toString(),
licenseModel: recommendation["licenseModel"].toString(),
maximumNormalizedUnitsUsedPerHour: maximumNormalizedUnitsUsedPerHour,
maximumNumberOfInstancesUsedPerHour: maximumNumberOfInstancesUsedPerHour,
minimumNormalizedUnitsUsedPerHour: minimumNormalizedUnitsUsedPerHour,
minimumNumberOfInstancesUsedPerHour: minimumNumberOfInstancesUsedPerHour,
nodeType: recommendation["nodeType"].toString(),
platform: platform,
productDescription: recommendation["productDescription"].toString(),
recommendedNormalizedUnitsToPurchase: recommendedNormalizedUnitsToPurchase,
recommendedQuantity: recommendedNumberOfInstancesToPurchase,
recurringStandardMonthlyCost: recurringStandardMonthlyCost,
region: recommendation["region"].toString(),
sizeFlexEligible: recommendation["sizeFlexEligible"].toString(),
tenancy: recommendation["tenancy"].toString(),
upfrontCost: upfrontCost,
resourceType: resourceType,
term: term,
savingsCurrency: ds_currency['symbol'],
policy_name: ds_applied_policy['name'],
total_savings: "",
message: ""
})
}
})
})
// Messaging for currency conversion
currency = ds_currency['code']
if (ds_conditional_currency_conversion[0] != undefined) {
currency = ds_conditional_currency_conversion[0]['from']
}
conversion_message = ""
if (ds_currency['code'] != currency && ds_currency_conversion.length > 0 && exchange_rate != 1) {
conversion_message = [
"Savings values were converted from ", currency, " to ", ds_currency['code'],
" using an exchange rate of ", exchange_rate, ".\n\n"
].join('')
}
if (ds_currency['code'] != currency && ds_currency_conversion.length == 0) {
conversion_message = "Savings values are in ", currency, " due to a malfunction with Flexera's internal currency conversion API. Please contact Flexera support to report this issue."
}
// Only show EC2 Specification setting if it is applicable
ec2_spec = ""
if (param_service.length == 0 || _.contains(param_service, "Elastic Compute Cloud (EC2)")) {
ec2_spec = "- EC2 Specification: " + param_service_spec + "\n"
}
message = [
"The following settings were used when generating recommendations:\n",
"- AWS Services: ", param_service.join(', '), "\n",
ec2_spec,
"- Account Scope: ", param_scope, "\n",
"- Term: ", param_term, "\n",
"- Look Back Period: ", param_days, "\n",
"- Payment Option: ", param_payment_option, "\n",
"- Minimum Savings Threshold: ", param_min_savings, "\n\n",
].join('')
disclaimer = "The above settings can be modified by editing the applied policy and changing the appropriate parameters.\n\n"
empty_fields = "Empty fields indicate information that is not applicable to that particular recommendation."
savings_message = [
ds_currency['symbol'], ' ',
formatNumber(parseFloat(total_savings).toFixed(2), ds_currency['t_separator'])
].join('')
// Sort by highest savings first
result = _.sortBy(result, function(item) { return item['savings'] * -1 })
if (result.length > 0) {
result[0]['total_savings'] = savings_message
result[0]['message'] = conversion_message + message + disclaimer + empty_fields
}
EOS
end
###############################################################################
# Policy
###############################################################################
policy "pol_aws_ri_recommendations" do
validate_each $ds_ri_normalization do
summary_template "{{ with index data 0 }}{{ .policy_name }}{{ end }}: {{ len data }} AWS Reserved Instances Purchase Recommendations"
detail_template <<-'EOS'
**Potential Monthly Savings:** {{ with index data 0 }}{{ .total_savings }}{{ end }}
{{ with index data 0 }}{{ .message }}{{ end }}
EOS
check lt(val(item, "savings"), 0)
escalate $esc_email
export do
resource_level false
field "accountID" do
label "Account ID"
end
field "accountName" do
label "Account Name"
end
field "region" do
label "Region"
end
field "service" do
label "Service"
end
field "savingsCurrency" do
label "Currency"
end
field "savings" do
label "Estimated Monthly Savings Amount"
end
field "scope" do
label "Account Scope"
end
field "averageNormalizedUnitsUsedPerHour" do
label "Average Normalized Units Used Per Hour"
end
field "averageNumberOfInstancesUsedPerHour" do
label "Average Number Of Instances Used Per Hour"
end
field "averageUtilization" do
label "Average Utilization"
end
field "databaseEdition" do
label "Database Edition"
end
field "databaseEngine" do
label "Database Engine"
end
field "deploymentOption" do
label "Deployment Option"
end
field "estimatedBreakEvenInMonths" do
label "Estimated Break Even In Months"
end
field "estimatedMonthlyOnDemandCost" do
label "Estimated Monthly On Demand Cost"
end
field "estimatedMonthlySavingsPercentage" do
label "Estimated Monthly Savings Percentage"
end
field "estimatedReservationCostForLookbackPeriod" do
label "Estimated Reservation Cost For Lookback Period"
end
field "family" do
label "Family"
end
field "instanceClass" do
label "Instance Class"
end
field "instanceSize" do
label "Instance Size"
end
field "instanceType" do
label "Instance Type"
end
field "licenseModel" do
label "License Model"
end
field "lookbackPeriod" do
label "Look Back Period (Days)"
end
field "maximumNormalizedUnitsUsedPerHour" do
label "Maximum Normalized Units Used Per Hour"
end
field "maximumNumberOfInstancesUsedPerHour" do
label "Maximum Number Of Instances Used Per Hour"
end
field "minimumNormalizedUnitsUsedPerHour" do
label "Minimum Normalized Units Used Per Hour"
end
field "minimumNumberOfInstancesUsedPerHour" do
label "Minimum Number Of Instances Used Per Hour"
end
field "nodeType" do
label "Node Type"
end
field "paymentOption" do
label "Payment Option"
end
field "platform" do
label "Platform"
end
field "productDescription" do
label "Product Description"
end
field "recommendedNormalizedUnitsToPurchase" do
label "Recommended Normalized Units To Purchase"
end
field "recommendedQuantity" do
label "Recommended Number Of Instances To Purchase"
end
field "recurringStandardMonthlyCost" do
label "Recurring Standard Monthly Cost"
end
field "sizeFlexEligible" do
label "Flex Eligible"
end
field "tenancy" do
label "Tenancy"
end
field "upfrontCost" do
label "Upfront Cost"
end
field "resourceType" do
label "Resource Type"
end
field "term" do
label "Term"
end
end
end
end
###############################################################################
# Escalations
###############################################################################
escalation "esc_email" do
automatic true
label "Send Email"
description "Send incident email"
email $param_email
end