-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
resource_arm_monitor_log_profile.go
306 lines (255 loc) · 8.79 KB
/
resource_arm_monitor_log_profile.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
package azurerm
import (
"fmt"
"log"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2019-06-01/insights"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"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/helpers/validate"
"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"
)
func resourceArmMonitorLogProfile() *schema.Resource {
return &schema.Resource{
Create: resourceArmLogProfileCreateUpdate,
Read: resourceArmLogProfileRead,
Update: resourceArmLogProfileCreateUpdate,
Delete: resourceArmLogProfileDelete,
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,
ValidateFunc: validate.NoEmptyStrings,
},
"storage_account_id": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: azure.ValidateResourceIDOrEmpty,
},
"servicebus_rule_id": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: azure.ValidateResourceIDOrEmpty,
},
"locations": {
Type: schema.TypeSet,
MinItems: 1,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
StateFunc: azure.NormalizeLocation,
DiffSuppressFunc: azure.SuppressLocationDiff,
},
Set: schema.HashString,
},
"categories": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
DiffSuppressFunc: suppress.CaseDifference,
},
Set: schema.HashString,
},
"retention_policy": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Required: true,
},
"days": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
},
},
},
},
},
}
}
func resourceArmLogProfileCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).Monitor.LogProfilesClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*ArmClient).StopContext, d)
defer cancel()
name := d.Get("name").(string)
if features.ShouldResourcesBeImported() && d.IsNewResource() {
existing, err := client.Get(ctx, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of existing Monitor Log Profile %q: %s", name, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_monitor_log_profile", *existing.ID)
}
}
storageAccountID := d.Get("storage_account_id").(string)
serviceBusRuleID := d.Get("servicebus_rule_id").(string)
categories := expandLogProfileCategories(d)
locations := expandLogProfileLocations(d)
retentionPolicy := expandAzureRmLogProfileRetentionPolicy(d)
logProfileProperties := &insights.LogProfileProperties{
Categories: &categories,
Locations: &locations,
RetentionPolicy: &retentionPolicy,
}
if storageAccountID != "" {
logProfileProperties.StorageAccountID = utils.String(storageAccountID)
}
if serviceBusRuleID != "" {
logProfileProperties.ServiceBusRuleID = utils.String(serviceBusRuleID)
}
parameters := insights.LogProfileResource{
Name: utils.String(name),
LogProfileProperties: logProfileProperties,
}
if _, err := client.CreateOrUpdate(ctx, name, parameters); err != nil {
return fmt.Errorf("Error Creating/Updating Log Profile %q: %+v", name, err)
}
// Wait for Log Profile to become available
if err := resource.Retry(600*time.Second, retryLogProfilesClientGet(name, meta)); err != nil {
return fmt.Errorf("Error waiting for Log Profile %q to become available: %+v", name, err)
}
read, err := client.Get(ctx, name)
if err != nil {
return fmt.Errorf("Error retrieving Log Profile %q: %+v", name, err)
}
d.SetId(*read.ID)
return resourceArmLogProfileRead(d, meta)
}
func resourceArmLogProfileRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).Monitor.LogProfilesClient
ctx, cancel := timeouts.ForRead(meta.(*ArmClient).StopContext, d)
defer cancel()
name, err := parseLogProfileNameFromID(d.Id())
if err != nil {
return fmt.Errorf("Error parsing log profile name from ID %s: %s", d.Id(), err)
}
resp, err := client.Get(ctx, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Log Profile %q was not found - removing from state!", name)
d.SetId("")
return nil
}
return fmt.Errorf("Error making Read request on Azure Log Profile %q: %+v", name, err)
}
d.Set("name", resp.Name)
if props := resp.LogProfileProperties; props != nil {
d.Set("storage_account_id", props.StorageAccountID)
d.Set("servicebus_rule_id", props.ServiceBusRuleID)
d.Set("categories", props.Categories)
if err := d.Set("locations", flattenAzureRmLogProfileLocations(props.Locations)); err != nil {
return fmt.Errorf("Error setting `locations`: %+v", err)
}
if err := d.Set("retention_policy", flattenAzureRmLogProfileRetentionPolicy(props.RetentionPolicy)); err != nil {
return fmt.Errorf("Error setting `retention_policy`: %+v", err)
}
}
return nil
}
func resourceArmLogProfileDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).Monitor.LogProfilesClient
ctx, cancel := timeouts.ForDelete(meta.(*ArmClient).StopContext, d)
defer cancel()
name, err := parseLogProfileNameFromID(d.Id())
if err != nil {
return fmt.Errorf("Error parsing log profile name from ID %s: %s", d.Id(), err)
}
_, err = client.Delete(ctx, name)
if err != nil {
return fmt.Errorf("Error deleting Log Profile %q: %+v", name, err)
}
return nil
}
func expandLogProfileCategories(d *schema.ResourceData) []string {
logProfileCategories := d.Get("categories").(*schema.Set).List()
categories := make([]string, 0)
for _, category := range logProfileCategories {
categories = append(categories, category.(string))
}
return categories
}
func expandLogProfileLocations(d *schema.ResourceData) []string {
logProfileLocations := d.Get("locations").(*schema.Set).List()
locations := make([]string, 0)
for _, location := range logProfileLocations {
locations = append(locations, azure.NormalizeLocation(location.(string)))
}
return locations
}
func expandAzureRmLogProfileRetentionPolicy(d *schema.ResourceData) insights.RetentionPolicy {
vs := d.Get("retention_policy").([]interface{})
v := vs[0].(map[string]interface{})
enabled := v["enabled"].(bool)
days := v["days"].(int)
logProfileRetentionPolicy := insights.RetentionPolicy{
Enabled: utils.Bool(enabled),
Days: utils.Int32(int32(days)),
}
return logProfileRetentionPolicy
}
func flattenAzureRmLogProfileLocations(input *[]string) []string {
result := make([]string, 0)
if input != nil {
for _, location := range *input {
result = append(result, azure.NormalizeLocation(location))
}
}
return result
}
func flattenAzureRmLogProfileRetentionPolicy(input *insights.RetentionPolicy) []interface{} {
if input == nil {
return []interface{}{}
}
result := make(map[string]interface{})
if input.Enabled != nil {
result["enabled"] = *input.Enabled
}
if input.Days != nil {
result["days"] = *input.Days
}
return []interface{}{result}
}
func retryLogProfilesClientGet(name string, meta interface{}) func() *resource.RetryError {
return func() *resource.RetryError {
client := meta.(*ArmClient).Monitor.LogProfilesClient
ctx := meta.(*ArmClient).StopContext
if _, err := client.Get(ctx, name); err != nil {
return resource.RetryableError(err)
}
return nil
}
}
func parseLogProfileNameFromID(id string) (string, error) {
components := strings.Split(id, "/")
if len(components) == 0 {
return "", fmt.Errorf("Azure Log Profile ID is empty or not formatted correctly: %s", id)
}
if len(components) != 7 {
return "", fmt.Errorf("Azure Log Profile ID should have 6 segments, got %d: '%s'", len(components)-1, id)
}
return components[6], nil
}