-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathcurrency_conversion.pt
500 lines (426 loc) · 15.9 KB
/
currency_conversion.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
name "Currency Conversion"
rs_pt_ver 20180301
type "policy"
short_description "A policy that creates an adjustment rule that converts the currency of the cost of the Cloud Vendor of choice. It utilizes xe.com to retrieve the latest exchange rates. See the [README](https://github.com/flexera-public/policy_templates/tree/master/cost/flexera/cco/currency_conversion/) and [docs.flexera.com/flexera/EN/Automation](https://docs.flexera.com/flexera/EN/Automation/AutomationGS.htm) to learn more."
long_description ""
severity "low"
default_frequency "monthly"
category "Cost"
info(
version: "5.0.1",
provider: "Flexera",
service: "Cloud Cost Optimization",
policy_set: "Cloud Cost Optimization",
hide_skip_approvals: "true"
)
###############################################################################
# Parameters
###############################################################################
parameter "param_dimensions" do
type "list"
category "Policy Settings"
label "Dimensions"
description "The Flexera CCO cost dimension names/ids and values to apply the currency conversion to in 'Dimension=Value' format. Example: Cloud Vendor=AWS"
allowed_pattern /.+=.+/
min_length 1
# No default value, user input required
end
parameter "param_dimensions_boolean" do
type "string"
category "Policy Settings"
label "Dimensions Boolean"
description "Whether to apply the currency conversion to costs that match any of the criteria in the 'Dimensions' parameter or only those that match all of them. Only applicable if more than one value is specified for the 'Dimensions' parameter."
allowed_values "Any", "All"
default "All"
end
parameter "param_backfill" do
type "string"
category "Policy Settings"
label "Backfill Adjustments"
description "Whether to add/modify currency conversion to just the current month or to backfill previous months."
allowed_values "Current Month", "Backfill Previous Months"
default "Current Month"
end
parameter "param_backfill_start_date" do
type "string"
category "Policy Settings"
label "Backfill Start Date"
description "The month and year in YYYY-MM format to backfill adjustments to. Only applicable if \"Backfill Previous Months\" is selected."
default ""
end
parameter "param_backfill_exchange_rate" do
type "string"
category "Policy Settings"
label "Backfill Exchange Rates"
description "Whether or not to use the current exchange rate, or the exchange rate at the time, when applying currency conversion to previous months. Only applicable if \"Backfill Previous Months\" is selected."
allowed_values "Current Exchange Rate", "Backdated Exchange Rate"
default "Backdated Exchange Rate"
end
parameter "param_currency_from" do
type "string"
category "Currency"
label "Currency From"
description "Currency you want to convert from (based on ISO 4217 codes - e.g. 'USD' for US Dollar)"
default "USD"
end
parameter "param_currency_to" do
type "string"
category "Currency"
label "Currency To"
description "Currency you want to convert to (based on ISO 4217 codes - e.g. 'EUR' for Euro)"
default "USD"
end
parameter "param_set_org_currency" do
type "string"
category "Currency"
label "Set Organization Currency"
description "Whether or not to configure the Flexera CCO user interface to present costs in the currency specified in the \"Currency To\" parameter. See README for more information."
allowed_values "Yes", "No"
default "No"
end
###############################################################################
# Authentication
###############################################################################
credentials "auth_flexera" do
schemes "oauth2"
label "Flexera"
description "Select Flexera One OAuth2 credentials"
tags "provider=flexera"
end
###############################################################################
# Datasources & Scripts
###############################################################################
# Find dimension in the CCO platform based on user input
datasource "ds_dimensions" do
request do
auth $auth_flexera
host rs_optima_host
path join(["/bill-analysis/orgs/", rs_org_id, "/costs/dimensions"])
header "Api-Version", "0.1"
header "User-Agent", "RS Policies"
end
result do
encoding "json"
collect jmes_path(response, "dimensions[].{id: id, name: name, type:type}") do
field "id", jmes_path(col_item, "id")
field "name", jmes_path(col_item, "name")
field "type", jmes_path(col_item, "type")
end
end
end
datasource "ds_filter_dimensions" do
run_script $js_filter_dimensions, $ds_dimensions, $param_dimensions
end
script "js_filter_dimensions", type: "javascript" do
parameters "ds_dimensions", "param_dimensions"
result "result"
code <<-'EOS'
result = _.map(param_dimensions, function(item) {
key = item.split('=')[0]
value = item.split('=')[1]
dimension = _.find(ds_dimensions, function(dimension) {
return dimension['id'] == key || dimension['name'] == key
})
if (dimension) {
return {
id: dimension['id'],
name: dimension['name'],
type: dimension['type'],
value: value
}
} else {
return null
}
})
result = _.compact(result)
EOS
end
# Branching Logic: Whether or not to set the organization currency
datasource "ds_set_org_currency_logic" do
run_script $js_set_org_currency_logic, $param_set_org_currency, $param_currency_to
end
script "js_set_org_currency_logic", type: "javascript" do
parameters "param_set_org_currency", "param_currency_to"
result "result"
code <<-'EOS'
result = []
if (param_set_org_currency == "Yes") { result = [{ currency_code: param_currency_to }] }
EOS
end
datasource "ds_set_org_currency" do
iterate $ds_set_org_currency_logic
request do
auth $auth_flexera
verb "PUT"
host rs_optima_host
path join(["/bill-analysis/orgs/", rs_org_id, "/settings/currency_code"])
header "Api-Version", "1.0"
header "User-Agent", "RS Policies"
body_field "value", val(iter_item, "currency_code")
end
end
# Create a list of months in YYYY-MM format that we need to apply adjustments for
datasource "ds_month_list" do
run_script $js_month_list, $param_backfill, $param_backfill_start_date
end
script "js_month_list", type: "javascript" do
parameters "param_backfill", "param_backfill_start_date"
result "result"
code <<-'EOS'
// Function to take YYYY-MM formatted date and move it backwards or forwards by month
function move_month(date_string, amount) {
year = Number(date_string.split('-')[0])
month = Number(date_string.split('-')[1])
if (amount > 0) {
for (var i = 1; i <= amount; i++) {
if (month == 12) {
year += 1
month = 1
} else {
month += 1
}
}
}
if (amount < 0) {
for (var i = -1; i >= amount; i--) {
if (month == 1) {
year -= 1
month = 12
} else {
month -= 1
}
}
}
if (month < 10) { month = '0' + month }
return [year, month].join('-')
}
result = []
current_date_parts = new Date().toISOString().split('-')
current_date = [current_date_parts[0], current_date_parts[1]].join('-')
if (param_backfill == "Backfill Previous Months" && param_backfill_start_date != '') {
iterating_date = param_backfill_start_date
while (iterating_date != current_date) {
result.push({
previous: move_month(iterating_date, -1),
current: iterating_date
})
iterating_date = move_month(iterating_date, 1)
}
}
result.push({
previous: move_month(current_date, -1),
current: current_date
})
EOS
end
datasource "ds_year_list_for_xe" do
run_script $js_year_list_for_xe, $ds_month_list
end
script "js_year_list_for_xe", type: "javascript" do
parameters "ds_month_list"
result "result"
code <<-'EOS'
dates = _.uniq(_.pluck(ds_month_list, 'previous').concat(_.pluck(ds_month_list, 'current')))
years = _.map(dates, function(date) { return date.split('-')[0] })
result = _.uniq(years).sort()
EOS
end
# Gather exchange rates for each year
datasource "ds_xe_exchange_rates" do
iterate $ds_year_list_for_xe
request do
host "api.xe-auth.flexeraeng.com"
path "/prod/{proxy+}"
query "from", $param_currency_from
query "to", $param_currency_to
query "amount", "1"
query "year", iter_item
end
result do
encoding "json"
field "from", jmes_path(response, "from")
field "to", jmes_path(response, "to")
field "year", jmes_path(response, "year")
end
end
# Assemble exchange rates into a simple object that can be used later
datasource "ds_exchange_rates" do
run_script $js_exchange_rates, $ds_xe_exchange_rates, $param_currency_to
end
script "js_exchange_rates", type: "javascript" do
parameters "ds_xe_exchange_rates", "param_currency_to"
result "result"
code <<-'EOS'
result = {}
currency_code = param_currency_to.toUpperCase().trim()
_.each(ds_xe_exchange_rates, function(item) {
year_num = item['year'].toString()
_.each(item['to'][currency_code], function(month) {
month_num = month['month'].toString()
if (month['month'] < 10) { month_num = '0' + month_num }
date = [year_num, month_num].join('-')
result[date] = month['monthlyAverage']
})
})
EOS
end
datasource "ds_current_adjustments" do
request do
auth $auth_flexera
host rs_optima_host
path join(["/bill-analysis/orgs/", rs_org_id, "/adjustments/"])
header "User-Agent", "RS Policies"
end
end
datasource "ds_updated_adjustments" do
run_script $js_updated_adjustments, $ds_exchange_rates, $ds_current_adjustments, $ds_month_list, $ds_filter_dimensions, $param_currency_from, $param_currency_to, $param_backfill_exchange_rate, $param_backfill, $param_backfill_start_date, $param_dimensions_boolean
end
script "js_updated_adjustments", type: "javascript" do
parameters "ds_exchange_rates", "ds_current_adjustments", "ds_month_list", "ds_filter_dimensions", "param_currency_from", "param_currency_to", "param_backfill_exchange_rate", "param_backfill", "param_backfill_start_date", "param_dimensions_boolean"
result "result"
code <<-'EOS'
// Get most recent exchange rate
current_conversion_rate = ds_exchange_rates[ds_month_list[ds_month_list.length - 1]['previous']]
// Create an object containing all of the existing adjustment rule lists by date
existing_adjustment_lists = {}
_.each(ds_current_adjustments['dated_adjustment_lists'], function(list) {
existing_adjustment_lists[list['effective_at']] = list['adjustment_list']
})
// Include any existing rules for months we don't intend to modify
new_adjustments = _.reject(ds_current_adjustments['dated_adjustment_lists'], function(list) {
return _.contains(_.pluck(ds_month_list, 'current'), list['effective_at'])
})
// Dimension details
if (ds_filter_dimensions.length > 1) {
pretty_dimension = param_dimensions_boolean + ": " + _.map(ds_filter_dimensions, function(item) {
return item['name'] + '=' + item['value']
}).join(" | ")
} else {
pretty_dimension = ds_filter_dimensions[0]['name'] + '=' + ds_filter_dimensions[0]['value']
}
new_adj_name = "Currency Conversion - " + pretty_dimension
// Rule information stored for incident
message_rules = []
// Create a new adjustment list for each month
_.each(ds_month_list, function(date) {
// Set the currency conversion rate based on user parameter
conversion_rate = current_conversion_rate
if (param_backfill_exchange_rate == "Backdated Exchange Rate") {
conversion_rate = ds_exchange_rates[date['previous']]
}
// Create the currency conversion rule
if (ds_filter_dimensions.length > 1) {
boolean_type = "or"
if (param_dimensions_boolean == "All") { boolean_type = "and" }
condition = {
type: boolean_type,
expressions: _.map(ds_filter_dimensions, function(item) {
return {
type: "dimension_equals",
dimension: item['id'],
value: item['value']
}
})
}
} else {
condition = {
type: "dimension_equals",
dimension: ds_filter_dimensions[0]['id'],
value: ds_filter_dimensions[0]['value']
}
}
currency_conversion_rule = {
name: new_adj_name,
rules: [
{
condition: condition,
cost_multiplier: conversion_rate - 1,
label: param_currency_from + " to " + param_currency_to
}
]
}
// Store rule information for incident
message_rules.push(date + ": " + conversion_rate.toString())
// Incorporate the new rule into the existing rule set if necessary
adjustment_list = [ currency_conversion_rule ]
existing_list = existing_adjustment_lists[date['current']]
if (existing_list != undefined) {
// Check if a Currency Conversion adjustment rule already exists for current month
adj_name = _.find(existing_list, function(list) {
return list['name'] == new_adj_name
})
// Add CC rule to existing rules while filtering for existing CC rules
adjustment_list = _.filter(existing_list, function(list) {
// Return 'true' for all items if we did not find an existing CC rule
return list['name'] != new_adj_name || adj_name == undefined
})
adjustment_list.push(currency_conversion_rule)
}
// Create the new adjustment list for this month
new_adjustment_list = {
adjustment_list: adjustment_list,
effective_at: date['current']
}
new_adjustments.push(new_adjustment_list)
})
this_month = new Date().toISOString().split('-')[0] + '-' + new Date().toISOString().split('-')[1]
message = "Adjustments applied for " + pretty_dimension + " for month of " + this_month + ".\n\n"
if (param_backfill != 'Current Month' && param_backfill_start_date != '') {
message = "Adjustments applied for " + pretty_dimension + " from month of " + param_backfill_start_date + " to month of " + this_month + ". "
if (param_backfill_exchange_rate == 'Backdated Exchange Rate') {
message += "Backdated exchange rates were used for previous months.\n\n"
} else {
message += "Current exchange rate was used for previous months.\n\n"
}
}
new_adjustments = _.sortBy(new_adjustments, "effective_at")
result = {
list: { dated_adjustment_lists: new_adjustments },
message: message + message_rules.join("\n"),
dimension: pretty_dimension
}
EOS
end
# Include ds_set_org_currency to ensure it executes, not because it's used by this script
datasource "ds_updated_adjustments_payload" do
run_script $js_updated_adjustments_payload, $ds_updated_adjustments, $ds_set_org_currency
end
script "js_updated_adjustments_payload", type: "javascript" do
parameters "ds_updated_adjustments", "ds_set_org_currency"
result "result"
code <<-'EOS'
result = [{
list: JSON.stringify(ds_updated_adjustments['list']),
message: ds_updated_adjustments['message'],
dimension: ds_updated_adjustments['dimension']
}]
EOS
end
# Update adjustment table to include new currency conversion adjustments
datasource "ds_new_adjustments" do
iterate $ds_updated_adjustments_payload
request do
auth $auth_flexera
verb "PUT"
host rs_optima_host
path join(["/bill-analysis/orgs/", rs_org_id, "/adjustments/"])
header "content-type", "application/json"
header "User-Agent", "RS Policies"
body val(iter_item, "list")
end
result do
encoding "json"
field "message", val(iter_item, "message")
field "dimension", val(iter_item, "dimension")
end
end
###############################################################################
# Policy
###############################################################################
policy "pol_currency_conversion" do
validate_each $ds_new_adjustments do
summary_template "Currency Conversion - {{ parameters.param_currency_from }} to {{ parameters.param_currency_to }} - {{ with index data 0 }}{{ .dimension }}{{ end }}"
detail_template "{{ with index data 0 }}{{ .message }}{{ end }}"
check eq(0, 1)
end
end