forked from DataDog/terraform-provider-datadog
/
resource_datadog_dashboard_json.go
245 lines (205 loc) · 7.44 KB
/
resource_datadog_dashboard_json.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
package datadog
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"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/structure"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/Telemetron/terraform-provider-datadog/v3/datadog/internal/utils"
)
var computedFields = []string{"id", "author_handle", "author_name", "created_at", "modified_at", "url"}
const path = "/api/v1/dashboard"
func resourceDatadogDashboardJSON() *schema.Resource {
return &schema.Resource{
Description: "Provides a Datadog dashboard JSON resource. This can be used to create and manage Datadog dashboards using the JSON definition.",
CreateContext: resourceDatadogDashboardJSONCreate,
ReadContext: resourceDatadogDashboardJSONRead,
UpdateContext: resourceDatadogDashboardJSONUpdate,
DeleteContext: resourceDatadogDashboardJSONDelete,
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,
},
Schema: map[string]*schema.Schema{
"dashboard": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsJSON,
StateFunc: func(v interface{}) string {
// Remove computed fields when comparing diffs
attrMap, _ := structure.ExpandJsonFromString(v.(string))
for _, f := range computedFields {
delete(attrMap, f)
}
// Remove every widget id too
if widgets, ok := attrMap["widgets"].([]interface{}); ok {
deleteWidgetID(widgets)
}
res, _ := structure.FlattenJsonToString(attrMap)
return res
},
Description: "The JSON formatted definition of the Dashboard.",
},
"url": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The URL of the dashboard.",
},
"dashboard_lists": {
Type: schema.TypeSet,
Optional: true,
Description: "The list of dashboard lists this dashboard belongs to.",
Elem: &schema.Schema{Type: schema.TypeInt},
},
"dashboard_lists_removed": {
Type: schema.TypeSet,
Computed: true,
Description: "The list of dashboard lists this dashboard should be removed from. Internal only.",
Elem: &schema.Schema{Type: schema.TypeInt},
},
},
}
}
func deleteWidgetID(widgets []interface{}) {
for _, w := range widgets {
widget := w.(map[string]interface{})
def := widget["definition"].(map[string]interface{})
if def["type"] == "group" {
deleteWidgetID(def["widgets"].([]interface{}))
}
delete(widget, "id")
}
}
func resourceDatadogDashboardJSONRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
datadogClientV1 := providerConf.DatadogClientV1
authV1 := providerConf.AuthV1
id := d.Id()
respByte, httpResp, err := utils.SendRequest(authV1, datadogClientV1, "GET", path+"/"+id, nil)
if err != nil {
if httpResp != nil && httpResp.StatusCode == 404 {
d.SetId("")
return nil
}
return diag.FromErr(err)
}
respMap, err := utils.ConvertResponseByteToMap(respByte)
if err != nil {
return diag.FromErr(err)
}
return updateDashboardJSONState(d, respMap)
}
func resourceDatadogDashboardJSONCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
datadogClientV1 := providerConf.DatadogClientV1
authV1 := providerConf.AuthV1
dashboard := d.Get("dashboard").(string)
respByte, httpresp, err := utils.SendRequest(authV1, datadogClientV1, "POST", path, &dashboard)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpresp, "error creating resource")
}
respMap, err := utils.ConvertResponseByteToMap(respByte)
if err != nil {
return diag.FromErr(err)
}
id, ok := respMap["id"]
if !ok {
return diag.FromErr(errors.New("error retrieving id from response"))
}
d.SetId(id.(string))
layoutType, ok := respMap["layout_type"]
if !ok {
return diag.FromErr(errors.New("error retrieving layout_type from response"))
}
var httpResponse *http.Response
err = resource.RetryContext(ctx, d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
_, httpResponse, err = utils.SendRequest(authV1, datadogClientV1, "GET", path+"/"+id.(string), nil)
if err != nil {
if httpResponse != nil && httpResponse.StatusCode == 404 {
return resource.RetryableError(fmt.Errorf("dashboard not created yet"))
}
return resource.NonRetryableError(err)
}
// We only log the error, as failing to update the list shouldn't fail dashboard creation
// Method imported from dashboard resource
updateDashboardLists(d, providerConf, id.(string), layoutType.(string))
return nil
})
if err != nil {
return diag.FromErr(err)
}
return updateDashboardJSONState(d, respMap)
}
func resourceDatadogDashboardJSONUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
datadogClientV1 := providerConf.DatadogClientV1
authV1 := providerConf.AuthV1
dashboard := d.Get("dashboard").(string)
id := d.Id()
respByte, httpresp, err := utils.SendRequest(authV1, datadogClientV1, "PUT", path+"/"+id, &dashboard)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpresp, "error updating dashboard")
}
respMap, err := utils.ConvertResponseByteToMap(respByte)
if err != nil {
return diag.FromErr(err)
}
layoutType, ok := respMap["layout_type"]
if !ok {
return diag.FromErr(errors.New("error retrieving layout_type from response"))
}
// Method imported from dashboard resource
updateDashboardLists(d, providerConf, id, layoutType.(string))
return updateDashboardJSONState(d, respMap)
}
func resourceDatadogDashboardJSONDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
datadogClientV1 := providerConf.DatadogClientV1
authV1 := providerConf.AuthV1
id := d.Id()
_, httpresp, err := utils.SendRequest(authV1, datadogClientV1, "DELETE", path+"/"+id, nil)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpresp, "error deleting dashboard")
}
return nil
}
func updateDashboardJSONState(d *schema.ResourceData, dashboard map[string]interface{}) diag.Diagnostics {
if v, ok := dashboard["url"]; ok {
if err := d.Set("url", v.(string)); err != nil {
return diag.FromErr(err)
}
}
// Remove computed fields from the object
for _, f := range computedFields {
delete(dashboard, f)
}
// Remove every widget id too
deleteWidgetID(dashboard["widgets"].([]interface{}))
dashboardString, err := structure.FlattenJsonToString(dashboard)
if err != nil {
return diag.FromErr(err)
}
if err = d.Set("dashboard", dashboardString); err != nil {
return diag.FromErr(err)
}
return nil
}