-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
resource_arm_notification_hub_namespace.go
350 lines (297 loc) · 11.8 KB
/
resource_arm_notification_hub_namespace.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
package azurerm
import (
"context"
"fmt"
"log"
"strconv"
"time"
"github.com/Azure/azure-sdk-for-go/services/notificationhubs/mgmt/2017-04-01/notificationhubs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"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/response"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
var notificationHubNamespaceResourceName = "azurerm_notification_hub_namespace"
func resourceArmNotificationHubNamespace() *schema.Resource {
return &schema.Resource{
Create: resourceArmNotificationHubNamespaceCreateUpdate,
Read: resourceArmNotificationHubNamespaceRead,
Update: resourceArmNotificationHubNamespaceCreateUpdate,
Delete: resourceArmNotificationHubNamespaceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
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),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_group_name": azure.SchemaResourceGroupName(),
"location": azure.SchemaLocation(),
"sku": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Deprecated: "This property has been deprecated in favour of the 'sku_name' property and will be removed in version 2.0 of the provider",
ConflictsWith: []string{"sku_name"},
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(notificationhubs.Basic),
string(notificationhubs.Free),
string(notificationhubs.Standard),
}, false),
},
},
},
},
"sku_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"sku"},
ValidateFunc: validation.StringInSlice([]string{
string(notificationhubs.Basic),
string(notificationhubs.Free),
string(notificationhubs.Standard),
}, false),
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"namespace_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(notificationhubs.Messaging),
string(notificationhubs.NotificationHub),
}, true),
DiffSuppressFunc: suppress.CaseDifference,
},
// NOTE: skipping tags as there's a bug in the API where the Keys for Tags are returned in lower-case
// Azure Rest API Specs issue: https://github.com/Azure/azure-sdk-for-go/issues/2239
//"tags": tags.Schema(),
"servicebus_endpoint": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceArmNotificationHubNamespaceCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).NotificationHubs.NamespacesClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*ArmClient).StopContext, d)
defer cancel()
// Remove in 2.0
var sku notificationhubs.Sku
if inputs := d.Get("sku").([]interface{}); len(inputs) != 0 {
input := inputs[0].(map[string]interface{})
v := input["name"].(string)
sku = notificationhubs.Sku{
Name: notificationhubs.SkuName(v),
}
} else {
// Keep in 2.0
sku = notificationhubs.Sku{
Name: notificationhubs.SkuName(d.Get("sku_name").(string)),
}
}
if sku.Name == "" {
return fmt.Errorf("either 'sku_name' or 'sku' must be defined in the configuration file")
}
name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
location := azure.NormalizeLocation(d.Get("location").(string))
namespaceType := d.Get("namespace_type").(string)
enabled := d.Get("enabled").(bool)
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 Notification Hub Namesapce %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_notification_hub_namespace", *existing.ID)
}
}
parameters := notificationhubs.NamespaceCreateOrUpdateParameters{
Location: utils.String(location),
Sku: &sku,
NamespaceProperties: ¬ificationhubs.NamespaceProperties{
Region: utils.String(location),
NamespaceType: notificationhubs.NamespaceType(namespaceType),
Enabled: utils.Bool(enabled),
},
}
if _, err := client.CreateOrUpdate(ctx, resourceGroup, name, parameters); err != nil {
return fmt.Errorf("Error creating/updating Notification Hub Namesapce %q (Resource Group %q): %+v", name, resourceGroup, err)
}
log.Printf("[DEBUG] Waiting for Notification Hub Namespace %q (Resource Group %q) to be created", name, resourceGroup)
stateConf := &resource.StateChangeConf{
Pending: []string{"404"},
Target: []string{"200"},
Refresh: notificationHubNamespaceStateRefreshFunc(ctx, client, resourceGroup, name),
MinTimeout: 15 * time.Second,
ContinuousTargetOccurence: 10,
}
if features.SupportsCustomTimeouts() {
if d.IsNewResource() {
stateConf.Timeout = d.Timeout(schema.TimeoutCreate)
} else {
stateConf.Timeout = d.Timeout(schema.TimeoutUpdate)
}
} else {
stateConf.Timeout = 10 * time.Minute
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Notification Hub %q (Resource Group %q) to finish replicating: %s", name, resourceGroup, err)
}
read, err := client.Get(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error retrieving Notification Hub Namesapce %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Notification Hub Namespace %q (Resource Group %q) ID", name, resourceGroup)
}
d.SetId(*read.ID)
return resourceArmNotificationHubNamespaceRead(d, meta)
}
func resourceArmNotificationHubNamespaceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).NotificationHubs.NamespacesClient
ctx, cancel := timeouts.ForRead(meta.(*ArmClient).StopContext, d)
defer cancel()
id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
name := id.Path["namespaces"]
resp, err := client.Get(ctx, resourceGroup, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Notification Hub Namespace %q (Resource Group %q) was not found - removing from state!", name, resourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("Error making Read request on Notification Hub Namespace %q (Resource Group %q): %+v", name, resourceGroup, err)
}
d.Set("name", resp.Name)
d.Set("resource_group_name", resourceGroup)
if location := resp.Location; location != nil {
d.Set("location", azure.NormalizeLocation(*location))
}
if sku := resp.Sku; sku != nil {
// Remove in 2.0
if err := d.Set("sku", flattenNotificationHubNamespacesSku(sku)); err != nil {
return fmt.Errorf("Error setting 'sku': %+v", err)
}
if err := d.Set("sku_name", string(sku.Name)); err != nil {
return fmt.Errorf("Error setting 'sku_name': %+v", err)
}
} else {
return fmt.Errorf("Error making Read request on Notification Hub Namespace %q (Resource Group %q): Unable to retrieve 'sku' value", name, resourceGroup)
}
if props := resp.NamespaceProperties; props != nil {
d.Set("enabled", props.Enabled)
d.Set("namespace_type", props.NamespaceType)
d.Set("servicebus_endpoint", props.ServiceBusEndpoint)
}
return nil
}
func resourceArmNotificationHubNamespaceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).NotificationHubs.NamespacesClient
ctx, cancel := timeouts.ForDelete(meta.(*ArmClient).StopContext, d)
defer cancel()
id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
name := id.Path["namespaces"]
future, err := client.Delete(ctx, resourceGroup, name)
if err != nil {
if !response.WasNotFound(future.Response()) {
return fmt.Errorf("Error deleting Notification Hub Namespace %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}
// the future returned from the Delete method is broken 50% of the time - let's poll ourselves for now
// Related Bug: https://github.com/Azure/azure-sdk-for-go/issues/2254
log.Printf("[DEBUG] Waiting for Notification Hub Namespace %q (Resource Group %q) to be deleted", name, resourceGroup)
stateConf := &resource.StateChangeConf{
Pending: []string{"200", "202"},
Target: []string{"404"},
Refresh: notificationHubNamespaceDeleteStateRefreshFunc(ctx, client, resourceGroup, name),
}
if features.SupportsCustomTimeouts() {
stateConf.Timeout = d.Timeout(schema.TimeoutDelete)
} else {
stateConf.Timeout = 10 * time.Minute
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Notification Hub %q (Resource Group %q) to be deleted: %s", name, resourceGroup, err)
}
return nil
}
// Remove in 2.0
func flattenNotificationHubNamespacesSku(input *notificationhubs.Sku) []interface{} {
outputs := make([]interface{}, 0)
if input == nil {
return outputs
}
output := map[string]interface{}{
"name": string(input.Name),
}
outputs = append(outputs, output)
return outputs
}
func notificationHubNamespaceStateRefreshFunc(ctx context.Context, client *notificationhubs.NamespacesClient, resourceGroupName string, name string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
res, err := client.Get(ctx, resourceGroupName, name)
if err != nil {
if utils.ResponseWasNotFound(res.Response) {
return nil, "404", nil
}
return nil, "", fmt.Errorf("Error retrieving Notification Hub Namespace %q (Resource Group %q): %s", name, resourceGroupName, err)
}
return res, strconv.Itoa(res.StatusCode), nil
}
}
func notificationHubNamespaceDeleteStateRefreshFunc(ctx context.Context, client *notificationhubs.NamespacesClient, resourceGroupName string, name string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
res, err := client.Get(ctx, resourceGroupName, name)
if err != nil {
if !utils.ResponseWasNotFound(res.Response) {
return nil, "", fmt.Errorf("Error retrieving Notification Hub Namespace %q (Resource Group %q): %s", name, resourceGroupName, err)
}
}
// Note: this exists as the Delete API only seems to work some of the time
// in this case we're going to try triggering the Deletion again, in-case it didn't work prior to this attepmpt
// Upstream Bug: https://github.com/Azure/azure-sdk-for-go/issues/2254
if _, err := client.Delete(ctx, resourceGroupName, name); err != nil {
log.Printf("Error reissuing Notification Hub Namespace %q delete request (Resource Group %q): %+v", name, resourceGroupName, err)
}
return res, strconv.Itoa(res.StatusCode), nil
}
}