-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathazure_rightsize_netapp.pt
1513 lines (1358 loc) · 55.3 KB
/
azure_rightsize_netapp.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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
name "Azure Rightsize NetApp Resources"
rs_pt_ver 20180301
type "policy"
short_description "Reports oversized NetApp capacity pools and volumes and, optionally, rezies them. See the [README](https://github.com/flexera-public/policy_templates/tree/master/cost/azure/rightsize_netapp/) and [docs.flexera.com/flexera/EN/Automation](https://docs.flexera.com/flexera/EN/Automation/AutomationGS.htm) to learn more."
long_description ""
category "Cost"
severity "low"
default_frequency "weekly"
info(
version: "2.0.4",
provider: "Azure",
service: "NetApp Files",
policy_set: "Rightsize Storage",
recommendation_type: "Usage Reduction",
hide_skip_approvals: "true"
)
###############################################################################
# Parameters
###############################################################################
parameter "param_email" do
type "list"
category "Policy Settings"
label "Email Addresses"
description "A list of email addresses to notify."
default []
end
parameter "param_azure_endpoint" do
type "string"
category "Policy Settings"
label "Azure Endpoint"
description "Select the API endpoint to use for Azure. Use default value of management.azure.com unless using Azure China."
allowed_values "management.azure.com", "management.chinacloudapi.cn"
default "management.azure.com"
end
parameter "param_stats_underutil_threshold_pool_value" do
type "number"
category "Statistics"
label "Pool Allocated to Volume Threshold (%)"
description "The allocation threshold at which to consider a NetApp pool to be 'oversized' and therefore be flagged for downsizing."
min_value 0
max_value 100
default 50
end
parameter "param_stats_underutil_threshold_volume_value" do
type "number"
category "Statistics"
label "Volume Consumed Capacity Threshold (%)"
description "The capacity usage threshold at which to consider a NetApp volume to be 'oversized' and therefore be flagged for downsizing."
min_value 0
max_value 100
default 50
end
parameter "param_exclusion_tags" do
type "list"
category "Filters"
label "Exclusion Tags"
description "Cloud native tags to ignore resources that you don't want to produce recommendations for. Enter the Key name to filter resources with a specific Key, regardless of Value, and enter Key==Value to filter resources with a specific Key:Value pair. Other operators and regex are supported; please see the README for more details."
default []
end
parameter "param_exclusion_tags_boolean" do
type "string"
category "Filters"
label "Exclusion Tags: Any / All"
description "Whether to filter instances containing any of the specified tags or only those that contain all of them. Only applicable if more than one value is entered in the 'Exclusion Tags' field."
allowed_values "Any", "All"
default "Any"
end
parameter "param_subscriptions_allow_or_deny" do
type "string"
category "Filters"
label "Allow/Deny Subscriptions"
description "Allow or Deny entered Subscriptions"
allowed_values "Allow", "Deny"
default "Allow"
end
parameter "param_subscriptions_list" do
type "list"
category "Filters"
label "Allow/Deny Subscriptions List"
description "A list of allowed or denied Subscription IDs/names"
default []
end
parameter "param_regions_allow_or_deny" do
type "string"
category "Filters"
label "Allow/Deny Regions"
description "Allow or deny entered regions. See the README for more details."
allowed_values "Allow", "Deny"
default "Allow"
end
parameter "param_regions_list" do
type "list"
category "Filters"
label "Allow/Deny Regions List"
description "A list of allowed or denied regions. See the README for more details."
default []
end
parameter "param_show_size_increment_recommendations" do
type "string"
category "Filters"
label "Show Upsize Recommendations"
description "Whether or not to include upsize recommendations for pools and volumes"
allowed_values "Yes", "No"
default "No"
end
parameter "param_resource_types" do
type "string"
category "Filter"
label "Resource Types"
description "Whether to produce recommendations only for pools or for both pools and volumes"
allowed_values "Pools", "Pools and Volumes"
default "Pools"
end
parameter "param_min_savings" do
type "number"
category "Policy Settings"
label "Minimum Savings Threshold"
description "Minimum potential savings required to generate a recommendation"
min_value 0
default 0
end
parameter "param_automatic_action" do
type "list"
category "Actions"
label "Automatic Actions"
description "When this value is set, this policy will automatically take the selected action."
allowed_values ["Rightsize NetApp Resources"]
default []
end
###############################################################################
# Authentication
###############################################################################
credentials "auth_azure" do
schemes "oauth2"
label "Azure"
description "Select the Azure Resource Manager Credential from the list."
tags "provider=azure_rm"
end
credentials "auth_flexera" do
schemes "oauth2"
label "Flexera"
description "Select Flexera One OAuth2 credentials"
tags "provider=flexera"
end
###############################################################################
# Pagination
###############################################################################
pagination "pagination_azure" do
get_page_marker do
body_path "nextLink"
end
set_page_marker do
uri true
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
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" do
run_script $js_currency, $ds_currency_reference, $ds_currency_code
end
script "js_currency", type:"javascript" do
parameters "ds_currency_reference", "ds_currency_code"
result "result"
code <<-EOS
symbol = "$"
separator = ","
if (ds_currency_code['value'] != undefined) {
if (ds_currency_reference[ds_currency_code['value']] != undefined) {
symbol = ds_currency_reference[ds_currency_code['value']]['symbol']
if (ds_currency_reference[ds_currency_code['value']]['t_separator'] != undefined) {
separator = ds_currency_reference[ds_currency_code['value']]['t_separator']
} else {
separator = ""
}
}
}
result = {
symbol: symbol,
separator: separator
}
EOS
end
datasource "ds_azure_subscriptions" do
request do
auth $auth_azure
pagination $pagination_azure
host $param_azure_endpoint
path "/subscriptions/"
query "api-version", "2020-01-01"
header "User-Agent", "RS Policies"
# Header X-Meta-Flexera has no affect on datasource query, but is required for Meta Policies
# Forces `ds_is_deleted` datasource to run first during policy execution
header "Meta-Flexera", val($ds_is_deleted, "path")
# Ignore status 400, 403, and 404 which can be returned in certain (legacy) types of Azure Subscriptions
ignore_status [400, 403, 404]
end
result do
encoding "json"
collect jmes_path(response, "value[*]") do
field "id", jmes_path(col_item, "subscriptionId")
field "name", jmes_path(col_item, "displayName")
field "state", jmes_path(col_item, "state")
end
end
end
datasource "ds_azure_subscriptions_filtered" do
run_script $js_azure_subscriptions_filtered, $ds_azure_subscriptions, $param_subscriptions_allow_or_deny, $param_subscriptions_list
end
script "js_azure_subscriptions_filtered", type: "javascript" do
parameters "ds_azure_subscriptions", "param_subscriptions_allow_or_deny", "param_subscriptions_list"
result "result"
code <<-EOS
if (param_subscriptions_list.length > 0) {
result = _.filter(ds_azure_subscriptions, function(subscription) {
include_subscription = _.contains(param_subscriptions_list, subscription['id']) || _.contains(param_subscriptions_list, subscription['name'])
if (param_subscriptions_allow_or_deny == "Deny") { include_subscription = !include_subscription }
return include_subscription
})
} else {
result = ds_azure_subscriptions
}
EOS
end
datasource "ds_naf_accounts" do
iterate $ds_azure_subscriptions_filtered
request do
auth $auth_azure
host $param_azure_endpoint
path join(["/subscriptions/", val(iter_item, "id"), "/providers/Microsoft.NetApp/netAppAccounts"])
query "api-version", "2023-05-01"
ignore_status [400, 403, 404]
end
result do
encoding "json"
collect jmes_path(response, "value[*]") do
field "subscription_id", jmes_path(iter_item, "id")
field "subscription_name", val(iter_item, "name")
field "resource_group_name", get(4, split(jmes_path(col_item, "id"), "/"))
field "region", jmes_path(col_item, "location")
field "naf_account_name", jmes_path(col_item, "name")
field "tags", jmes_path(col_item, "tags")
end
end
end
datasource "ds_naf_accounts_region_filtered" do
run_script $js_naf_accounts_region_filtered, $ds_naf_accounts, $param_regions_allow_or_deny, $param_regions_list
end
script "js_naf_accounts_region_filtered", type: "javascript" do
parameters "ds_objects", "param_regions_allow_or_deny", "param_regions_list"
result "result"
code <<-EOS
if (param_regions_list.length > 0) {
result = _.filter(ds_objects, function(item) {
include_item = _.contains(param_regions_list, item['region'])
if (param_regions_allow_or_deny == "Deny") { include_item = !include_item }
return include_item
})
} else {
result = ds_objects
}
EOS
end
datasource "ds_naf_accounts_tag_filtered" do
run_script $js_objects_tag_filtered, $ds_naf_accounts_region_filtered, $param_exclusion_tags, $param_exclusion_tags_boolean
end
datasource "ds_naf_capacity_pools" do
iterate $ds_naf_accounts_tag_filtered
request do
auth $auth_azure
host $param_azure_endpoint
path join(["/subscriptions/", val(iter_item, "subscription_id"), "/resourceGroups/", val(iter_item, "resource_group_name"), "/providers/Microsoft.NetApp/netAppAccounts/", val(iter_item, "naf_account_name"), "/capacityPools"])
query "api-version", "2023-05-01"
ignore_status [400, 403, 404]
end
result do
encoding "json"
collect jmes_path(response, "value[*]") do
field "subscription_id", jmes_path(iter_item, "subscription_id")
field "subscription_name", jmes_path(iter_item, "subscription_name")
field "resource_group_name", jmes_path(iter_item, "resource_group_name")
field "resource_kind", jmes_path(col_item, "type")
field "service_type", first(split(jmes_path(col_item, "type"), "/"))
field "naf_account_name", jmes_path(iter_item, "naf_account_name")
field "naf_pool_id", jmes_path(col_item, "id")
field "naf_pool_name", last(split(jmes_path(col_item, "name"), "/"))
field "naf_pool_size", jmes_path(col_item, "properties.size")
field "naf_pool_region", jmes_path(col_item, "location")
field "naf_pool_service", jmes_path(col_item, "properties.serviceLevel")
field "naf_pool_encryption", jmes_path(col_item, "properties.encryptionType")
field "naf_pool_cool", jmes_path(col_item, "properties.coolAccess")
field "naf_pool_created_at", jmes_path(col_item, "systemData.createdAt")
field "tags", jmes_path(col_item, "tags")
end
end
end
datasource "ds_naf_capacity_pools_tag_filtered" do
run_script $js_objects_tag_filtered, $ds_naf_capacity_pools, $param_exclusion_tags, $param_exclusion_tags_boolean
end
script "js_objects_tag_filtered", type: "javascript" do
parameters "objects_to_filter", "param_exclusion_tags", "param_exclusion_tags_boolean"
result "result"
code <<-EOS
comparators = _.map(param_exclusion_tags, function(item) {
if (item.indexOf('==') != -1) {
return { comparison: '==', key: item.split('==')[0], value: item.split('==')[1], string: item }
}
if (item.indexOf('!=') != -1) {
return { comparison: '!=', key: item.split('!=')[0], value: item.split('!=')[1], string: item }
}
if (item.indexOf('=~') != -1) {
value = item.split('=~')[1]
regex = new RegExp(value.slice(1, value.length - 1))
return { comparison: '=~', key: item.split('=~')[0], value: regex, string: item }
}
if (item.indexOf('!~') != -1) {
value = item.split('!~')[1]
regex = new RegExp(value.slice(1, value.length - 1))
return { comparison: '!~', key: item.split('!~')[0], value: regex, string: item }
}
// If = is present but none of the above are, assume user error and that the user intended ==
if (item.indexOf('=') != -1) {
return { comparison: '==', key: item.split('=')[0], value: item.split('=')[1], string: item }
}
// Assume we're just testing for a key if none of the comparators are found
return { comparison: 'key', key: item, value: null, string: item }
})
if (param_exclusion_tags.length > 0) {
result = _.reject(objects_to_filter, function(resource) {
resource_tags = {}
if (typeof(resource['tags']) == 'object') { resource_tags = resource['tags'] }
// Store a list of found tags
found_tags = []
_.each(comparators, function(comparator) {
comparison = comparator['comparison']
value = comparator['value']
string = comparator['string']
resource_tag = resource_tags[comparator['key']]
if (comparison == 'key' && resource_tag != undefined) { found_tags.push(string) }
if (comparison == '==' && resource_tag == value) { found_tags.push(string) }
if (comparison == '!=' && resource_tag != value) { found_tags.push(string) }
if (comparison == '=~') {
if (resource_tag != undefined && value.test(resource_tag)) { found_tags.push(string) }
}
if (comparison == '!~') {
if (resource_tag == undefined) { found_tags.push(string) }
if (resource_tag != undefined && value.test(resource_tag)) { found_tags.push(string) }
}
})
all_tags_found = found_tags.length == comparators.length
any_tags_found = found_tags.length > 0 && param_exclusion_tags_boolean == 'Any'
return all_tags_found || any_tags_found
})
} else {
result = objects_to_filter
}
EOS
end
datasource "ds_naf_pool_metrics" do
iterate $ds_naf_capacity_pools_tag_filtered
request do
run_script $js_naf_pool_metrics, val(iter_item, "naf_pool_id"), $param_azure_endpoint
end
result do
encoding "json"
field "subscription_id", jmes_path(iter_item, "subscription_id")
field "subscription_name", jmes_path(iter_item, "subscription_name")
field "resource_group_name", jmes_path(iter_item, "resource_group_name")
field "resource_kind", jmes_path(iter_item, "resource_kind")
field "service_type", jmes_path(iter_item, "service_type")
field "naf_account_name", jmes_path(iter_item, "naf_account_name")
field "naf_pool_id", jmes_path(iter_item, "naf_pool_id")
field "naf_pool_name", jmes_path(iter_item, "naf_pool_name")
field "naf_pool_size", jmes_path(iter_item, "naf_pool_size")
field "naf_pool_region", jmes_path(iter_item, "naf_pool_region")
field "naf_pool_service", jmes_path(iter_item, "naf_pool_service")
field "naf_pool_encryption", jmes_path(iter_item, "naf_pool_encryption")
field "naf_pool_cool", jmes_path(iter_item, "naf_pool_cool")
field "naf_pool_created_at", jmes_path(iter_item, "naf_pool_created_at")
field "tags", jmes_path(iter_item, "tags")
field "naf_pool_metrics", jmes_path(response, "value[*]")
end
end
script "js_naf_pool_metrics", type: "javascript" do
parameters "poolId", "param_azure_endpoint"
result "request"
code <<-EOS
var end_date = new Date()
var start_date = new Date(end_date)
start_date.setHours(end_date.getHours() - 12)
start_date.setMilliseconds(0)
start_date.setSeconds(0)
start_date.setMinutes(0)
timespan = start_date.toISOString() + "/" + end_date.toISOString()
var request = {
auth: "auth_azure",
host: param_azure_endpoint,
path: poolId + "/providers/microsoft.insights/metrics",
query_params: {
"api-version": "2018-01-01",
"metricnames": "VolumePoolAllocatedUsed,VolumePoolTotalLogicalSize,VolumePoolAllocatedSize",
"timespan": timespan,
},
headers: {
"User-Agent": "RS Policies",
},
ignore_status: [400, 403, 404]
}
EOS
end
datasource "ds_naf_get_costs" do
request do
run_script $js_naf_get_costs, $ds_naf_capacity_pools_tag_filtered
end
result do
encoding "json"
collect jmes_path(response, "Items[*]") do
field "retailPrice", jmes_path(col_item, "retailPrice")
field "region", jmes_path(col_item, "armRegionName")
field "skuName", jmes_path(col_item, "skuName")
end
end
end
script "js_naf_get_costs", type: "javascript" do
parameters "ds_naf_capacity_pools_tag_filtered"
result "request"
code <<-EOS
var locations = []
var location = ""
_.each(ds_naf_capacity_pools_tag_filtered, function(pool){
locations.push("armRegionName eq '" + pool.naf_pool_region + "'")
})
if (locations.length > 0) { location = " and (" + locations.join(" or ") + ")" }
var request = {
host: "prices.azure.com"
path: "/api/retail/prices"
query_params: {
"api-version": "2021-10-01-preview"
"$filter": "serviceName eq 'Azure NetApp Files'" + location + " and priceType eq 'Consumption' and endsWith(meterName, 'Capacity') and (contains(skuName, 'Standard') or contains(skuName, 'Premium') or contains(skuName, 'Ultra'))"
},
ignore_status: [400, 403, 404]
}
EOS
end
datasource "ds_naf_capacity_pools_option_filtered" do
run_script $js_naf_capacity_pools_option_filtered, $ds_naf_capacity_pools_tag_filtered, $param_resource_types
end
script "js_naf_capacity_pools_option_filtered", type: "javascript" do
parameters "ds_naf_capacity_pools_tag_filtered", "param_resource_types"
result "result"
code <<-EOS
result = []
if (param_resource_types == "Pools and Volumes") {
result = ds_naf_capacity_pools_tag_filtered
}
EOS
end
datasource "ds_naf_volumes" do
iterate $ds_naf_capacity_pools_option_filtered
request do
auth $auth_azure
host $param_azure_endpoint
path join(["/subscriptions/", val(iter_item, "subscription_id"), "/resourceGroups/", val(iter_item, "resource_group_name"), "/providers/Microsoft.NetApp/netAppAccounts/", val(iter_item, "naf_account_name"), "/capacityPools/", val(iter_item, "naf_pool_name"), "/volumes"])
query "api-version", "2023-05-01"
ignore_status [400, 403, 404]
end
result do
encoding "json"
collect jmes_path(response, "value[*]") do
field "subscription_id", jmes_path(iter_item, "subscription_id")
field "resource_group_name", jmes_path(iter_item, "resource_group_name")
field "resource_kind", jmes_path(col_item, "type")
field "naf_account_name", jmes_path(iter_item, "naf_account_name")
field "naf_pool_id", jmes_path(iter_item, "naf_pool_id")
field "naf_pool_name", jmes_path(iter_item, "naf_pool_name")
field "naf_pool_size", jmes_path(iter_item, "naf_pool_size")
field "naf_pool_region", jmes_path(iter_item, "naf_pool_region")
field "naf_pool_service", jmes_path(iter_item, "naf_pool_service")
field "naf_pool_encryption", jmes_path(iter_item, "naf_pool_encryption")
field "naf_pool_cool", jmes_path(iter_item, "naf_pool_cool")
field "naf_volume_name", jmes_path(col_item, "name")
field "naf_volume_id", jmes_path(col_item, "id")
field "naf_usage_threshold", jmes_path(col_item, "properties.usageThreshold")
field "naf_volume_created_at", jmes_path(col_item, "systemData.createdAt")
field "tags", jmes_path(col_item, "tags")
end
end
end
datasource "ds_naf_volumes_tag_filtered" do
run_script $js_objects_tag_filtered, $ds_naf_volumes, $param_exclusion_tags, $param_exclusion_tags_boolean
end
datasource "ds_naf_volume_metrics" do
iterate $ds_naf_volumes_tag_filtered
request do
run_script $js_naf_volume_metrics, val(iter_item, "naf_volume_id"), $param_azure_endpoint
end
result do
encoding "json"
field "subscription_id", jmes_path(iter_item, "subscription_id")
field "resource_group_name", jmes_path(iter_item, "resource_group_name")
field "resource_kind", jmes_path(iter_item, "resource_kind")
field "naf_account_name", jmes_path(iter_item, "naf_account_name")
field "naf_pool_id", jmes_path(iter_item, "naf_pool_id")
field "naf_pool_name", jmes_path(iter_item, "naf_pool_name")
field "naf_pool_size", jmes_path(iter_item, "naf_pool_size")
field "naf_pool_region", jmes_path(iter_item, "naf_pool_region")
field "naf_pool_service", jmes_path(iter_item, "naf_pool_service")
field "naf_pool_encryption", jmes_path(iter_item, "naf_pool_encryption")
field "naf_pool_cool", jmes_path(iter_item, "naf_pool_cool")
field "naf_volume_name", jmes_path(iter_item, "naf_volume_name")
field "naf_volume_id", jmes_path(iter_item, "naf_volume_id")
field "naf_usage_threshold", jmes_path(iter_item, "naf_usage_threshold")
field "naf_volume_created_at", jmes_path(iter_item, "naf_volume_created_at")
field "tags", jmes_path(iter_item, "tags")
field "naf_volume_metrics", jmes_path(response, "value[*]")
end
end
script "js_naf_volume_metrics", type: "javascript" do
parameters "volId", "param_azure_endpoint"
result "request"
code <<-EOS
var end_date = new Date()
var start_date = new Date(end_date)
start_date.setHours(end_date.getHours() - 12)
start_date.setMilliseconds(0)
start_date.setSeconds(0)
start_date.setMinutes(0)
timespan = start_date.toISOString() + "/" + end_date.toISOString()
var request = {
auth: "auth_azure",
host: param_azure_endpoint,
path: volId + "/providers/microsoft.insights/metrics",
query_params: {
"api-version": "2018-01-01",
"metricnames": "VolumeLogicalSize,VolumeConsumedSizePercentage",
"timespan": timespan,
},
headers: {
"User-Agent": "RS Policies",
},
ignore_status: [400, 403, 404]
}
EOS
end
datasource "ds_naf_oversized_pools" do
run_script $js_naf_oversized_pools, $ds_naf_pool_metrics, $ds_naf_get_costs, $ds_currency, $ds_applied_policy, $param_stats_underutil_threshold_pool_value, $param_min_savings, $param_resource_types, $param_show_size_increment_recommendations
end
script "js_naf_oversized_pools", type: "javascript" do
parameters "ds_naf_pool_metrics", "ds_naf_get_costs", "ds_currency", "ds_applied_policy", "param_stats_underutil_threshold_pool_value", "param_min_savings", "param_resource_types", "param_show_size_increment_recommendations"
result "result"
code <<-'EOS'
// Variables
result = []
var minPoolSize = 2048
var maxPoolSize = 1024000
var total_savings = 0.0
// Functions
function bytesToGibibytes(bytes) { return Math.ceil(bytes * 9.3132257461548e-10) }
function gibibytesToTebibytes(gibibytes) { return Math.ceil(gibibytes / 1024) }
function poolCanBeResized(size, recommendedSize, param_show_size_increment_recommendations) {
var sizeChangeGiB = Math.abs(size - recommendedSize)
// Azure only admits 1 TiB steps
if (sizeChangeGiB < 1024) { return false }
if (recommendedSize == size) { return false }
if (recommendedSize > size && param_show_size_increment_recommendations == "No") { return false }
if (size == minPoolSize && recommendedSize < minPoolSize) { return false }
if (size == maxPoolSize && recommendedSize > maxPoolSize) { return false }
return true
}
function objectTagsToArrayTags(tags) {
var arrayTags = []
if (typeof(tags) == 'object') {
_.each(Object.keys(tags), function(key) { arrayTags.push([key, "=", tags[key]].join('')) })
}
return arrayTags
}
function getMonthlyCost(pool, poolSize) {
var monthlyCost = 0.0
_.each(ds_naf_get_costs, function(cost){
if (pool.naf_pool_region == cost.region) {
if (pool.naf_pool_service == "Standard" && cost['skuName'].indexOf("Standard") > -1) {
if (pool.naf_pool_cool == false && pool.naf_pool_encryption == "Single" && cost['skuName'] == "Standard") {
monthlyCost = cost.retailPrice * poolSize * 730
} else if (pool.naf_pool_cool == true && cost['skuName'].indexOf("Cool Access") > -1) {
monthlyCost = cost.retailPrice * poolSize * 730
} else if (pool.naf_pool_encryption == "Double" && cost['skuName'].indexOf("Double") > -1) {
monthlyCost = cost.retailPrice * poolSize * 730
}
}
if (pool.naf_pool_service == "Premium" && cost['skuName'].indexOf("Premium") > -1) {
if (pool.naf_pool_encryption == "Single" && cost['skuName'] == "Premium") {
monthlyCost = cost.retailPrice * poolSize * 730
} else if (pool.naf_pool_encryption == "Double" && cost['skuName'].indexOf("Double") > -1) {
monthlyCost = cost.retailPrice * poolSize * 730
}
}
if (pool.naf_pool_service == "Ultra" && cost['skuName'].indexOf("Ultra") > -1) {
if (pool.naf_pool_encryption == "Single" && cost['skuName'] == "Ultra") {
monthlyCost = cost.retailPrice * poolSize * 730
} else if (pool.naf_pool_encryption == "Double" && cost['skuName'].indexOf("Double") > -1) {
monthlyCost = cost.retailPrice * poolSize * 730
}
}
}
})
return monthlyCost
}
// Main Logic
if (param_resource_types == "Pools") {
_.each(ds_naf_pool_metrics, function(pool){
_.each(pool.naf_pool_metrics, function (metric) {
filteredTimeseries = _.filter(metric.timeseries[0].data, function(point) { return point.average != undefined })
var lastPointInTS = _.last(filteredTimeseries).average
switch (metric.name.value) {
case "VolumePoolAllocatedUsed":
pool.consumedSize = bytesToGibibytes(lastPointInTS)
break
case "VolumePoolAllocatedSize":
pool.allocatedSize = bytesToGibibytes(lastPointInTS)
break
}
})
if (pool.allocatedSize != undefined && pool.consumedSize != undefined) {
var poolConsumedPercentage = Math.round(pool.consumedSize * 100 / pool.allocatedSize)
if (poolConsumedPercentage != param_stats_underutil_threshold_pool_value) {
var poolRecommendedSize = Math.ceil(Math.ceil(pool.consumedSize * 100 / param_stats_underutil_threshold_pool_value) / 1024) * 1024
if (poolCanBeResized(pool.allocatedSize, poolRecommendedSize, param_show_size_increment_recommendations)) {
if (poolRecommendedSize < minPoolSize) { poolRecommendedSize = minPoolSize }
if (poolRecommendedSize > maxPoolSize) { poolRecommendedSize = maxPoolSize }
var allocatedSizeCost = getMonthlyCost(pool, pool.allocatedSize)
var recommendedSizeCost = getMonthlyCost(pool, poolRecommendedSize)
// If Recommended Size costs more than allocatedSize, savings will be 0
var savings = (allocatedSizeCost-recommendedSizeCost) < 0 ? 0 : (allocatedSizeCost-recommendedSizeCost)
if (savings >= param_min_savings) {
total_savings += savings
size = Math.round(pool['allocatedSize'] / 1024)
recommendedSize = gibibytesToTebibytes(poolRecommendedSize)
recommendationDetails = [
"Downsize Azure NetApp Pool ", pool['naf_pool_name'], " ",
"in Azure Subscription ", pool['subscription_name'], " ",
"(", pool['subscription_id'], ") ",
"from ", size, " TiB ",
"to ", recommendedSize, " TiB"
].join('')
result.push({
accountID: pool['subscription_id'],
accountName: pool['subscription_name'],
resourceID: pool['naf_pool_id'],
resourceGroup: pool['resource_group_name'],
resourceName: pool['naf_pool_name'],
size: size,
allocatedUsed: (pool['consumedSize'] / 1024).toFixed(3),
consumedPercentage: poolConsumedPercentage,
createdAt: pool['naf_pool_created_at'],
threshold: param_stats_underutil_threshold_pool_value,
recommendedSize: recommendedSize,
savings: parseFloat(savings.toFixed(3))
id: pool['naf_pool_id'],
region: pool['naf_pool_region'],
resourceTier: pool['naf_pool_service'],
resourceType: pool['resource_kind'],
tags: objectTagsToArrayTags(pool.tags),
savingsCurrency: "USD",
service: pool['service_type'],
recommendationDetails: recommendationDetails
})
}
}
}
}
})
}
if (result.length > 0 && param_resource_types == "Pools") {
result[0].total_savings = total_savings.toFixed(2)
result[0].savings_currency = "USD"
result[0].message = "Pools shown here meet the following conditions:\n\n"
result[0].message += "- A " + (param_show_size_increment_recommendations == "Yes" ? "different" : "lower") + " value than " + param_stats_underutil_threshold_pool_value + "% of used capacity.\n"
result[0].message += "\nThe above settings can be modified by editing the applied policy and changing the appropriate parameters."
result[0].policy_name = ds_applied_policy.name
} else {
result = [{
accountID: "",
accountName: "",
resourceID: "",
resourceGroup: "",
resourceName: "",
size: "",
allocatedUsed: "",
consumedPercentage: "",
createdAt: "",
threshold: "",
recommendedSize: "",
savings: "",
id: "",
region: "",
resourceTier: "",
resourceType: "",
tags: "",
savingsCurrency: "",
service: "",
recommendationDetails: "",
total_savings: "",
savings_currency: "",
message: "",
policy_name: ""
}]
}
EOS
end
datasource "ds_naf_oversized_volumes" do
run_script $js_naf_oversized_volumes, $ds_naf_volume_metrics, $ds_naf_pool_metrics, $ds_naf_get_costs, $ds_currency, $ds_applied_policy, $param_stats_underutil_threshold_pool_value, $param_stats_underutil_threshold_volume_value, $param_min_savings, $param_resource_types, $param_show_size_increment_recommendations
end
script "js_naf_oversized_volumes", type: "javascript" do
parameters "ds_naf_volume_metrics", "ds_naf_pool_metrics", "ds_naf_get_costs", "ds_currency", "ds_applied_policy", "param_stats_underutil_threshold_pool_value", "param_stats_underutil_threshold_volume_value", "param_min_savings", "param_resource_types", "param_show_size_increment_recommendations"
result "result"
code <<-'EOS'
// Variables
result = []
var minPoolSize = 2048
var maxPoolSize = 1024000
var minVolSize = 100
var maxVolSize = 512000
var total_savings = 0.0
// Functions
function poolCanBeResized(size, recommendedSize, param_show_size_increment_recommendations) {
var sizeChangeGiB = Math.abs(size - recommendedSize)
// Azure only admits 1 TiB steps
if (sizeChangeGiB < 1024) { return false }
if (recommendedSize == size) { return false }
if (recommendedSize > size && param_show_size_increment_recommendations == "No") { return false }
if (size == minPoolSize && recommendedSize < minPoolSize) { return false }
if (size == maxPoolSize && recommendedSize > maxPoolSize) { return false }
return true
}
function objectTagsToArrayTags(tags) {
var arrayTags = []
if (typeof(tags) == 'object') {
_.each(Object.keys(tags), function(key) { arrayTags.push([key, "=", tags[key]].join('')) })
}
return arrayTags
}
function getMonthlyCost(pool, poolSize) {
var monthlyCost = 0.0
_.each(ds_naf_get_costs, function(cost){
if (pool.naf_pool_region == cost.region) {
if (pool.naf_pool_service == "Standard" && cost['skuName'].indexOf("Standard") > -1) {
if (pool.naf_pool_cool == false && pool.naf_pool_encryption == "Single" && cost['skuName'] == "Standard") {
monthlyCost = cost.retailPrice * poolSize * 730
} else if (pool.naf_pool_cool == true && cost['skuName'].indexOf("Cool Access") > -1) {
monthlyCost = cost.retailPrice * poolSize * 730
} else if (pool.naf_pool_encryption == "Double" && cost['skuName'].indexOf("Double") > -1) {
monthlyCost = cost.retailPrice * poolSize * 730
}
}
if (pool.naf_pool_service == "Premium" && cost['skuName'].indexOf("Premium") > -1) {
if (pool.naf_pool_encryption == "Single" && cost['skuName'] == "Premium") {
monthlyCost = cost.retailPrice * poolSize * 730
} else if (pool.naf_pool_encryption == "Double" && cost['skuName'].indexOf("Double") > -1) {
monthlyCost = cost.retailPrice * poolSize * 730
}
}
if (pool.naf_pool_service == "Ultra" && cost['skuName'].indexOf("Ultra") > -1) {
if (pool.naf_pool_encryption == "Single" && cost['skuName'] == "Ultra") {
monthlyCost = cost.retailPrice * poolSize * 730
} else if (pool.naf_pool_encryption == "Double" && cost['skuName'].indexOf("Double") > -1) {
monthlyCost = cost.retailPrice * poolSize * 730
}
}
}
})
return monthlyCost
}
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
}
function bytesToGibibytes(bytes) { return Math.ceil(bytes * 9.3132257461548e-10) }
function gibibytesToTebibytes(gibibytes) { return Math.ceil(gibibytes / 1024) }
function volumeCanBeResized(size, recommendedSize) {
if (size == minVolSize && recommendedSize < minVolSize) { return false }
if (size == maxVolSize && recommendedSize > maxVolSize) { return false }
return true
}
// Main logic
if (param_resource_types == "Pools and Volumes") {
_.each(ds_naf_volume_metrics, function(volume) {
volume.volume_allocated_size = bytesToGibibytes(volume.naf_usage_threshold)
_.each(volume.naf_volume_metrics, function(metric) {
filteredTimeseries = _.filter(metric.timeseries[0].data, function(point) { return point.average != undefined })
var lastPointInTS = _.last(filteredTimeseries).average
switch (metric.name.value) {
case "VolumeLogicalSize":
volume.volume_logical_size = bytesToGibibytes(lastPointInTS)
break
case "VolumeConsumedSizePercentage":
volume.volume_consumed_size_percentage = Math.round(lastPointInTS)
break
}
})
// Check if volume contains required metrics info
volume.recommendedAllocatedSize = volume.volume_allocated_size
if (volume.volume_logical_size != undefined && volume.volume_allocated_size != undefined && volume.volume_consumed_size_percentage != undefined) {
if (volume.volume_consumed_size_percentage != param_stats_underutil_threshold_volume_value) {
var recommendedVolumeAllocatedSize = Math.ceil(volume.volume_logical_size * 100 / param_stats_underutil_threshold_volume_value)
if (volumeCanBeResized(volume.volume_allocated_size, recommendedVolumeAllocatedSize)) {
if (recommendedVolumeAllocatedSize < minVolSize) { recommendedVolumeAllocatedSize = minVolSize }
if (recommendedVolumeAllocatedSize > maxVolSize) { recommendedVolumeAllocatedSize = maxVolSize }
volume.recommendedAllocatedSize = recommendedVolumeAllocatedSize
}
}
}
})
_.each(ds_naf_pool_metrics, function(pool){
pool.naf_pool_volumes = []
var recommendedPoolAllocatedUsed = 0
_.each(ds_naf_volume_metrics, function(volume) {
if (pool.naf_pool_id == volume.naf_pool_id) {
if (volume.recommendedAllocatedSize != volume.volume_allocated_size && volume.volume_logical_size != undefined) {
endpool.naf_pool_volumes.push(volume)
}
recommendedPoolAllocatedUsed += volume.recommendedAllocatedSize
}
})
_.each(pool.naf_pool_metrics, function (metric) {
filteredTimeseries = _.filter(metric.timeseries[0].data, function(point) { return point.average != undefined })
var lastPointInTS = _.last(filteredTimeseries).average
switch (metric.name.value) {
case "VolumePoolAllocatedUsed":
pool.consumedSize = bytesToGibibytes(lastPointInTS)
break
case "VolumePoolAllocatedSize":
pool.allocatedSize = bytesToGibibytes(lastPointInTS)
break
}
})
if (pool.allocatedSize != undefined && pool.consumedSize != undefined) {
var poolConsumedPercentage = Math.round(recommendedPoolAllocatedUsed * 100 / pool.allocatedSize)
var poolOldConsumedPercentage = Math.round(pool.consumedSize * 100 / pool.allocatedSize)
if (poolConsumedPercentage != param_stats_underutil_threshold_pool_value) {
var poolRecommendedSize = Math.ceil(Math.ceil(recommendedPoolAllocatedUsed * 100 / param_stats_underutil_threshold_pool_value) / 1024) * 1024
if (poolCanBeResized(pool.allocatedSize, poolRecommendedSize, param_show_size_increment_recommendations)) {