forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabricks_workspace_resource.go
371 lines (306 loc) · 11.4 KB
/
databricks_workspace_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
package databricks
import (
"fmt"
"log"
"regexp"
"time"
"github.com/Azure/azure-sdk-for-go/services/databricks/mgmt/2018-04-01/databricks"
"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/services/databricks/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 resourceArmDatabricksWorkspace() *schema.Resource {
return &schema.Resource{
Create: resourceArmDatabricksWorkspaceCreateUpdate,
Read: resourceArmDatabricksWorkspaceRead,
Update: resourceArmDatabricksWorkspaceCreateUpdate,
Delete: resourceArmDatabricksWorkspaceDelete,
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.DatabricksWorkspaceID(id)
return err
}),
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: ValidateDatabricksWorkspaceName,
},
"location": azure.SchemaLocation(),
"resource_group_name": azure.SchemaResourceGroupName(),
"sku": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"standard",
"premium",
"trial",
}, false),
},
"tags": tags.Schema(),
"managed_resource_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"custom_parameters": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"no_public_ip": {
Type: schema.TypeBool,
ForceNew: true,
Optional: true,
},
"public_subnet_name": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"private_subnet_name": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"virtual_network_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
ValidateFunc: azure.ValidateResourceIDOrEmpty,
},
},
},
},
"managed_resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"workspace_url": {
Type: schema.TypeString,
Computed: true,
},
"workspace_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceArmDatabricksWorkspaceCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).DataBricks.WorkspacesClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
subscriptionID := meta.(*clients.Client).Account.SubscriptionId
log.Printf("[INFO] preparing arguments for Azure ARM Databricks Workspace creation.")
name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
if 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 Databricks Workspace %q (Resource Group %q): %s", name, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_databricks_workspace", *existing.ID)
}
}
skuName := d.Get("sku").(string)
managedResourceGroupName := d.Get("managed_resource_group_name").(string)
var managedResourceGroupID string
location := azure.NormalizeLocation(d.Get("location").(string))
t := d.Get("tags").(map[string]interface{})
expandedTags := tags.Expand(t)
if managedResourceGroupName == "" {
// no managed resource group name was provided, we use the default pattern
log.Printf("[DEBUG][azurerm_databricks_workspace] no managed resource group id was provided, we use the default pattern.")
managedResourceGroupID = fmt.Sprintf("/subscriptions/%s/resourceGroups/databricks-rg-%s", subscriptionID, resourceGroup)
} else {
log.Printf("[DEBUG][azurerm_databricks_workspace] a managed group name was provided: %q", managedResourceGroupName)
managedResourceGroupID = fmt.Sprintf("/subscriptions/%s/resourceGroups/%s", subscriptionID, managedResourceGroupName)
}
workspace := databricks.Workspace{
Sku: &databricks.Sku{
Name: utils.String(skuName),
},
Location: utils.String(location),
WorkspaceProperties: &databricks.WorkspaceProperties{
ManagedResourceGroupID: &managedResourceGroupID,
Parameters: expandWorkspaceCustomParameters(d),
},
Tags: expandedTags,
}
future, err := client.CreateOrUpdate(ctx, workspace, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error creating/updating Databricks Workspace %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for the completion of the creating/updating of Databricks Workspace %q (Resource Group %q): %+v", name, resourceGroup, err)
}
read, err := client.Get(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error retrieving Databricks Workspace %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Databricks Workspace %q (Resource Group %q) ID", name, resourceGroup)
}
d.SetId(*read.ID)
return resourceArmDatabricksWorkspaceRead(d, meta)
}
func resourceArmDatabricksWorkspaceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).DataBricks.WorkspacesClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.DatabricksWorkspaceID(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("[DEBUG] Databricks Workspace %q was not found in Resource Group %q - removing from state", id.Name, id.ResourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("Error making Read request on Azure Databricks Workspace %s: %s", id.Name, err)
}
d.Set("name", id.Name)
d.Set("resource_group_name", id.ResourceGroup)
if location := resp.Location; location != nil {
d.Set("location", azure.NormalizeLocation(*location))
}
if sku := resp.Sku; sku != nil {
d.Set("sku", sku.Name)
}
if props := resp.WorkspaceProperties; props != nil {
managedResourceGroupID, err := azure.ParseAzureResourceID(*props.ManagedResourceGroupID)
if err != nil {
return err
}
d.Set("managed_resource_group_id", props.ManagedResourceGroupID)
d.Set("managed_resource_group_name", managedResourceGroupID.ResourceGroup)
d.Set("custom_parameters", flattenWorkspaceCustomParameters(props.Parameters))
d.Set("workspace_url", props.WorkspaceURL)
d.Set("workspace_id", props.WorkspaceID)
}
return tags.FlattenAndSet(d, resp.Tags)
}
func resourceArmDatabricksWorkspaceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).DataBricks.WorkspacesClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.DatabricksWorkspaceID(d.Id())
if err != nil {
return err
}
future, err := client.Delete(ctx, id.ResourceGroup, id.Name)
if err != nil {
return fmt.Errorf("Error deleting Databricks Workspace %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
if !response.WasNotFound(future.Response()) {
return fmt.Errorf("Error waiting for deletion of Databricks Workspace %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
}
return nil
}
func flattenWorkspaceCustomParameters(p *databricks.WorkspaceCustomParameters) []interface{} {
if p == nil {
return nil
}
parameters := make(map[string]interface{})
if v := p.EnableNoPublicIP; v != nil {
if v.Value != nil {
parameters["no_public_ip"] = *v.Value
}
}
if v := p.CustomPrivateSubnetName; v != nil {
if v.Value != nil {
parameters["private_subnet_name"] = *v.Value
}
}
if v := p.CustomPublicSubnetName; v != nil {
if v.Value != nil {
parameters["public_subnet_name"] = *v.Value
}
}
if v := p.CustomVirtualNetworkID; v != nil {
if v.Value != nil {
parameters["virtual_network_id"] = *v.Value
}
}
return []interface{}{parameters}
}
func expandWorkspaceCustomParameters(d *schema.ResourceData) *databricks.WorkspaceCustomParameters {
configList, ok := d.GetOkExists("custom_parameters")
if !ok {
return nil
}
config := configList.([]interface{})[0].(map[string]interface{})
parameters := databricks.WorkspaceCustomParameters{}
if v, ok := config["no_public_ip"].(bool); ok {
parameters.EnableNoPublicIP = &databricks.WorkspaceCustomBooleanParameter{
Value: &v,
}
}
if v := config["public_subnet_name"].(string); v != "" {
parameters.CustomPublicSubnetName = &databricks.WorkspaceCustomStringParameter{
Value: &v,
}
}
if v := config["private_subnet_name"].(string); v != "" {
parameters.CustomPrivateSubnetName = &databricks.WorkspaceCustomStringParameter{
Value: &v,
}
}
if v := config["virtual_network_id"].(string); v != "" {
parameters.CustomVirtualNetworkID = &databricks.WorkspaceCustomStringParameter{
Value: &v,
}
}
return ¶meters
}
func ValidateDatabricksWorkspaceName(i interface{}, k string) (warnings []string, errors []error) {
v, ok := i.(string)
if !ok {
errors = append(errors, fmt.Errorf("expected %q type to be string", k))
return warnings, errors
}
// Cannot be empty
if len(v) == 0 {
errors = append(errors, fmt.Errorf("%q cannot be an empty string: %q", k, v))
return warnings, errors
}
// First, second, and last characters must be a letter or number with a total length between 3 to 64 characters
// NOTE: Restricted name to 30 characters because that is the restriction in Azure Portal even though the API supports 64 characters
if !regexp.MustCompile("^[a-zA-Z0-9]{2}[-_a-zA-Z0-9]{0,27}[a-zA-Z0-9]{1}$").MatchString(v) {
errors = append(errors, fmt.Errorf("%q must be 3 - 30 characters in length", k))
errors = append(errors, fmt.Errorf("%q first, second, and last characters must be a letter or number", k))
errors = append(errors, fmt.Errorf("%q can only contain letters, numbers, underscores, and hyphens", k))
}
// No consecutive hyphens
if regexp.MustCompile("(--)").MatchString(v) {
errors = append(errors, fmt.Errorf("%q must not contain any consecutive hyphens", k))
}
return warnings, errors
}