forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_analytics_linked_service_resource.go
352 lines (291 loc) · 13.2 KB
/
log_analytics_linked_service_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
package loganalytics
import (
"fmt"
"log"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/operationalinsights/mgmt/2020-08-01/operationalinsights"
"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/suppress"
"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/services/loganalytics/parse"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/loganalytics/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func resourceArmLogAnalyticsLinkedService() *schema.Resource {
return &schema.Resource{
Create: resourceArmLogAnalyticsLinkedServiceCreateUpdate,
Read: resourceArmLogAnalyticsLinkedServiceRead,
Update: resourceArmLogAnalyticsLinkedServiceCreateUpdate,
Delete: resourceArmLogAnalyticsLinkedServiceDelete,
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{
"resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(),
// TODO: Remove in 3.0
"workspace_name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: validate.LogAnalyticsWorkspaceName,
ExactlyOneOf: []string{"workspace_name", "workspace_id"},
Deprecated: "This field has been deprecated in favour of `workspace_id` and will be removed in a future version of the provider",
},
"workspace_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: azure.ValidateResourceID,
ExactlyOneOf: []string{"workspace_name", "workspace_id"},
},
// TODO: Remove in 3.0
"linked_service_name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: validation.StringInSlice([]string{
"automation",
"cluster",
}, false),
Deprecated: "This field has been deprecated and will be removed in a future version of the provider",
},
// TODO: Remove in 3.0
"resource_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: azure.ValidateResourceID,
ExactlyOneOf: []string{"read_access_id", "write_access_id", "resource_id"},
Deprecated: "This field has been deprecated in favour of `read_access_id` and will be removed in a future version of the provider",
},
"read_access_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: azure.ValidateResourceID,
ExactlyOneOf: []string{"read_access_id", "write_access_id", "resource_id"},
},
"write_access_id": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: azure.ValidateResourceID,
ExactlyOneOf: []string{"read_access_id", "write_access_id", "resource_id"},
},
// Exported properties
"name": {
Type: schema.TypeString,
Computed: true,
},
"tags": tags.Schema(),
},
// TODO: Remove in 3.0
CustomizeDiff: func(d *schema.ResourceDiff, v interface{}) error {
if d.HasChange("linked_service_name") {
oldServiceName, newServiceName := d.GetChange("linked_service_name")
// This is an unneeded field, if it is removed you can safely ignore it
// as it's value can be(and is) derived via the 'read_access_id' field. It
// is only here for backwards compatibility to avoid a breaking change
if newServiceName.(string) != "" {
// Ignore change if it's in case only
if !strings.EqualFold(oldServiceName.(string), newServiceName.(string)) {
d.ForceNew("linked_service_name")
}
}
}
if d.HasChange("workspace_id") {
forceNew := true
_, newWorkspaceName := d.GetChange("workspace_name")
oldWorkspaceID, newWorkspaceID := d.GetChange("workspace_id")
// If the workspcae ID has been removed, only do a force new if the new workspace name
// and the old workspace ID points to different workspaces
if oldWorkspaceID.(string) != "" && newWorkspaceName.(string) != "" && newWorkspaceID.(string) == "" {
workspace, err := parse.LogAnalyticsWorkspaceID(oldWorkspaceID.(string))
if err == nil {
if workspace.WorkspaceName == newWorkspaceName.(string) {
forceNew = false
}
}
}
if forceNew {
d.ForceNew("workspace_id")
}
}
if d.HasChange("workspace_name") {
forceNew := true
oldWorkspaceName, newWorkspaceName := d.GetChange("workspace_name")
_, newWorkspaceID := d.GetChange("workspace_id")
// If the workspcae name has been removed, only do a force new if the new workspace ID
// and the old workspace name points to different workspaces
if oldWorkspaceName.(string) != "" && newWorkspaceID.(string) != "" && newWorkspaceName.(string) == "" {
workspace, err := parse.LogAnalyticsWorkspaceID(newWorkspaceID.(string))
if err == nil {
if workspace.WorkspaceName == oldWorkspaceName.(string) {
forceNew = false
}
}
}
if forceNew {
d.ForceNew("workspace_name")
}
}
return nil
},
}
}
func resourceArmLogAnalyticsLinkedServiceCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).LogAnalytics.LinkedServicesClient
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
log.Printf("[INFO] preparing arguments for AzureRM Log Analytics Linked Services creation.")
// TODO: Remove in 3.0
var tmpSpace parse.LogAnalyticsWorkspaceId
var workspaceId string
resourceGroup := d.Get("resource_group_name").(string)
readAccess := d.Get("read_access_id").(string)
writeAccess := d.Get("write_access_id").(string)
linkedServiceName := d.Get("linked_service_name").(string)
t := d.Get("tags").(map[string]interface{})
if resourceId := d.Get("resource_id").(string); resourceId != "" {
readAccess = resourceId
}
if workspaceName := d.Get("workspace_name").(string); workspaceName != "" {
tmpSpace = parse.NewLogAnalyticsWorkspaceID(subscriptionId, resourceGroup, workspaceName)
workspaceId = tmpSpace.ID()
} else {
workspaceId = d.Get("workspace_id").(string)
}
workspace, err := parse.LogAnalyticsWorkspaceID(workspaceId)
if err != nil {
return fmt.Errorf("Linked Service (Resource Group %q) unable to parse workspace id: %+v", resourceGroup, err)
}
id := parse.NewLogAnalyticsLinkedServiceID(subscriptionId, resourceGroup, workspace.WorkspaceName, LogAnalyticsLinkedServiceType(readAccess))
if linkedServiceName != "" {
if !strings.EqualFold(linkedServiceName, LogAnalyticsLinkedServiceType(readAccess)) {
return fmt.Errorf("Linked Service '%s/%s' (Resource Group %q): 'linked_service_name' %q does not match expected value of %q", workspace.WorkspaceName, id.LinkedServiceName, resourceGroup, linkedServiceName, LogAnalyticsLinkedServiceType(readAccess))
}
}
if strings.EqualFold(id.LinkedServiceName, "Cluster") && writeAccess == "" {
return fmt.Errorf("Linked Service '%s/%s' (Resource Group %q): A linked Log Analytics Cluster requires the 'write_access_id' attribute to be set", workspace.WorkspaceName, id.LinkedServiceName, resourceGroup)
}
if strings.EqualFold(id.LinkedServiceName, "Automation") && readAccess == "" {
return fmt.Errorf("Linked Service '%s/%s' (Resource Group %q): A linked Automation Account requires the 'read_access_id' attribute to be set", workspace.WorkspaceName, id.LinkedServiceName, resourceGroup)
}
if d.IsNewResource() {
existing, err := client.Get(ctx, resourceGroup, workspace.WorkspaceName, id.LinkedServiceName)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("checking for presence of existing Linked Service '%s/%s' (Resource Group %q): %+v", workspace.WorkspaceName, id.LinkedServiceName, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_log_analytics_linked_service", *existing.ID)
}
}
parameters := operationalinsights.LinkedService{
LinkedServiceProperties: &operationalinsights.LinkedServiceProperties{},
Tags: tags.Expand(t),
}
if id.LinkedServiceName == "Automation" {
parameters.LinkedServiceProperties.ResourceID = utils.String(readAccess)
}
if id.LinkedServiceName == "Cluster" {
parameters.LinkedServiceProperties.WriteAccessResourceID = utils.String(writeAccess)
}
future, err := client.CreateOrUpdate(ctx, resourceGroup, workspace.WorkspaceName, id.LinkedServiceName, parameters)
if err != nil {
return fmt.Errorf("creating Linked Service '%s/%s' (Resource Group %q): %+v", workspace.WorkspaceName, id.LinkedServiceName, resourceGroup, err)
}
if err := future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting on creating future for Linked Service '%s/%s' (Resource Group %q): %+v", workspace.WorkspaceName, id.LinkedServiceName, resourceGroup, err)
}
_, err = client.Get(ctx, resourceGroup, workspace.WorkspaceName, id.LinkedServiceName)
if err != nil {
return fmt.Errorf("retrieving Linked Service '%s/%s' (Resource Group %q): %+v", workspace.WorkspaceName, id.LinkedServiceName, resourceGroup, err)
}
d.SetId(id.ID())
return resourceArmLogAnalyticsLinkedServiceRead(d, meta)
}
func resourceArmLogAnalyticsLinkedServiceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).LogAnalytics.LinkedServicesClient
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
workspaceName := id.Path["workspaces"]
serviceType := id.Path["linkedServices"]
workspace := parse.NewLogAnalyticsWorkspaceID(subscriptionId, resourceGroup, workspaceName)
resp, err := client.Get(ctx, resourceGroup, workspaceName, serviceType)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
d.SetId("")
return nil
}
return fmt.Errorf("making Read request on AzureRM Log Analytics Linked Service '%s/%s' (Resource Group %q): %+v", workspace.WorkspaceName, serviceType, resourceGroup, err)
}
d.Set("name", resp.Name)
d.Set("resource_group_name", resourceGroup)
d.Set("workspace_id", workspace.ID())
d.Set("workspace_name", workspaceName)
d.Set("linked_service_name", serviceType)
if props := resp.LinkedServiceProperties; props != nil {
d.Set("resource_id", props.ResourceID)
d.Set("read_access_id", props.ResourceID)
d.Set("write_access_id", props.WriteAccessResourceID)
}
return tags.FlattenAndSet(d, resp.Tags)
}
func resourceArmLogAnalyticsLinkedServiceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).LogAnalytics.LinkedServicesClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
workspaceName := id.Path["workspaces"]
serviceType := id.Path["linkedServices"]
future, err := client.Delete(ctx, resourceGroup, workspaceName, serviceType)
if err != nil {
return fmt.Errorf("deleting Log Analytics Linked Service '%s/%s' (Resource Group %q): %+v", workspaceName, serviceType, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
if !response.WasNotFound(future.Response()) {
return fmt.Errorf("waiting for deletion of Log Analytics Linked Service '%s/%s' (Resource Group %q): %+v", workspaceName, serviceType, resourceGroup, err)
}
}
// (@WodansSon) - This is a bug in the service API, it returns instantly from the delete call with a 200
// so we must wait for the state to change before we return from the delete function
deleteWait := logAnalyticsLinkedServiceDeleteWaitForState(ctx, meta, d.Timeout(schema.TimeoutDelete), resourceGroup, workspaceName, serviceType)
if _, err := deleteWait.WaitForState(); err != nil {
return fmt.Errorf("waiting for Log Analytics Cluster to finish deleting '%s/%s' (Resource Group %q): %+v", workspaceName, serviceType, resourceGroup, err)
}
return nil
}
func LogAnalyticsLinkedServiceType(readAccessId string) string {
if readAccessId != "" {
return "Automation"
}
return "Cluster"
}