-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
resource_aws_budgets_budget.go
646 lines (563 loc) · 19.8 KB
/
resource_aws_budgets_budget.go
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
package aws
import (
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/budgets"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceAwsBudgetsBudget() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"account_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
ValidateFunc: validateAwsAccountId,
},
"name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
},
"name_prefix": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
},
"budget_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(budgets.BudgetType_Values(), false),
},
"limit_amount": {
Type: schema.TypeString,
Required: true,
},
"limit_unit": {
Type: schema.TypeString,
Required: true,
},
"cost_types": {
Type: schema.TypeList,
Computed: true,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"include_credit": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"include_discount": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"include_other_subscription": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"include_recurring": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"include_refund": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"include_subscription": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"include_support": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"include_tax": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"include_upfront": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"use_amortized": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"use_blended": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
},
"time_period_start": {
Type: schema.TypeString,
Required: true,
},
"time_period_end": {
Type: schema.TypeString,
Optional: true,
Default: "2087-06-15_00:00",
},
"time_unit": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(budgets.TimeUnit_Values(), false),
},
"cost_filters": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"notification": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(budgets.ComparisonOperator_Values(), false),
},
"threshold": {
Type: schema.TypeFloat,
Required: true,
},
"threshold_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(budgets.ThresholdType_Values(), false),
},
"notification_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(budgets.NotificationType_Values(), false),
},
"subscriber_email_addresses": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"subscriber_sns_topic_arns": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateArn,
},
},
},
},
},
},
Create: resourceAwsBudgetsBudgetCreate,
Read: resourceAwsBudgetsBudgetRead,
Update: resourceAwsBudgetsBudgetUpdate,
Delete: resourceAwsBudgetsBudgetDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
}
}
func resourceAwsBudgetsBudgetCreate(d *schema.ResourceData, meta interface{}) error {
budget, err := expandBudgetsBudgetUnmarshal(d)
if err != nil {
return fmt.Errorf("failed unmarshalling budget: %v", err)
}
if v, ok := d.GetOk("name"); ok {
budget.BudgetName = aws.String(v.(string))
} else if v, ok := d.GetOk("name_prefix"); ok {
budget.BudgetName = aws.String(resource.PrefixedUniqueId(v.(string)))
} else {
budget.BudgetName = aws.String(resource.UniqueId())
}
conn := meta.(*AWSClient).budgetconn
var accountID string
if v, ok := d.GetOk("account_id"); ok {
accountID = v.(string)
} else {
accountID = meta.(*AWSClient).accountid
}
_, err = conn.CreateBudget(&budgets.CreateBudgetInput{
AccountId: aws.String(accountID),
Budget: budget,
})
if err != nil {
return fmt.Errorf("create budget failed: %v", err)
}
d.SetId(fmt.Sprintf("%s:%s", accountID, aws.StringValue(budget.BudgetName)))
notificationsRaw := d.Get("notification").(*schema.Set).List()
notifications, subscribers := expandBudgetNotificationsUnmarshal(notificationsRaw)
err = resourceAwsBudgetsBudgetNotificationsCreate(notifications, subscribers, *budget.BudgetName, accountID, meta)
if err != nil {
return fmt.Errorf("error creating Budget (%s) Notifications: %s", d.Id(), err)
}
return resourceAwsBudgetsBudgetRead(d, meta)
}
func resourceAwsBudgetsBudgetNotificationsCreate(notifications []*budgets.Notification, subscribers [][]*budgets.Subscriber, budgetName string, accountID string, meta interface{}) error {
conn := meta.(*AWSClient).budgetconn
for i, notification := range notifications {
subscribers := subscribers[i]
if len(subscribers) == 0 {
return fmt.Errorf("Notification must have at least one subscriber!")
}
_, err := conn.CreateNotification(&budgets.CreateNotificationInput{
BudgetName: aws.String(budgetName),
AccountId: aws.String(accountID),
Notification: notification,
Subscribers: subscribers,
})
if err != nil {
return err
}
}
return nil
}
func expandBudgetNotificationsUnmarshal(notificationsRaw []interface{}) ([]*budgets.Notification, [][]*budgets.Subscriber) {
notifications := make([]*budgets.Notification, len(notificationsRaw))
subscribersForNotifications := make([][]*budgets.Subscriber, len(notificationsRaw))
for i, notificationRaw := range notificationsRaw {
notificationRaw := notificationRaw.(map[string]interface{})
comparisonOperator := notificationRaw["comparison_operator"].(string)
threshold := notificationRaw["threshold"].(float64)
thresholdType := notificationRaw["threshold_type"].(string)
notificationType := notificationRaw["notification_type"].(string)
notifications[i] = &budgets.Notification{
ComparisonOperator: aws.String(comparisonOperator),
Threshold: aws.Float64(threshold),
ThresholdType: aws.String(thresholdType),
NotificationType: aws.String(notificationType),
}
emailSubscribers := expandBudgetSubscribers(notificationRaw["subscriber_email_addresses"], budgets.SubscriptionTypeEmail)
snsSubscribers := expandBudgetSubscribers(notificationRaw["subscriber_sns_topic_arns"], budgets.SubscriptionTypeSns)
subscribersForNotifications[i] = append(emailSubscribers, snsSubscribers...)
}
return notifications, subscribersForNotifications
}
func expandBudgetSubscribers(rawList interface{}, subscriptionType string) []*budgets.Subscriber {
result := make([]*budgets.Subscriber, 0)
addrs := expandStringSet(rawList.(*schema.Set))
for _, addr := range addrs {
result = append(result, &budgets.Subscriber{
SubscriptionType: aws.String(subscriptionType),
Address: addr,
})
}
return result
}
func resourceAwsBudgetsBudgetRead(d *schema.ResourceData, meta interface{}) error {
accountID, budgetName, err := decodeBudgetsBudgetID(d.Id())
if err != nil {
return err
}
conn := meta.(*AWSClient).budgetconn
describeBudgetOutput, err := conn.DescribeBudget(&budgets.DescribeBudgetInput{
BudgetName: aws.String(budgetName),
AccountId: aws.String(accountID),
})
if isAWSErr(err, budgets.ErrCodeNotFoundException, "") {
log.Printf("[WARN] Budget %s not found, removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("describe budget failed: %v", err)
}
budget := describeBudgetOutput.Budget
if budget == nil {
log.Printf("[WARN] Budget %s not found, removing from state", d.Id())
d.SetId("")
return nil
}
d.Set("account_id", accountID)
d.Set("budget_type", budget.BudgetType)
if err := d.Set("cost_filters", convertCostFiltersToStringMap(budget.CostFilters)); err != nil {
return fmt.Errorf("error setting cost_filters: %s", err)
}
if err := d.Set("cost_types", flattenBudgetsCostTypes(budget.CostTypes)); err != nil {
return fmt.Errorf("error setting cost_types: %s %s", err, budget.CostTypes)
}
if budget.BudgetLimit != nil {
d.Set("limit_amount", budget.BudgetLimit.Amount)
d.Set("limit_unit", budget.BudgetLimit.Unit)
}
d.Set("name", budget.BudgetName)
if budget.TimePeriod != nil {
d.Set("time_period_end", aws.TimeValue(budget.TimePeriod.End).Format("2006-01-02_15:04"))
d.Set("time_period_start", aws.TimeValue(budget.TimePeriod.Start).Format("2006-01-02_15:04"))
}
d.Set("time_unit", budget.TimeUnit)
arn := arn.ARN{
Partition: meta.(*AWSClient).partition,
Service: "budgetservice",
AccountID: meta.(*AWSClient).accountid,
Resource: fmt.Sprintf("budget/%s", aws.StringValue(budget.BudgetName)),
}
d.Set("arn", arn.String())
return resourceAwsBudgetsBudgetNotificationRead(d, meta)
}
func resourceAwsBudgetsBudgetNotificationRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).budgetconn
accountID, budgetName, err := decodeBudgetsBudgetID(d.Id())
if err != nil {
return fmt.Errorf("error decoding Budget (%s) ID: %s", d.Id(), err)
}
describeNotificationsForBudgetOutput, err := conn.DescribeNotificationsForBudget(&budgets.DescribeNotificationsForBudgetInput{
BudgetName: aws.String(budgetName),
AccountId: aws.String(accountID),
})
if err != nil {
return fmt.Errorf("error describing Budget (%s) Notifications: %s", d.Id(), err)
}
notifications := make([]map[string]interface{}, 0)
for _, notificationOutput := range describeNotificationsForBudgetOutput.Notifications {
notification := make(map[string]interface{})
notification["comparison_operator"] = aws.StringValue(notificationOutput.ComparisonOperator)
notification["threshold"] = aws.Float64Value(notificationOutput.Threshold)
notification["notification_type"] = aws.StringValue(notificationOutput.NotificationType)
if notificationOutput.ThresholdType == nil {
// The AWS API doesn't seem to return a ThresholdType if it's set to PERCENTAGE
// Set it manually to make behavior more predictable
notification["threshold_type"] = budgets.ThresholdTypePercentage
} else {
notification["threshold_type"] = aws.StringValue(notificationOutput.ThresholdType)
}
subscribersOutput, err := conn.DescribeSubscribersForNotification(&budgets.DescribeSubscribersForNotificationInput{
BudgetName: aws.String(budgetName),
AccountId: aws.String(accountID),
Notification: notificationOutput,
})
if err != nil {
return fmt.Errorf("error describing Budget (%s) Notification Subscribers: %s", d.Id(), err)
}
snsSubscribers := make([]interface{}, 0)
emailSubscribers := make([]interface{}, 0)
for _, subscriberOutput := range subscribersOutput.Subscribers {
if aws.StringValue(subscriberOutput.SubscriptionType) == budgets.SubscriptionTypeSns {
snsSubscribers = append(snsSubscribers, *subscriberOutput.Address)
} else if aws.StringValue(subscriberOutput.SubscriptionType) == budgets.SubscriptionTypeEmail {
emailSubscribers = append(emailSubscribers, *subscriberOutput.Address)
}
}
if len(snsSubscribers) > 0 {
notification["subscriber_sns_topic_arns"] = schema.NewSet(schema.HashString, snsSubscribers)
}
if len(emailSubscribers) > 0 {
notification["subscriber_email_addresses"] = schema.NewSet(schema.HashString, emailSubscribers)
}
notifications = append(notifications, notification)
}
if err := d.Set("notification", notifications); err != nil {
return fmt.Errorf("error setting notification: %s %s", err, describeNotificationsForBudgetOutput.Notifications)
}
return nil
}
func resourceAwsBudgetsBudgetUpdate(d *schema.ResourceData, meta interface{}) error {
accountID, _, err := decodeBudgetsBudgetID(d.Id())
if err != nil {
return err
}
conn := meta.(*AWSClient).budgetconn
budget, err := expandBudgetsBudgetUnmarshal(d)
if err != nil {
return fmt.Errorf("could not create budget: %v", err)
}
_, err = conn.UpdateBudget(&budgets.UpdateBudgetInput{
AccountId: aws.String(accountID),
NewBudget: budget,
})
if err != nil {
return fmt.Errorf("update budget failed: %v", err)
}
err = resourceAwsBudgetsBudgetNotificationsUpdate(d, meta)
if err != nil {
return fmt.Errorf("update budget notification failed: %v", err)
}
return resourceAwsBudgetsBudgetRead(d, meta)
}
func resourceAwsBudgetsBudgetNotificationsUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).budgetconn
accountID, budgetName, err := decodeBudgetsBudgetID(d.Id())
if err != nil {
return err
}
if d.HasChange("notification") {
o, n := d.GetChange("notification")
os := o.(*schema.Set)
ns := n.(*schema.Set)
removeNotifications, _ := expandBudgetNotificationsUnmarshal(os.Difference(ns).List())
addNotifications, addSubscribers := expandBudgetNotificationsUnmarshal(ns.Difference(os).List())
for _, notification := range removeNotifications {
input := &budgets.DeleteNotificationInput{
AccountId: aws.String(accountID),
BudgetName: aws.String(budgetName),
Notification: notification,
}
_, err := conn.DeleteNotification(input)
if err != nil {
return fmt.Errorf("error deleting Budget (%s) Notification: %s", d.Id(), err)
}
}
err = resourceAwsBudgetsBudgetNotificationsCreate(addNotifications, addSubscribers, budgetName, accountID, meta)
if err != nil {
return fmt.Errorf("error creating Budget (%s) Notifications: %s", d.Id(), err)
}
}
return nil
}
func resourceAwsBudgetsBudgetDelete(d *schema.ResourceData, meta interface{}) error {
accountID, budgetName, err := decodeBudgetsBudgetID(d.Id())
if err != nil {
return err
}
conn := meta.(*AWSClient).budgetconn
_, err = conn.DeleteBudget(&budgets.DeleteBudgetInput{
BudgetName: aws.String(budgetName),
AccountId: aws.String(accountID),
})
if err != nil {
if isAWSErr(err, budgets.ErrCodeNotFoundException, "") {
log.Printf("[INFO] budget %s could not be found. skipping delete.", d.Id())
return nil
}
return fmt.Errorf("delete budget failed: %v", err)
}
return nil
}
func flattenBudgetsCostTypes(costTypes *budgets.CostTypes) []map[string]interface{} {
if costTypes == nil {
return []map[string]interface{}{}
}
m := map[string]interface{}{
"include_credit": aws.BoolValue(costTypes.IncludeCredit),
"include_discount": aws.BoolValue(costTypes.IncludeDiscount),
"include_other_subscription": aws.BoolValue(costTypes.IncludeOtherSubscription),
"include_recurring": aws.BoolValue(costTypes.IncludeRecurring),
"include_refund": aws.BoolValue(costTypes.IncludeRefund),
"include_subscription": aws.BoolValue(costTypes.IncludeSubscription),
"include_support": aws.BoolValue(costTypes.IncludeSupport),
"include_tax": aws.BoolValue(costTypes.IncludeTax),
"include_upfront": aws.BoolValue(costTypes.IncludeUpfront),
"use_amortized": aws.BoolValue(costTypes.UseAmortized),
"use_blended": aws.BoolValue(costTypes.UseBlended),
}
return []map[string]interface{}{m}
}
func convertCostFiltersToStringMap(costFilters map[string][]*string) map[string]string {
convertedCostFilters := make(map[string]string)
for k, v := range costFilters {
filterValues := make([]string, 0)
for _, singleFilterValue := range v {
filterValues = append(filterValues, *singleFilterValue)
}
convertedCostFilters[k] = strings.Join(filterValues, ",")
}
return convertedCostFilters
}
func expandBudgetsBudgetUnmarshal(d *schema.ResourceData) (*budgets.Budget, error) {
budgetName := d.Get("name").(string)
budgetType := d.Get("budget_type").(string)
budgetLimitAmount := d.Get("limit_amount").(string)
budgetLimitUnit := d.Get("limit_unit").(string)
costTypes := expandBudgetsCostTypesUnmarshal(d.Get("cost_types").([]interface{}))
budgetTimeUnit := d.Get("time_unit").(string)
budgetCostFilters := make(map[string][]*string)
for k, v := range d.Get("cost_filters").(map[string]interface{}) {
filterValue := v.(string)
budgetCostFilters[k] = append(budgetCostFilters[k], aws.String(filterValue))
}
budgetTimePeriodStart, err := time.Parse("2006-01-02_15:04", d.Get("time_period_start").(string))
if err != nil {
return nil, fmt.Errorf("failure parsing time: %v", err)
}
budgetTimePeriodEnd, err := time.Parse("2006-01-02_15:04", d.Get("time_period_end").(string))
if err != nil {
return nil, fmt.Errorf("failure parsing time: %v", err)
}
budget := &budgets.Budget{
BudgetName: aws.String(budgetName),
BudgetType: aws.String(budgetType),
BudgetLimit: &budgets.Spend{
Amount: aws.String(budgetLimitAmount),
Unit: aws.String(budgetLimitUnit),
},
CostTypes: costTypes,
TimePeriod: &budgets.TimePeriod{
End: &budgetTimePeriodEnd,
Start: &budgetTimePeriodStart,
},
TimeUnit: aws.String(budgetTimeUnit),
CostFilters: budgetCostFilters,
}
return budget, nil
}
func decodeBudgetsBudgetID(id string) (string, string, error) {
parts := strings.Split(id, ":")
if len(parts) != 2 {
return "", "", fmt.Errorf("Unexpected format of ID (%q), expected AccountID:BudgetName", id)
}
return parts[0], parts[1], nil
}
func expandBudgetsCostTypesUnmarshal(budgetCostTypes []interface{}) *budgets.CostTypes {
costTypes := &budgets.CostTypes{
IncludeCredit: aws.Bool(true),
IncludeDiscount: aws.Bool(true),
IncludeOtherSubscription: aws.Bool(true),
IncludeRecurring: aws.Bool(true),
IncludeRefund: aws.Bool(true),
IncludeSubscription: aws.Bool(true),
IncludeSupport: aws.Bool(true),
IncludeTax: aws.Bool(true),
IncludeUpfront: aws.Bool(true),
UseAmortized: aws.Bool(false),
UseBlended: aws.Bool(false),
}
if len(budgetCostTypes) == 1 {
costTypesMap := budgetCostTypes[0].(map[string]interface{})
for k, v := range map[string]*bool{
"include_credit": costTypes.IncludeCredit,
"include_discount": costTypes.IncludeDiscount,
"include_other_subscription": costTypes.IncludeOtherSubscription,
"include_recurring": costTypes.IncludeRecurring,
"include_refund": costTypes.IncludeRefund,
"include_subscription": costTypes.IncludeSubscription,
"include_support": costTypes.IncludeSupport,
"include_tax": costTypes.IncludeTax,
"include_upfront": costTypes.IncludeUpfront,
"use_amortized": costTypes.UseAmortized,
"use_blended": costTypes.UseBlended,
} {
if val, ok := costTypesMap[k]; ok {
*v = val.(bool)
}
}
}
return costTypes
}