/
eventgrid_domain_resource.go
429 lines (353 loc) · 13 KB
/
eventgrid_domain_resource.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
package eventgrid
import (
"fmt"
"log"
"time"
"github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid"
"github.com/hashicorp/go-azure-helpers/response"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/eventgrid/parse"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags"
azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func resourceArmEventGridDomain() *schema.Resource {
return &schema.Resource{
Create: resourceArmEventGridDomainCreateUpdate,
Read: resourceArmEventGridDomainRead,
Update: resourceArmEventGridDomainCreateUpdate,
Delete: resourceArmEventGridDomainDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Read: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error {
_, err := parse.EventGridDomainID(id)
return err
}),
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"location": azure.SchemaLocation(),
"resource_group_name": azure.SchemaResourceGroupName(),
"tags": tags.Schema(),
"input_schema": {
Type: schema.TypeString,
Optional: true,
Default: string(eventgrid.InputSchemaEventGridSchema),
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(eventgrid.InputSchemaCloudEventSchemaV10),
string(eventgrid.InputSchemaCustomEventSchema),
string(eventgrid.InputSchemaEventGridSchema),
}, false),
},
"input_mapping_fields": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"topic": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"event_time": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"event_type": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"subject": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"data_version": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
},
},
},
"input_mapping_default_values": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"event_type": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"subject": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"data_version": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
},
},
},
"endpoint": {
Type: schema.TypeString,
Computed: true,
},
"primary_access_key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"secondary_access_key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
},
}
}
func resourceArmEventGridDomainCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).EventGrid.DomainsClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
if features.ShouldResourcesBeImported() && d.IsNewResource() {
existing, err := client.Get(ctx, resourceGroup, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of existing EventGrid Domain %q (Resource Group %q): %s", name, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_eventgrid_domain", *existing.ID)
}
}
location := azure.NormalizeLocation(d.Get("location").(string))
t := d.Get("tags").(map[string]interface{})
domainProperties := &eventgrid.DomainProperties{
InputSchemaMapping: expandAzureRmEventgridDomainInputMapping(d),
InputSchema: eventgrid.InputSchema(d.Get("input_schema").(string)),
}
domain := eventgrid.Domain{
Location: &location,
DomainProperties: domainProperties,
Tags: tags.Expand(t),
}
log.Printf("[INFO] preparing arguments for AzureRM EventGrid Domain creation with Properties: %+v", domain)
future, err := client.CreateOrUpdate(ctx, resourceGroup, name, domain)
if err != nil {
return fmt.Errorf("Error creating/updating EventGrid Domain %q (Resource Group %q): %s", name, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for EventGrid Domain %q (Resource Group %q) to become available: %s", name, resourceGroup, err)
}
read, err := client.Get(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error retrieving EventGrid Domain %q (Resource Group %q): %s", name, resourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read EventGrid Domain %q (resource group %s) ID", name, resourceGroup)
}
d.SetId(*read.ID)
return resourceArmEventGridDomainRead(d, meta)
}
func resourceArmEventGridDomainRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).EventGrid.DomainsClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.EventGridDomainID(d.Id())
if err != nil {
return err
}
resp, err := client.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[WARN] EventGrid Domain %q was not found (Resource Group %q)", id.Name, id.ResourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("Error making Read request on EventGrid Domain %q: %+v", id.Name, err)
}
d.Set("name", resp.Name)
d.Set("resource_group_name", id.ResourceGroup)
if location := resp.Location; location != nil {
d.Set("location", azure.NormalizeLocation(*location))
}
if props := resp.DomainProperties; props != nil {
d.Set("endpoint", props.Endpoint)
d.Set("input_schema", string(props.InputSchema))
inputMappingFields, err := flattenAzureRmEventgridDomainInputMapping(props.InputSchemaMapping)
if err != nil {
return fmt.Errorf("Unable to flatten `input_schema_mapping_fields` for EventGrid Domain %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err)
}
if err := d.Set("input_mapping_fields", inputMappingFields); err != nil {
return fmt.Errorf("Error setting `input_schema_mapping_fields` for EventGrid Domain %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err)
}
inputMappingDefaultValues, err := flattenAzureRmEventgridDomainInputMappingDefaultValues(props.InputSchemaMapping)
if err != nil {
return fmt.Errorf("Unable to flatten `input_schema_mapping_default_values` for EventGrid Domain %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err)
}
if err := d.Set("input_mapping_default_values", inputMappingDefaultValues); err != nil {
return fmt.Errorf("Error setting `input_schema_mapping_fields` for EventGrid Domain %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err)
}
}
keys, err := client.ListSharedAccessKeys(ctx, id.ResourceGroup, id.Name)
if err != nil {
return fmt.Errorf("Error retrieving Shared Access Keys for EventGrid Domain %q: %+v", id.Name, err)
}
d.Set("primary_access_key", keys.Key1)
d.Set("secondary_access_key", keys.Key2)
return tags.FlattenAndSet(d, resp.Tags)
}
func resourceArmEventGridDomainDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).EventGrid.DomainsClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.EventGridDomainID(d.Id())
if err != nil {
return err
}
future, err := client.Delete(ctx, id.ResourceGroup, id.Name)
if err != nil {
if response.WasNotFound(future.Response()) {
return nil
}
return fmt.Errorf("Error deleting Event Grid Domain %q: %+v", id.Name, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
if response.WasNotFound(future.Response()) {
return nil
}
return fmt.Errorf("Error deleting Event Grid Domain %q: %+v", id.Name, err)
}
return nil
}
func expandAzureRmEventgridDomainInputMapping(d *schema.ResourceData) *eventgrid.JSONInputSchemaMapping {
imf, imfok := d.GetOk("input_mapping_fields")
imdv, imdvok := d.GetOk("input_mapping_default_values")
if !imfok && !imdvok {
return nil
}
jismp := eventgrid.JSONInputSchemaMappingProperties{}
if imfok {
mappings := imf.([]interface{})
mapping := mappings[0].(map[string]interface{})
if id := mapping["id"].(string); id != "" {
jismp.ID = &eventgrid.JSONField{SourceField: &id}
}
if eventTime := mapping["event_time"].(string); eventTime != "" {
jismp.EventTime = &eventgrid.JSONField{SourceField: &eventTime}
}
if topic := mapping["topic"].(string); topic != "" {
jismp.Topic = &eventgrid.JSONField{SourceField: &topic}
}
if dataVersion := mapping["data_version"].(string); dataVersion != "" {
jismp.DataVersion = &eventgrid.JSONFieldWithDefault{SourceField: &dataVersion}
}
if subject := mapping["subject"].(string); subject != "" {
jismp.Subject = &eventgrid.JSONFieldWithDefault{SourceField: &subject}
}
if eventType := mapping["event_type"].(string); eventType != "" {
jismp.EventType = &eventgrid.JSONFieldWithDefault{SourceField: &eventType}
}
}
if imdvok {
mappings := imdv.([]interface{})
mapping := mappings[0].(map[string]interface{})
if dataVersion := mapping["data_version"].(string); dataVersion != "" {
jismp.DataVersion = &eventgrid.JSONFieldWithDefault{DefaultValue: &dataVersion}
}
if subject := mapping["subject"].(string); subject != "" {
jismp.Subject = &eventgrid.JSONFieldWithDefault{DefaultValue: &subject}
}
if eventType := mapping["event_type"].(string); eventType != "" {
jismp.EventType = &eventgrid.JSONFieldWithDefault{DefaultValue: &eventType}
}
}
jsonMapping := eventgrid.JSONInputSchemaMapping{
JSONInputSchemaMappingProperties: &jismp,
InputSchemaMappingType: eventgrid.InputSchemaMappingTypeJSON,
}
return &jsonMapping
}
func flattenAzureRmEventgridDomainInputMapping(input eventgrid.BasicInputSchemaMapping) ([]interface{}, error) {
if input == nil {
return nil, nil
}
result := make(map[string]interface{})
jsonValues, ok := input.(eventgrid.JSONInputSchemaMapping)
if !ok {
return nil, fmt.Errorf("Unable to read JSONInputSchemaMapping")
}
props := jsonValues.JSONInputSchemaMappingProperties
if props.EventTime != nil && props.EventTime.SourceField != nil {
result["event_time"] = *props.EventTime.SourceField
}
if props.ID != nil && props.ID.SourceField != nil {
result["id"] = *props.ID.SourceField
}
if props.Topic != nil && props.Topic.SourceField != nil {
result["topic"] = *props.Topic.SourceField
}
if props.DataVersion != nil && props.DataVersion.SourceField != nil {
result["data_version"] = *props.DataVersion.SourceField
}
if props.EventType != nil && props.EventType.SourceField != nil {
result["event_type"] = *props.EventType.SourceField
}
if props.Subject != nil && props.Subject.SourceField != nil {
result["subject"] = *props.Subject.SourceField
}
return []interface{}{result}, nil
}
func flattenAzureRmEventgridDomainInputMappingDefaultValues(input eventgrid.BasicInputSchemaMapping) ([]interface{}, error) {
if input == nil {
return nil, nil
}
result := make(map[string]interface{})
jsonValues, ok := input.(eventgrid.JSONInputSchemaMapping)
if !ok {
return nil, fmt.Errorf("Unable to read JSONInputSchemaMapping")
}
props := jsonValues.JSONInputSchemaMappingProperties
if props.DataVersion != nil && props.DataVersion.DefaultValue != nil {
result["data_version"] = *props.DataVersion.DefaultValue
}
if props.EventType != nil && props.EventType.DefaultValue != nil {
result["event_type"] = *props.EventType.DefaultValue
}
if props.Subject != nil && props.Subject.DefaultValue != nil {
result["subject"] = *props.Subject.DefaultValue
}
return []interface{}{result}, nil
}