-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathgoogle_delete_old_snapshots.pt
1195 lines (1063 loc) · 39.3 KB
/
google_delete_old_snapshots.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 "Google Old Snapshots"
rs_pt_ver 20180301
type "policy"
short_description "Checks for snapshots older than specified number of days and, optionally, deletes them. See the [README](https://github.com/flexera-public/policy_templates/tree/master/cost/google/old_snapshots) 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: "5.1.2",
provider:"Google",
service: "Storage",
policy_set: "Old Snapshots",
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_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_snapshot_age" do
type "number"
category "Policy Settings"
label "Snapshot Age Threshold"
description "The number of days since the snapshot was created to consider a snapshot old."
min_value 1
default 30
end
parameter "param_projects_allow_or_deny" do
type "string"
category "Filters"
label "Allow/Deny Projects"
description "Allow or Deny entered Projects. See the README for more details."
allowed_values "Allow", "Deny"
default "Allow"
end
parameter "param_projects_list" do
type "list"
category "Filters"
label "Allow/Deny Projects List"
description "A list of allowed or denied Subscription IDs/names. See the README for more details."
default []
end
parameter "param_exclusion_labels" do
type "list"
category "Filters"
label "Exclusion Labels"
description "Cloud native labels 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_labels_boolean" do
type "string"
category "Filters"
label "Exclusion Labels: Any / All"
description "Whether to filter instances containing any of the specified labels or only those that contain all of them. Only applicable if more than one value is entered in the 'Exclusion Labels' field."
allowed_values "Any", "All"
default "Any"
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 ["Delete Snapshots"]
default []
end
###############################################################################
# Authentication
###############################################################################
credentials "auth_google" do
schemes "oauth2"
label "Google"
description "Select the Google Cloud Credential from the list."
tags "provider=gce"
end
credentials "auth_flexera" do
schemes "oauth2"
label "Flexera"
description "Select Flexera One OAuth2 credentials"
tags "provider=flexera"
end
###############################################################################
# Pagination
###############################################################################
pagination "pagination_google" do
get_page_marker do
body_path "nextPageToken"
end
set_page_marker do
query "pageToken"
end
end
###############################################################################
# Datasources & Scripts
###############################################################################
# Table to derive region from zone
datasource "ds_zone_to_region" do
run_script $js_zone_to_region
end
script "js_zone_to_region", type:"javascript" do
result "result"
code <<-EOS
result = {
"us-east1-b": "us-east1",
"us-east1-c": "us-east1",
"us-east1-d": "us-east1",
"us-east4-c": "us-east4",
"us-east4-b": "us-east4",
"us-east4-a": "us-east4",
"us-central1-c": "us-central1",
"us-central1-a": "us-central1",
"us-central1-f": "us-central1",
"us-central1-b": "us-central1",
"us-west1-b": "us-west1",
"us-west1-c": "us-west1",
"us-west1-a": "us-west1",
"europe-west4-a": "europe-west4",
"europe-west4-b": "europe-west4",
"europe-west4-c": "europe-west4",
"europe-west1-b": "europe-west1",
"europe-west1-d": "europe-west1",
"europe-west1-c": "europe-west1",
"europe-west3-c": "europe-west3",
"europe-west3-a": "europe-west3",
"europe-west3-b": "europe-west3",
"europe-west2-c": "europe-west2",
"europe-west2-b": "europe-west2",
"europe-west2-a": "europe-west2",
"asia-east1-b": "asia-east1",
"asia-east1-a": "asia-east1",
"asia-east1-c": "asia-east1",
"asia-southeast1-b": "asia-southeast1",
"asia-southeast1-a": "asia-southeast1",
"asia-southeast1-c": "asia-southeast1",
"asia-northeast1-b": "asia-northeast1",
"asia-northeast1-c": "asia-northeast1",
"asia-northeast1-a": "asia-northeast1",
"asia-south1-c": "asia-south1",
"asia-south1-b": "asia-south1",
"asia-south1-a": "asia-south1",
"australia-southeast1-b": "australia-southeast1",
"australia-southeast1-c": "australia-southeast1",
"australia-southeast1-a": "australia-southeast1",
"southamerica-east1-b": "southamerica-east1",
"southamerica-east1-c": "southamerica-east1",
"southamerica-east1-a": "southamerica-east1",
"asia-east2-a": "asia-east2",
"asia-east2-b": "asia-east2",
"asia-east2-c": "asia-east2",
"asia-northeast2-a": "asia-northeast2",
"asia-northeast2-b": "asia-northeast2",
"asia-northeast2-c": "asia-northeast2",
"asia-northeast3-a": "asia-northeast3",
"asia-northeast3-b": "asia-northeast3",
"asia-northeast3-c": "asia-northeast3",
"asia-south2-a": "asia-south2",
"asia-south2-b": "asia-south2",
"asia-south2-c": "asia-south2",
"asia-southeast2-a": "asia-southeast2",
"asia-southeast2-b": "asia-southeast2",
"asia-southeast2-c": "asia-southeast2",
"australia-southeast2-a": "australia-southeast2",
"australia-southeast2-b": "australia-southeast2",
"australia-southeast2-c": "australia-southeast2",
"europe-central2-a": "europe-central2",
"europe-central2-b": "europe-central2",
"europe-central2-c": "europe-central2",
"europe-north1-a": "europe-north1",
"europe-north1-b": "europe-north1",
"europe-north1-c": "europe-north1",
"europe-southwest1-a": "europe-southwest1",
"europe-southwest1-b": "europe-southwest1",
"europe-southwest1-c": "europe-southwest1",
"europe-west6-a": "europe-west6",
"europe-west6-b": "europe-west6",
"europe-west6-c": "europe-west6",
"northamerica-northeast1-a": "northamerica-northeast1",
"northamerica-northeast1-b": "northamerica-northeast1",
"northamerica-northeast1-c": "northamerica-northeast1",
"northamerica-northeast2-a": "northamerica-northeast2",
"northamerica-northeast2-b": "northamerica-northeast2",
"northamerica-northeast2-c": "northamerica-northeast2",
"us-west2-a": "us-west2",
"us-west2-b": "us-west2",
"us-west2-c": "us-west2",
"us-west3-a": "us-west3",
"us-west3-b": "us-west3",
"us-west3-c": "us-west3",
"us-west4-a": "us-west4",
"us-west4-b": "us-west4",
"us-west4-c": "us-west4",
"us-west5-a": "us-west5",
"us-west5-b": "us-west5",
"us-west5-c": "us-west5",
"us-west6-a": "us-west6",
"us-west6-b": "us-west6",
"us-west6-c": "us-west6",
"us-west7-a": "us-west7",
"us-west7-b": "us-west7",
"us-west7-c": "us-west7"
}
EOS
end
# 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
# 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
end
script "js_conditional_currency_conversion", type: "javascript" do
parameters "ds_currency_target"
result "result"
code <<-EOS
result = []
// Make the request only if the target currency is not USD
if (ds_currency_target['code'] != 'USD') {
result = [1]
}
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", "USD"
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_google_projects" do
request do
auth $auth_google
pagination $pagination_google
host "cloudresourcemanager.googleapis.com"
path "/v1/projects/"
query "filter", "(lifecycleState:ACTIVE)"
# 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")
end
result do
encoding "json"
collect jmes_path(response, "projects[*]") do
field "number", jmes_path(col_item, "projectNumber")
field "id", jmes_path(col_item, "projectId")
field "name", jmes_path(col_item, "name")
end
end
end
datasource "ds_google_projects_filtered" do
run_script $js_google_projects_filtered, $ds_google_projects, $param_projects_allow_or_deny, $param_projects_list
end
script "js_google_projects_filtered", type: "javascript" do
parameters "ds_google_projects", "param_projects_allow_or_deny", "param_projects_list"
result "result"
code <<-'EOS'
if (param_projects_list.length > 0) {
result = _.filter(ds_google_projects, function(project) {
include_project = _.contains(param_projects_list, project['id']) || _.contains(param_projects_list, project['name']) || _.contains(param_projects_list, project['number'])
if (param_projects_allow_or_deny == "Deny") {
include_project = !include_project
}
return include_project
})
} else {
result = ds_google_projects
}
EOS
end
datasource "ds_google_snapshots" do
iterate $ds_google_projects_filtered
request do
auth $auth_google
pagination $pagination_google
host "compute.googleapis.com"
path join(["/compute/v1/projects/", val(iter_item, "id"), "/global/snapshots"])
query "filter", "status=READY"
ignore_status [403, 404]
end
result do
encoding "json"
collect jmes_path(response, "items[*]") do
field "architecture", jmes_path(col_item, "architecture")
field "creationTimestamp", jmes_path(col_item, "creationTimestamp")
field "diskSizeGb", jmes_path(col_item, "diskSizeGb")
field "labels", jmes_path(col_item, "labels")
field "id", jmes_path(col_item, "id")
field "kind", jmes_path(col_item, "kind")
field "name", jmes_path(col_item, "name")
field "selfLink", jmes_path(col_item, "selfLink")
field "snapshotType", jmes_path(col_item, "snapshotType")
field "sourceDisk", jmes_path(col_item, "sourceDisk")
field "sourceDiskId", jmes_path(col_item, "sourceDiskId")
field "status", jmes_path(col_item, "status")
field "projectId", val(iter_item, "id")
field "projectName", val(iter_item, "name")
field "projectNumber", val(iter_item, "number")
end
end
end
datasource "ds_google_snapshots_label_filtered" do
run_script $js_google_snapshots_label_filtered, $ds_google_snapshots, $param_exclusion_labels, $param_exclusion_labels_boolean
end
script "js_google_snapshots_label_filtered", type: "javascript" do
parameters "ds_google_snapshots", "param_exclusion_labels", "param_exclusion_labels_boolean"
result "result"
code <<-EOS
comparators = _.map(param_exclusion_labels, 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_labels.length > 0) {
result = _.reject(ds_google_snapshots, function(resource) {
resource_labels = {}
if (typeof(resource['labels']) == 'object') { resource_labels = resource['labels'] }
// Store a list of found labels
found_labels = []
_.each(comparators, function(comparator) {
comparison = comparator['comparison']
value = comparator['value']
string = comparator['string']
resource_label = resource_labels[comparator['key']]
if (comparison == 'key' && resource_label != undefined) { found_labels.push(string) }
if (comparison == '==' && resource_label == value) { found_labels.push(string) }
if (comparison == '!=' && resource_label != value) { found_labels.push(string) }
if (comparison == '=~') {
if (resource_label != undefined && value.test(resource_label)) { found_labels.push(string) }
}
if (comparison == '!~') {
if (resource_label == undefined) { found_labels.push(string) }
if (resource_label != undefined && value.test(resource_label)) { found_labels.push(string) }
}
})
all_labels_found = found_labels.length == comparators.length
any_labels_found = found_labels.length > 0 && param_exclusion_labels_boolean == 'Any'
return all_labels_found || any_labels_found
})
} else {
result = ds_google_snapshots
}
EOS
end
datasource "ds_google_old_snapshots" do
run_script $js_google_old_snapshots, $ds_google_snapshots_label_filtered, $ds_applied_policy, $param_snapshot_age
end
script "js_google_old_snapshots", type: "javascript" do
parameters "ds_google_snapshots_label_filtered", "ds_applied_policy", "param_snapshot_age"
result "result"
code <<-'EOS'
result = []
_.each(ds_google_snapshots_label_filtered, function(snapshot) {
labels = []
if (typeof(snapshot['labels']) == 'object') {
_.each(Object.keys(snapshot['labels']), function(key) {
labels.push([key, "=", snapshot['labels'][key]].join(''))
})
}
snapshotTime = Date.parse(snapshot['creationTimestamp'])
age = Math.round((new Date().getTime() - new Date(snapshotTime).getTime()) / (1000 * 3600 * 24))
if (age > param_snapshot_age) {
recommendationDetails = [
"Delete Google snapshot ", snapshot["name"], " ",
"in Google Project ", snapshot["projectName"],
" (", snapshot["projectId"], ")"
].join('')
result.push({
architecture: snapshot['architecture'],
size: snapshot['diskSizeGb'],
resourceID: snapshot['id'],
kind: snapshot['kind'],
resourceName: snapshot['name'],
selfLink: snapshot['selfLink'],
snapshotType: snapshot['snapshotType'],
sourceDisk: snapshot['sourceDisk'],
sourceDiskId: snapshot['sourceDiskId'],
status: snapshot['status'],
accountID: snapshot['projectId'],
accountName: snapshot['projectName'],
projectNumber: snapshot['projectNumber'],
policy_name: ds_applied_policy['name'],
createdAt: new Date(snapshotTime).toISOString(),
labels: labels.join(', '),
lookbackPeriod: param_snapshot_age,
recommendationDetails: recommendationDetails,
age: age,
service: "Compute Engine",
message: ''
})
}
})
EOS
end
datasource "ds_zones" do
iterate $ds_google_projects_filtered
request do
auth $auth_google
pagination $pagination_google
host "compute.googleapis.com"
path join(["/compute/v1/projects/", val(iter_item, "id"), "/zones"])
ignore_status [403, 404]
end
result do
encoding "json"
collect jmes_path(response, "items[*]") do
field "id", jmes_path(col_item, "id")
field "name", jmes_path(col_item, "name")
field "projectId", val(iter_item, "id")
field "projectName", val(iter_item, "name")
field "projectNumber", val(iter_item, "number")
end
end
end
datasource "ds_zonal_disks" do
iterate $ds_zones
request do
auth $auth_google
pagination $pagination_google
host "compute.googleapis.com"
path join(["/compute/v1/projects/", val(iter_item, "projectId"), "/zones/", val(iter_item, "name"), "/disks"])
ignore_status [403, 404]
end
result do
encoding "json"
collect jmes_path(response, "items[*]") do
field "id", jmes_path(col_item, "id")
field "kind", jmes_path(col_item, "kind")
field "name", jmes_path(col_item, "name")
field "description", jmes_path(col_item, "description")
field "sizeGb", jmes_path(col_item, "sizeGb")
field "zone", jmes_path(col_item, "zone")
field "status", jmes_path(col_item, "status")
field "projectId", val(iter_item, "projectId")
field "projectName", val(iter_item, "projectName")
field "projectNumber", val(iter_item, "projectNumber")
end
end
end
datasource "ds_regions" do
iterate $ds_google_projects_filtered
request do
auth $auth_google
pagination $pagination_google
host "compute.googleapis.com"
path join(["/compute/v1/projects/", val(iter_item, "id"), "/regions"])
ignore_status [403, 404]
end
result do
encoding "json"
collect jmes_path(response, "items[*]") do
field "id", jmes_path(col_item, "id")
field "name", jmes_path(col_item, "name")
field "projectId", val(iter_item, "id")
field "projectName", val(iter_item, "name")
field "projectNumber", val(iter_item, "number")
end
end
end
datasource "ds_regional_disks" do
iterate $ds_regions
request do
auth $auth_google
pagination $pagination_google
host "compute.googleapis.com"
path join(["/compute/v1/projects/", val(iter_item, "projectId"), "/regions/", val(iter_item, "name"), "/disks"])
ignore_status [403, 404]
end
result do
encoding "json"
collect jmes_path(response, "items[*]") do
field "id", jmes_path(col_item, "id")
field "kind", jmes_path(col_item, "kind")
field "name", jmes_path(col_item, "name")
field "description", jmes_path(col_item, "description")
field "sizeGb", jmes_path(col_item, "sizeGb")
field "zone", jmes_path(col_item, "zone")
field "status", jmes_path(col_item, "status")
field "region", val(iter_item, "name")
field "projectId", val(iter_item, "projectId")
field "projectName", val(iter_item, "projectName")
field "projectNumber", val(iter_item, "projectNumber")
end
end
end
datasource "ds_disk_to_region" do
run_script $js_disk_to_region, $ds_zonal_disks, $ds_regional_disks, $ds_zone_to_region
end
script "js_disk_to_region", type: "javascript" do
parameters "ds_zonal_disks", "ds_regional_disks", "ds_zone_to_region"
result "result"
code <<-'EOS'
disks = ds_zonal_disks.concat(ds_regional_disks)
result = {}
_.each(disks, function(disk) {
id = disk["id"]
zone = disk["zone"].split('/')[8]
region = ds_zone_to_region[zone]
result[id] = region
})
EOS
end
datasource "ds_google_old_snapshots_with_region" do
run_script $js_google_old_snapshots_with_region, $ds_google_old_snapshots, $ds_disk_to_region
end
script "js_google_old_snapshots_with_region", type: "javascript" do
parameters "ds_google_old_snapshots", "ds_disk_to_region"
result "result"
code <<-'EOS'
result = _.map(ds_google_old_snapshots, function(snapshot) {
return {
architecture: snapshot['architecture'],
size: snapshot['size'],
resourceID: snapshot['resourceID'],
kind: snapshot['kind'],
resourceName: snapshot['resourceName'],
selfLink: snapshot['selfLink'],
snapshotType: snapshot['snapshotType'],
sourceDisk: snapshot['sourceDisk'],
sourceDiskId: snapshot['sourceDiskId'],
status: snapshot['status'],
accountID: snapshot['accountID'],
accountName: snapshot['accountName'],
projectNumber: snapshot['projectNumber'],
policy_name: snapshot['policy_name'],
createdAt: snapshot['createdAt'],
labels: snapshot['labels'],
lookbackPeriod: snapshot['lookbackPeriod'],
recommendationDetails: snapshot['recommendationDetails'],
age: snapshot['age'],
service: snapshot['service'],
message: snapshot['message'],
region: ds_disk_to_region[snapshot['sourceDiskId']]
}
})
EOS
end
datasource "ds_google_billing_services" do
request do
auth $auth_google
pagination $pagination_google
host "cloudbilling.googleapis.com"
path "/v1/services"
end
result do
encoding "json"
collect jmes_path(response, "services[*]") do
field "businessEntityName", jmes_path(col_item, "businessEntityName")
field "displayName", jmes_path(col_item, "displayName")
field "name", jmes_path(col_item, "name")
field "serviceId", jmes_path(col_item, "serviceId")
end
end
end
datasource "ds_google_billing_compute_service" do
run_script $js_google_billing_compute_service, $ds_google_billing_services
end
script "js_google_billing_compute_service", type: "javascript" do
parameters "ds_google_billing_services"
result "result"
code <<-'EOS'
compute_service = _.find(ds_google_billing_services, function(service) {
return service["displayName"] == "Compute Engine"
})
result = [compute_service]
EOS
end
datasource "ds_google_billing_compute_service_pricing" do
iterate $ds_google_billing_compute_service
request do
auth $auth_google
pagination $pagination_google
host "cloudbilling.googleapis.com"
path join(["/v1/", val(iter_item, "name"), "/skus"])
end
result do
encoding "json"
collect jmes_path(response, "skus[*]") do
field "name", jmes_path(col_item, "name")
field "description", jmes_path(col_item, "description")
field "skuId", jmes_path(col_item, "skuId")
field "regions", jmes_path(col_item, "geoTaxonomy.regions")
field "regionType", jmes_path(col_item, "geoTaxonomy.type")
field "resourceFamily", jmes_path(col_item, "category.resourceFamily")
field "resourceGroup", jmes_path(col_item, "category.resourceGroup")
field "usageType", jmes_path(col_item, "category.usageType")
field "resourceFamily", jmes_path(col_item, "category.resourceFamily")
field "pricingInfo", jmes_path(col_item, "pricingInfo")
end
end
end
datasource "ds_google_billing_snapshot_pricing" do
run_script $js_google_billing_snapshot_pricing, $ds_google_billing_compute_service_pricing
end
script "js_google_billing_snapshot_pricing", type: "javascript" do
parameters "ds_google_billing_compute_service_pricing"
result "result"
code <<-'EOS'
filtered_pricing = _.filter(ds_google_billing_compute_service_pricing, function(entry) {
return entry["description"].indexOf("Storage PD Snapshot") != -1
})
sorted_data = _.map(filtered_pricing, function(entry) {
rate = _.find(entry["pricingInfo"][0]["pricingExpression"]["tieredRates"], function(item) {
return item["unitPrice"]["nanos"] != 0
})
location = entry["description"].split("PD Snapshot in ")[1]
if (entry["regionType"] == "REGIONAL") { location = entry["regions"][0] }
if (entry["description"] == "Storage PD Snapshot") { location = "default" }
return {
name: entry["name"],
description: entry["description"],
skuId: entry["skuId"],
regions: entry["regions"],
regionType: entry["regionType"],
location: location,
startUsageAmountGiB: rate["startUsageAmount"],
pricePerGiB: rate["unitPrice"]["nanos"] / 1000000000
}
})
result = {}
_.each(sorted_data, function(item) {
result[item["location"]] = item
})
EOS
end
datasource "ds_google_old_snapshots_with_savings" do
run_script $js_google_old_snapshots_with_savings, $ds_google_old_snapshots_with_region, $ds_google_billing_snapshot_pricing, $ds_currency, $param_min_savings
end
script "js_google_old_snapshots_with_savings", type: "javascript" do
parameters "ds_google_old_snapshots_with_region", "ds_google_billing_snapshot_pricing", "ds_currency", "param_min_savings"
result "result"
code <<-'EOS'
savings_list = _.map(ds_google_old_snapshots_with_region, function(snapshot) {
price_data = ds_google_billing_snapshot_pricing["default"]
if (typeof(snapshot['region']) == 'string') {
if (ds_google_billing_snapshot_pricing[snapshot['region']] != undefined) {
price_data = ds_google_billing_snapshot_pricing[snapshot['region']]
}
}
savings = 0.00
if (snapshot['size'] > price_data['startUsageAmountGiB']) {
savings = price_data['pricePerGiB'] * snapshot['size'] * ds_currency['exchange_rate']
}
return {
architecture: snapshot['architecture'],
size: snapshot['size'],
resourceID: snapshot['resourceID'],
kind: snapshot['kind'],
resourceName: snapshot['resourceName'],
selfLink: snapshot['selfLink'],
snapshotType: snapshot['snapshotType'],
sourceDisk: snapshot['sourceDisk'],
sourceDiskId: snapshot['sourceDiskId'],
status: snapshot['status'],
accountID: snapshot['accountID'],
accountName: snapshot['accountName'],
projectNumber: snapshot['projectNumber'],
policy_name: snapshot['policy_name'],
createdAt: snapshot['createdAt'],
tags: snapshot['labels'],
lookbackPeriod: snapshot['lookbackPeriod'],
recommendationDetails: snapshot['recommendationDetails'],
age: snapshot['age'],
service: snapshot['service'],
message: snapshot['message'],
region: snapshot['region'],
savings: Math.round(savings * 1000) / 1000,
savings_unrounded: savings,
savingsCurrency: ds_currency['symbol'],
type: 'Snapshot',
region: 'global',
total_savings: ""
}
})
result = _.filter(savings_list, function(snapshot) {
return snapshot["savings_unrounded"] >= param_min_savings
})
EOS
end
datasource "ds_google_old_snapshots_incident" do
run_script $js_google_old_snapshots_incident, $ds_google_snapshots_label_filtered, $ds_google_old_snapshots_with_savings, $ds_applied_policy, $ds_currency, $param_snapshot_age
end
script "js_google_old_snapshots_incident", type: "javascript" do
parameters "ds_google_snapshots_label_filtered", "ds_google_old_snapshots_with_savings", "ds_applied_policy", "ds_currency", "param_snapshot_age"
result "result"
code <<-'EOS'
// Function for formatting currency numbers later
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
}
// [].concat is to make sure we genuinely create a new list
result = [].concat(ds_google_old_snapshots_with_savings)
// Message for incident output
total_snapshots = ds_google_snapshots_label_filtered.length.toString()
total_old_snapshots = result.length.toString()
old_snapshots_percentage = (total_old_snapshots / total_snapshots * 100).toFixed(2).toString() + '%'
days_noun = "days"
if (param_snapshot_age == 1) { days_noun = "day" }
findings = [
"Out of ", total_snapshots, " snapshots analyzed, ",
total_old_snapshots, " (", old_snapshots_percentage,
") are older than ", param_snapshot_age, " ", days_noun, " ",
"and are recommended for deletion.\n\n"
].join('')
disclaimer = "The above settings can be modified by editing the applied policy and changing the appropriate parameters.\n\n"
savings_disclaimer = "Savings values are estimated via best guess using data from the source disk where available and the Google Cloud Billing API."
savings_list = _.pluck(result, 'savings_unrounded')
total_savings = _.reduce(savings_list, function(memo, num) { return memo + num; }, 0)
savings_message = [
ds_currency['symbol'], ' ',
formatNumber(parseFloat(total_savings).toFixed(2), ds_currency['t_separator'])
].join('')
result = _.sortBy(result, 'resourceName')
result = _.sortBy(result, 'accountID')
// Dummy item to ensure that the check statement in the policy executes at least once
result.push({
resourceID: "",
message: "",
labels: "",
age: "",
total_savings: ""
})
result[0]['message'] = findings + disclaimer + savings_disclaimer
result[0]['total_savings'] = savings_message
EOS
end
###############################################################################
# Policy
###############################################################################
policy "pol_old_snapshots" do
validate_each $ds_google_old_snapshots_incident do
summary_template "{{ with index data 0 }}{{ .policy_name }}{{ end }}: {{ len data }} Google Old Snapshots Found"
detail_template <<-'EOS'
**Potential Monthly Savings:** {{ with index data 0 }}{{ .total_savings }}{{ end }}
{{ with index data 0 }}{{ .message }}{{ end }}
EOS
check logic_or($ds_parent_policy_terminated, eq(val(item, "resourceID"), ""))
escalate $esc_email
escalate $esc_delete_snapshots
hash_exclude "message", "tags", "age", "savings", "savingsCurrency"
export do
resource_level true
field "accountID" do
label "Project ID"
end
field "accountName" do
label "Project Name"
end
field "projectNumber" do
label "Project Number"
end
field "resourceID" do
label "Resource ID"
end
field "resourceName" do
label "Resource Name"
end
field "tags" do
label "Resource Labels"
end
field "createdAt" do
label "Date/Time Created"
end
field "age" do
label "Age (Days)"
end
field "size" do