-
Notifications
You must be signed in to change notification settings - Fork 393
/
Copy pathresource_datadog_dashboard.go
11098 lines (10512 loc) · 419 KB
/
resource_datadog_dashboard.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
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
package datadog
import (
"context"
"fmt"
"log"
"net/http"
"github.com/terraform-providers/terraform-provider-datadog/datadog/internal/utils"
"github.com/terraform-providers/terraform-provider-datadog/datadog/internal/validators"
"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
"github.com/DataDog/datadog-api-client-go/v2/api/datadogV1"
"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceDatadogDashboard() *schema.Resource {
return &schema.Resource{
Description: "Provides a Datadog dashboard resource. This can be used to create and manage Datadog dashboards.\n\n!> The `is_read_only` field is deprecated and non-functional. Use `restricted_roles` instead to define which roles are required to edit the dashboard.",
CreateContext: resourceDatadogDashboardCreate,
UpdateContext: resourceDatadogDashboardUpdate,
ReadContext: resourceDatadogDashboardRead,
DeleteContext: resourceDatadogDashboardDelete,
CustomizeDiff: func(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error {
oldValue, newValue := diff.GetChange("dashboard_lists")
if !oldValue.(*schema.Set).Equal(newValue.(*schema.Set)) {
// Only calculate removed when the list change, to no create useless diffs
removed := oldValue.(*schema.Set).Difference(newValue.(*schema.Set))
if err := diff.SetNew("dashboard_lists_removed", removed); err != nil {
return err
}
} else {
if err := diff.Clear("dashboard_lists_removed"); err != nil {
return err
}
}
return nil
},
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
SchemaFunc: func() map[string]*schema.Schema {
return map[string]*schema.Schema{
"title": {
Type: schema.TypeString,
Required: true,
Description: "The title of the dashboard.",
},
"widget": {
Type: schema.TypeList,
Optional: true,
Description: "The list of widgets to display on the dashboard.",
Elem: &schema.Resource{
Schema: getWidgetSchema(),
},
},
"layout_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The layout type of the dashboard.",
ValidateDiagFunc: validators.ValidateEnumValue(datadogV1.NewDashboardLayoutTypeFromValue),
},
"reflow_type": {
Type: schema.TypeString,
Optional: true,
Description: "The reflow type of a new dashboard layout. Set this only when layout type is `ordered`. If set to `fixed`, the dashboard expects all widgets to have a layout, and if it's set to `auto`, widgets should not have layouts.",
ValidateDiagFunc: validators.ValidateEnumValue(datadogV1.NewDashboardReflowTypeFromValue),
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: "The description of the dashboard.",
},
"url": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The URL of the dashboard.",
DiffSuppressFunc: func(_, _, _ string, _ *schema.ResourceData) bool {
// This value is computed and cannot be updated.
// To maintain backward compatibility, always suppress diff rather
// than converting the attribute to `Computed` only
return true
},
},
"restricted_roles": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
ConflictsWith: []string{"is_read_only"},
Description: "UUIDs of roles whose associated users are authorized to edit the dashboard.",
},
"template_variable": {
Type: schema.TypeList,
Optional: true,
Description: "The list of template variables for this dashboard.",
Elem: &schema.Resource{
Schema: getTemplateVariableSchema(),
},
},
"template_variable_preset": {
Type: schema.TypeList,
Optional: true,
Description: "The list of selectable template variable presets for this dashboard.",
Elem: &schema.Resource{
Schema: getTemplateVariablePresetSchema(),
},
},
"notify_list": {
Type: schema.TypeSet,
Optional: true,
Description: "The list of handles for the users to notify when changes are made to this dashboard.",
Elem: &schema.Schema{Type: schema.TypeString},
},
"dashboard_lists": {
Type: schema.TypeSet,
Optional: true,
Description: "A list of dashboard lists this dashboard belongs to. This attribute should not be set if managing the corresponding dashboard lists using Terraform as it causes inconsistent behavior.",
Elem: &schema.Schema{Type: schema.TypeInt},
},
"dashboard_lists_removed": {
Type: schema.TypeSet,
Computed: true,
Description: "A list of dashboard lists this dashboard should be removed from. Internal only.",
Elem: &schema.Schema{Type: schema.TypeInt},
},
"is_read_only": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ConflictsWith: []string{"restricted_roles"},
Description: "Whether this dashboard is read-only.",
Deprecated: "This field is deprecated and non-functional. Use `restricted_roles` instead to define which roles are required to edit the dashboard.",
},
"tags": {
Type: schema.TypeList,
Optional: true,
MaxItems: 5,
Description: "A list of tags assigned to the Dashboard. Only team names of the form `team:<name>` are supported.",
Elem: &schema.Schema{Type: schema.TypeString},
},
}
},
}
}
func resourceDatadogDashboardCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
dashboardPayload, err := buildDatadogDashboard(d)
if err != nil {
return diag.Errorf("failed to parse resource configuration: %s", err.Error())
}
dashboard, httpresp, err := apiInstances.GetDashboardsApiV1().CreateDashboard(auth, *dashboardPayload)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpresp, "error creating dashboard")
}
if err := utils.CheckForUnparsed(dashboard); err != nil {
return diag.FromErr(err)
}
d.SetId(*dashboard.Id)
var getDashboard datadogV1.Dashboard
var httpResponse *http.Response
err = retry.RetryContext(ctx, d.Timeout(schema.TimeoutCreate), func() *retry.RetryError {
getDashboard, httpResponse, err = apiInstances.GetDashboardsApiV1().GetDashboard(auth, *dashboard.Id)
if err != nil {
if httpResponse != nil && httpResponse.StatusCode == 404 {
return retry.RetryableError(fmt.Errorf("dashboard not created yet"))
}
return retry.NonRetryableError(err)
}
if err := utils.CheckForUnparsed(getDashboard); err != nil {
return retry.NonRetryableError(err)
}
// We only log the error, as failing to update the list shouldn't fail dashboard creation
updateDashboardLists(d, providerConf, *dashboard.Id, d.Get("layout_type").(string))
return nil
})
if err != nil {
return diag.FromErr(err)
}
return updateDashboardState(d, &getDashboard)
}
func resourceDatadogDashboardUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
id := d.Id()
dashboard, err := buildDatadogDashboard(d)
if err != nil {
return diag.Errorf("failed to parse resource configuration: %s", err.Error())
}
updatedDashboard, httpresp, err := apiInstances.GetDashboardsApiV1().UpdateDashboard(auth, id, *dashboard)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpresp, "error updating dashboard")
}
if err := utils.CheckForUnparsed(updatedDashboard); err != nil {
return diag.FromErr(err)
}
updateDashboardLists(d, providerConf, *dashboard.Id, d.Get("layout_type").(string))
return updateDashboardState(d, &updatedDashboard)
}
func updateDashboardLists(d *schema.ResourceData, providerConf *ProviderConfiguration, dashboardID string, layoutType string) {
dashTypeString := "custom_screenboard"
if layoutType == "ordered" {
dashTypeString = "custom_timeboard"
}
dashType := datadogV2.DashboardType(dashTypeString)
itemsRequest := []datadogV2.DashboardListItemRequest{*datadogV2.NewDashboardListItemRequest(dashboardID, dashType)}
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
if v, ok := d.GetOk("dashboard_lists"); ok && v.(*schema.Set).Len() > 0 {
items := datadogV2.NewDashboardListAddItemsRequest()
items.SetDashboards(itemsRequest)
for _, id := range v.(*schema.Set).List() {
_, _, err := apiInstances.GetDashboardListsApiV2().CreateDashboardListItems(auth, int64(id.(int)), *items)
if err != nil {
log.Printf("[DEBUG] Got error adding to dashboard list %d: %v", id.(int), err)
}
}
}
if v, ok := d.GetOk("dashboard_lists_removed"); ok && v.(*schema.Set).Len() > 0 {
items := datadogV2.NewDashboardListDeleteItemsRequest()
items.SetDashboards(itemsRequest)
for _, id := range v.(*schema.Set).List() {
_, _, err := apiInstances.GetDashboardListsApiV2().DeleteDashboardListItems(auth, int64(id.(int)), *items)
if err != nil {
log.Printf("[DEBUG] Got error removing from dashboard list %d: %v", id.(int), err)
}
}
}
}
func updateDashboardState(d *schema.ResourceData, dashboard *datadogV1.Dashboard) diag.Diagnostics {
if err := d.Set("title", dashboard.GetTitle()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("layout_type", dashboard.GetLayoutType()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("reflow_type", dashboard.GetReflowType()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("description", dashboard.GetDescription()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("url", dashboard.GetUrl()); err != nil {
return diag.FromErr(err)
}
// Set RBAC role settings
if err := d.Set("is_read_only", dashboard.GetIsReadOnly()); err != nil {
return diag.FromErr(err)
}
restrictedRoles := buildTerraformRestrictedRoles(&dashboard.RestrictedRoles)
if err := d.Set("restricted_roles", restrictedRoles); err != nil {
return diag.FromErr(err)
}
// Set widgets
terraformWidgets, err := buildTerraformWidgets(&dashboard.Widgets, d)
if err != nil {
return diag.FromErr(err)
}
if err := d.Set("widget", terraformWidgets); err != nil {
return diag.FromErr(err)
}
// Set template variables
templateVariables := buildTerraformTemplateVariables(&dashboard.TemplateVariables)
if err := d.Set("template_variable", templateVariables); err != nil {
return diag.FromErr(err)
}
// Set template variable presets
templateVariablePresets := buildTerraformTemplateVariablePresets(&dashboard.TemplateVariablePresets)
if err := d.Set("template_variable_preset", templateVariablePresets); err != nil {
return diag.FromErr(err)
}
// Set notify list
notifyList := buildTerraformNotifyList(dashboard.NotifyList.Get())
if err := d.Set("notify_list", notifyList); err != nil {
return diag.FromErr(err)
}
// Set tags
tags := dashboard.GetTags()
if err := d.Set("tags", tags); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceDatadogDashboardRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
id := d.Id()
dashboard, httpresp, err := apiInstances.GetDashboardsApiV1().GetDashboard(auth, id)
if err != nil {
if httpresp != nil && httpresp.StatusCode == 404 {
d.SetId("")
return nil
}
return utils.TranslateClientErrorDiag(err, httpresp, "error getting dashboard")
}
if err := utils.CheckForUnparsed(dashboard); err != nil {
return diag.FromErr(err)
}
return updateDashboardState(d, &dashboard)
}
func resourceDatadogDashboardDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
id := d.Id()
if _, httpresp, err := apiInstances.GetDashboardsApiV1().DeleteDashboard(auth, id); err != nil {
return utils.TranslateClientErrorDiag(err, httpresp, "error deleting dashboard")
}
return nil
}
func buildDatadogDashboard(d *schema.ResourceData) (*datadogV1.Dashboard, error) {
var dashboard datadogV1.Dashboard
dashboard.SetId(d.Id())
if v, ok := d.GetOk("title"); ok {
dashboard.SetTitle(v.(string))
}
if v, ok := d.GetOk("layout_type"); ok {
dashboard.SetLayoutType(datadogV1.DashboardLayoutType(v.(string)))
}
if v, ok := d.GetOk("reflow_type"); ok {
dashboard.SetReflowType(datadogV1.DashboardReflowType(v.(string)))
}
if v, ok := d.GetOk("description"); ok {
dashboard.SetDescription(v.(string))
}
if v, ok := d.GetOk("is_read_only"); ok {
dashboard.SetIsReadOnly(v.(bool))
}
if v, ok := d.GetOk("restricted_roles"); ok && !dashboard.GetIsReadOnly() {
// do not set when 'is_read_only = true' because this takes priority on requests
dashboard.RestrictedRoles = *buildDatadogRestrictedRoles(v.(*schema.Set))
}
// Build Widgets
terraformWidgets := d.Get("widget").([]interface{})
datadogWidgets, err := buildDatadogWidgets(&terraformWidgets)
if err != nil {
return nil, err
}
dashboard.SetWidgets(*datadogWidgets)
// Build NotifyList
notifyList := d.Get("notify_list").(*schema.Set)
dashboard.SetNotifyList(*buildDatadogNotifyList(notifyList))
// Build Tags
tags := utils.GetStringSlice(d, "tags")
dashboard.SetTags(tags)
// Build TemplateVariables
templateVariables := d.Get("template_variable").([]interface{})
dashboard.TemplateVariables = *buildDatadogTemplateVariables(&templateVariables)
// Build TemplateVariablePresets
templateVariablePresets := d.Get("template_variable_preset").([]interface{})
dashboard.TemplateVariablePresets = *buildDatadogTemplateVariablePresets(&templateVariablePresets)
return &dashboard, nil
}
//
// Template Variable helpers
//
func getPpkTemplateVariableSchema() map[string]*schema.Schema {
return map[string]*schema.Schema{
"controlled_externally": {
Type: schema.TypeList,
Optional: true,
Description: "Template variables controlled by the external resource, such as the dashboard this powerpack is on.",
Elem: &schema.Resource{
Schema: getPpkTemplateVariableContentSchema(),
},
},
"controlled_by_powerpack": {
Type: schema.TypeList,
Optional: true,
Description: "Template variables controlled at the powerpack level.",
Elem: &schema.Resource{
Schema: getPpkTemplateVariableContentSchema(),
},
},
}
}
func getPpkTemplateVariableContentSchema() map[string]*schema.Schema {
return map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the variable.",
},
"prefix": {
Type: schema.TypeString,
Optional: true,
Description: "The tag prefix associated with the variable. Only tags with this prefix appear in the variable dropdown.",
},
"values": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringIsNotEmpty,
},
Description: "One or many template variable values within the saved view, which will be unioned together using `OR` if more than one is specified.",
},
}
}
func getTemplateVariableSchema() map[string]*schema.Schema {
return map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the variable.",
},
"prefix": {
Type: schema.TypeString,
Optional: true,
Description: "The tag prefix associated with the variable. Only tags with this prefix appear in the variable dropdown.",
},
"default": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Use `defaults` instead.",
Description: "The default value for the template variable on dashboard load. Cannot be used in conjunction with `defaults`.",
},
"defaults": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringIsNotEmpty,
},
Description: "One or many default values for template variables on load. If more than one default is specified, they will be unioned together with `OR`. Cannot be used in conjunction with `default`.",
},
"available_values": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: "The list of values that the template variable drop-down is be limited to",
},
}
}
func buildDatadogPowerpackTVarContents(contents []interface{}) []datadogV1.PowerpackTemplateVariableContents {
tVarContents := make([]datadogV1.PowerpackTemplateVariableContents, len(contents))
for ind, tvp := range contents {
typecastTvp := tvp.(map[string]interface{})
tvar := datadogV1.NewPowerpackTemplateVariableContentsWithDefaults()
if name, ok := typecastTvp["name"].(string); ok {
tvar.SetName(name)
}
if v, ok := typecastTvp["values"].([]interface{}); ok && len(v) != 0 {
var values []string
for _, s := range v {
values = append(values, s.(string))
}
tvar.SetValues(values)
}
if prefix, ok := typecastTvp["prefix"].(string); ok {
tvar.SetPrefix(prefix)
}
tVarContents[ind] = *tvar
}
return tVarContents
}
func buildTerraformPowerpackTVarContents(tVarContents []datadogV1.PowerpackTemplateVariableContents) []map[string]interface{} {
ppkTvarContents := make([]map[string]interface{}, len(tVarContents))
for i, templateVariable := range tVarContents {
terraformTemplateVariable := map[string]interface{}{}
if v, ok := templateVariable.GetNameOk(); ok {
terraformTemplateVariable["name"] = *v
}
if v := templateVariable.GetPrefix(); len(v) > 0 {
terraformTemplateVariable["prefix"] = v
}
if v, ok := templateVariable.GetValuesOk(); ok && len(*v) > 0 {
var tags []string
tags = append(tags, *v...)
terraformTemplateVariable["values"] = tags
}
ppkTvarContents[i] = terraformTemplateVariable
}
return ppkTvarContents
}
func buildDatadogTemplateVariables(terraformTemplateVariables *[]interface{}) *[]datadogV1.DashboardTemplateVariable {
datadogTemplateVariables := make([]datadogV1.DashboardTemplateVariable, len(*terraformTemplateVariables))
for i, ttv := range *terraformTemplateVariables {
if ttv == nil {
continue
}
terraformTemplateVariable := ttv.(map[string]interface{})
var datadogTemplateVariable datadogV1.DashboardTemplateVariable
if v, ok := terraformTemplateVariable["name"].(string); ok && len(v) != 0 {
datadogTemplateVariable.SetName(v)
}
if v, ok := terraformTemplateVariable["prefix"].(string); ok && len(v) != 0 {
datadogTemplateVariable.SetPrefix(v)
}
if v, ok := terraformTemplateVariable["defaults"].([]interface{}); ok && len(v) != 0 {
var defaults []string
for _, s := range v {
defaults = append(defaults, s.(string))
}
datadogTemplateVariable.SetDefaults(defaults)
} else if v, ok := terraformTemplateVariable["default"].(string); ok && len(v) != 0 {
datadogTemplateVariable.SetDefault(v)
}
if v, ok := terraformTemplateVariable["available_values"].([]interface{}); ok && len(v) > 0 {
availableValues := make([]string, len(v))
for i, availableValue := range v {
availableValues[i] = availableValue.(string)
}
datadogTemplateVariable.SetAvailableValues(availableValues)
}
datadogTemplateVariables[i] = datadogTemplateVariable
}
return &datadogTemplateVariables
}
func buildTerraformTemplateVariables(datadogTemplateVariables *[]datadogV1.DashboardTemplateVariable) *[]map[string]interface{} {
terraformTemplateVariables := make([]map[string]interface{}, len(*datadogTemplateVariables))
for i, templateVariable := range *datadogTemplateVariables {
terraformTemplateVariable := map[string]interface{}{}
if v, ok := templateVariable.GetNameOk(); ok {
terraformTemplateVariable["name"] = *v
}
if v := templateVariable.GetPrefix(); len(v) > 0 {
terraformTemplateVariable["prefix"] = v
}
if v, ok := templateVariable.GetDefaultsOk(); ok && len(*v) > 0 {
var tags []string
tags = append(tags, *v...)
terraformTemplateVariable["defaults"] = tags
} else if v, ok := templateVariable.GetDefaultOk(); ok {
terraformTemplateVariable["default"] = *v
}
if v, ok := templateVariable.GetAvailableValuesOk(); ok {
availableValues := make([]string, len(*v))
for i, availableValue := range *v {
availableValues[i] = availableValue
}
terraformTemplateVariable["available_values"] = availableValues
}
terraformTemplateVariables[i] = terraformTemplateVariable
}
return &terraformTemplateVariables
}
//
// Template Variable Preset Helpers
//
func getTemplateVariablePresetSchema() map[string]*schema.Schema {
return map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Description: "The name of the preset.",
},
"template_variable": {
Type: schema.TypeList,
Optional: true,
Description: "The template variable names and assumed values under the given preset",
Elem: &schema.Resource{
Schema: getTemplateVariablePresetValueSchema(),
},
},
}
}
func getTemplateVariablePresetValueSchema() map[string]*schema.Schema {
return map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Description: "The name of the template variable",
Optional: true,
},
"value": {
Type: schema.TypeString,
Description: "The value that should be assumed by the template variable in this preset. Cannot be used in conjunction with `values`.",
Optional: true,
Deprecated: "Use `values` instead.",
},
"values": {
Type: schema.TypeList,
Optional: true,
MinItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringIsNotEmpty,
},
Description: "One or many template variable values within the saved view, which will be unioned together using `OR` if more than one is specified. Cannot be used in conjunction with `value`.",
},
}
}
func buildDatadogTemplateVariablePresets(terraformTemplateVariablePresets *[]interface{}) *[]datadogV1.DashboardTemplateVariablePreset {
datadogTemplateVariablePresets := make([]datadogV1.DashboardTemplateVariablePreset, len(*terraformTemplateVariablePresets))
for i, tvp := range *terraformTemplateVariablePresets {
if tvp == nil {
continue
}
templateVariablePreset := tvp.(map[string]interface{})
var datadogTemplateVariablePreset datadogV1.DashboardTemplateVariablePreset
if v, ok := templateVariablePreset["name"].(string); ok && len(v) != 0 {
datadogTemplateVariablePreset.SetName(v)
}
if templateVariablePresetValues, ok := templateVariablePreset["template_variable"].([]interface{}); ok {
datadogTemplateVariablePresetValues := make([]datadogV1.DashboardTemplateVariablePresetValue, len(templateVariablePresetValues))
for j, tvp := range templateVariablePresetValues {
if tvp == nil {
continue
}
templateVariablePresetValue := tvp.(map[string]interface{})
var datadogTemplateVariablePresetValue datadogV1.DashboardTemplateVariablePresetValue
if w, ok := templateVariablePresetValue["name"].(string); ok && len(w) != 0 {
datadogTemplateVariablePresetValue.SetName(w)
}
if w, ok := templateVariablePresetValue["values"].([]interface{}); ok && len(w) != 0 {
var presets []string
for _, s := range w {
presets = append(presets, s.(string))
}
datadogTemplateVariablePresetValue.SetValues(presets)
} else if w, ok := templateVariablePresetValue["value"].(string); ok && len(w) != 0 {
datadogTemplateVariablePresetValue.SetValue(w)
}
datadogTemplateVariablePresetValues[j] = datadogTemplateVariablePresetValue
}
datadogTemplateVariablePreset.SetTemplateVariables(datadogTemplateVariablePresetValues)
}
datadogTemplateVariablePresets[i] = datadogTemplateVariablePreset
}
return &datadogTemplateVariablePresets
}
func buildTerraformTemplateVariablePresets(datadogTemplateVariablePresets *[]datadogV1.DashboardTemplateVariablePreset) *[]map[string]interface{} {
// Allocate final resting place for tf/hash version
terraformTemplateVariablePresets := make([]map[string]interface{}, len(*datadogTemplateVariablePresets))
//iterate over preset objects
for i, templateVariablePreset := range *datadogTemplateVariablePresets {
// Allocate for this preset group, a map of string key to obj (string for name, array for preset values
terraformTemplateVariablePreset := make(map[string]interface{})
if v, ok := templateVariablePreset.GetNameOk(); ok {
terraformTemplateVariablePreset["name"] = v
}
// allocate for array of preset values (names = name,value, values = name, template variable)
terraformTemplateVariablePresetValues := make([]map[string]interface{}, len(templateVariablePreset.GetTemplateVariables()))
for j, templateVariablePresetValue := range templateVariablePreset.GetTemplateVariables() {
// allocate map for name => name value => value
terraformTemplateVariablePresetValue := make(map[string]interface{})
if v, ok := templateVariablePresetValue.GetNameOk(); ok {
terraformTemplateVariablePresetValue["name"] = *v
}
if v, ok := templateVariablePresetValue.GetValuesOk(); ok && len(*v) > 0 {
var tags []string
tags = append(tags, *v...)
terraformTemplateVariablePresetValue["values"] = tags
} else if v, ok := templateVariablePresetValue.GetValueOk(); ok {
terraformTemplateVariablePresetValue["value"] = *v
}
terraformTemplateVariablePresetValues[j] = terraformTemplateVariablePresetValue
}
// Set template_variable to the array of values we just created
terraformTemplateVariablePreset["template_variable"] = terraformTemplateVariablePresetValues
// put the preset group into the output var
terraformTemplateVariablePresets[i] = terraformTemplateVariablePreset
}
return &terraformTemplateVariablePresets
}
//
// Restricted Roles helpers
//
func buildDatadogRestrictedRoles(terraformRestrictedRoles *schema.Set) *[]string {
roles := make([]string, 0)
for _, r := range terraformRestrictedRoles.List() {
roles = append(roles, r.(string))
}
return &roles
}
func buildTerraformRestrictedRoles(datadogRestrictedRoles *[]string) *[]string {
if datadogRestrictedRoles == nil {
terraformRestrictedRoles := make([]string, 0)
return &terraformRestrictedRoles
}
terraformRestrictedRoles := make([]string, len(*datadogRestrictedRoles))
for i, roleUUID := range *datadogRestrictedRoles {
terraformRestrictedRoles[i] = roleUUID
}
return &terraformRestrictedRoles
}
//
// Notify List helpers
//
func buildDatadogNotifyList(terraformNotifyList *schema.Set) *[]string {
datadogNotifyList := make([]string, len(terraformNotifyList.List()))
for i, authorHandle := range terraformNotifyList.List() {
datadogNotifyList[i] = authorHandle.(string)
}
return &datadogNotifyList
}
func buildTerraformNotifyList(datadogNotifyList *[]string) *[]string {
if datadogNotifyList == nil {
terraformNotifyList := make([]string, 0)
return &terraformNotifyList
}
terraformNotifyList := make([]string, len(*datadogNotifyList))
for i, authorHandle := range *datadogNotifyList {
terraformNotifyList[i] = authorHandle
}
return &terraformNotifyList
}
//
// Widget helpers
//
// The generic widget schema is a combination of the schema for a non-group widget
// and the schema for a Group Widget (which can contains only non-group widgets)
func getWidgetSchema() map[string]*schema.Schema {
widgetSchema := getNonGroupWidgetSchema(false)
widgetSchema["group_definition"] = &schema.Schema{
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Group widget.",
Elem: &schema.Resource{
Schema: getGroupDefinitionSchema(),
},
}
return widgetSchema
}
func getNonGroupWidgetSchema(isPowerpackSchema bool) map[string]*schema.Schema {
s := map[string]*schema.Schema{
"widget_layout": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
Description: "The layout of the widget on a 'free' dashboard.",
Elem: &schema.Resource{
Schema: getWidgetLayoutSchema(),
},
},
"id": {
Type: schema.TypeInt,
Computed: true,
Description: "The ID of the widget.",
},
// A widget should implement exactly one of the following definitions
"alert_graph_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Alert Graph widget.",
Elem: &schema.Resource{
Schema: getAlertGraphDefinitionSchema(),
},
},
"alert_value_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Alert Value widget.",
Elem: &schema.Resource{
Schema: getAlertValueDefinitionSchema(),
},
},
"change_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Change widget.",
Elem: &schema.Resource{
Schema: getChangeDefinitionSchema(),
},
},
"check_status_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Check Status widget.",
Elem: &schema.Resource{
Schema: getCheckStatusDefinitionSchema(),
},
},
"distribution_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Distribution widget.",
Elem: &schema.Resource{
Schema: getDistributionDefinitionSchema(),
},
},
"event_stream_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Event Stream widget.",
Elem: &schema.Resource{
Schema: getEventStreamDefinitionSchema(),
},
},
"event_timeline_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Event Timeline widget.",
Elem: &schema.Resource{
Schema: getEventTimelineDefinitionSchema(),
},
},
"free_text_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Free Text widget.",
Elem: &schema.Resource{
Schema: getFreeTextDefinitionSchema(),
},
},
"heatmap_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Heatmap widget.",
Elem: &schema.Resource{
Schema: getHeatmapDefinitionSchema(),
},
},
"hostmap_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Hostmap widget.",
Elem: &schema.Resource{
Schema: getHostmapDefinitionSchema(),
},
},
"iframe_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for an Iframe widget.",
Elem: &schema.Resource{
Schema: getIframeDefinitionSchema(),
},
},
"image_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for an Image widget",
Elem: &schema.Resource{
Schema: getImageDefinitionSchema(),
},
},
"list_stream_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a List Stream widget.",
Elem: &schema.Resource{
Schema: getListStreamDefinitionSchema(),
},
},
"log_stream_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for an Log Stream widget.",
Elem: &schema.Resource{
Schema: getLogStreamDefinitionSchema(),
},
},
"manage_status_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for an Manage Status widget.",
Elem: &schema.Resource{
Schema: getManageStatusDefinitionSchema(),
},
},
"note_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Note widget.",
Elem: &schema.Resource{
Schema: getNoteDefinitionSchema(),
},
},
"query_value_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Query Value widget.",
Elem: &schema.Resource{
Schema: getQueryValueDefinitionSchema(),
},
},
"query_table_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Query Table widget.",
Elem: &schema.Resource{
Schema: getQueryTableDefinitionSchema(),
},
},
"scatterplot_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Scatterplot widget.",
Elem: &schema.Resource{
Schema: getScatterplotDefinitionSchema(),
},
},
"servicemap_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Service Map widget.",
Elem: &schema.Resource{
Schema: getServiceMapDefinitionSchema(),
},
},
"service_level_objective_definition": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The definition for a Service Level Objective widget.",