-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
resource_arm_storage_share.go
390 lines (326 loc) · 13.1 KB
/
resource_arm_storage_share.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
package azurerm
import (
"fmt"
"log"
"regexp"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/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/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/storage"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
"github.com/tombuildsstuff/giovanni/storage/2018-11-09/file/shares"
)
func resourceArmStorageShare() *schema.Resource {
return &schema.Resource{
Create: resourceArmStorageShareCreate,
Read: resourceArmStorageShareRead,
Update: resourceArmStorageShareUpdate,
Delete: resourceArmStorageShareDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
SchemaVersion: 2,
StateUpgraders: []schema.StateUpgrader{
{
// this should have been applied from pre-0.12 migration system; backporting just in-case
Type: resourceStorageShareStateResourceV0V1().CoreConfigSchema().ImpliedType(),
Upgrade: resourceStorageShareStateUpgradeV0ToV1,
Version: 0,
},
{
Type: resourceStorageShareStateResourceV0V1().CoreConfigSchema().ImpliedType(),
Upgrade: resourceStorageShareStateUpgradeV1ToV2,
Version: 1,
},
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateArmStorageShareName,
},
"resource_group_name": azure.SchemaResourceGroupNameDeprecated(),
"storage_account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"quota": {
Type: schema.TypeInt,
Optional: true,
Default: 5120,
ValidateFunc: validation.IntBetween(1, 102400),
},
"metadata": storage.MetaDataSchema(),
"acl": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"access_policy": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"start": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.NoEmptyStrings,
},
"expiry": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.NoEmptyStrings,
},
"permissions": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.NoEmptyStrings,
},
},
},
},
},
},
},
"url": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceArmStorageShareCreate(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
storageClient := meta.(*ArmClient).Storage
accountName := d.Get("storage_account_name").(string)
shareName := d.Get("name").(string)
quota := d.Get("quota").(int)
metaDataRaw := d.Get("metadata").(map[string]interface{})
metaData := storage.ExpandMetaData(metaDataRaw)
aclsRaw := d.Get("acl").(*schema.Set).List()
acls := expandStorageShareACLs(aclsRaw)
resourceGroup, err := storageClient.FindResourceGroup(ctx, accountName)
if err != nil {
return fmt.Errorf("Error locating Resource Group for Storage Share %q (Account %s): %s", shareName, accountName, err)
}
if resourceGroup == nil {
return fmt.Errorf("Unable to locate Resource Group for Storage Share %q (Account %s) - assuming removed & removing from state", shareName, accountName)
}
client, err := storageClient.FileSharesClient(ctx, *resourceGroup, accountName)
if err != nil {
return fmt.Errorf("Error building File Share Client: %s", err)
}
id := client.GetResourceID(accountName, shareName)
if features.ShouldResourcesBeImported() {
existing, err := client.GetProperties(ctx, accountName, shareName)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for existence of existing Storage Share %q (Account %q / Resource Group %q): %+v", shareName, accountName, *resourceGroup, err)
}
}
if !utils.ResponseWasNotFound(existing.Response) {
return tf.ImportAsExistsError("azurerm_storage_share", id)
}
}
log.Printf("[INFO] Creating Share %q in Storage Account %q", shareName, accountName)
input := shares.CreateInput{
QuotaInGB: quota,
MetaData: metaData,
}
if _, err := client.Create(ctx, accountName, shareName, input); err != nil {
return fmt.Errorf("Error creating Share %q (Account %q / Resource Group %q): %+v", shareName, accountName, *resourceGroup, err)
}
if _, err := client.SetACL(ctx, accountName, shareName, acls); err != nil {
return fmt.Errorf("Error setting ACL's for Share %q (Account %q / Resource Group %q): %+v", shareName, accountName, *resourceGroup, err)
}
d.SetId(id)
return resourceArmStorageShareRead(d, meta)
}
func resourceArmStorageShareRead(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
storageClient := meta.(*ArmClient).Storage
id, err := shares.ParseResourceID(d.Id())
if err != nil {
return err
}
resourceGroup, err := storageClient.FindResourceGroup(ctx, id.AccountName)
if err != nil {
return fmt.Errorf("Error locating Resource Group for Storage Share %q (Account %s): %s", id.ShareName, id.AccountName, err)
}
if resourceGroup == nil {
log.Printf("[WARN] Unable to determine Resource Group for Storage Share %q (Account %s) - assuming removed & removing from state", id.ShareName, id.AccountName)
d.SetId("")
return nil
}
client, err := storageClient.FileSharesClient(ctx, *resourceGroup, id.AccountName)
if err != nil {
return fmt.Errorf("Error building File Share Client for Storage Account %q (Resource Group %q): %s", id.AccountName, *resourceGroup, err)
}
props, err := client.GetProperties(ctx, id.AccountName, id.ShareName)
if err != nil {
if utils.ResponseWasNotFound(props.Response) {
log.Printf("[DEBUG] File Share %q was not found in Account %q / Resource Group %q - assuming removed & removing from state", id.ShareName, id.AccountName, *resourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving File Share %q (Account %q / Resource Group %q): %s", id.ShareName, id.AccountName, *resourceGroup, err)
}
acls, err := client.GetACL(ctx, id.AccountName, id.ShareName)
if err != nil {
return fmt.Errorf("Error retrieving ACL's for File Share %q (Account %q / Resource Group %q): %s", id.ShareName, id.AccountName, *resourceGroup, err)
}
d.Set("name", id.ShareName)
d.Set("storage_account_name", id.AccountName)
d.Set("url", client.GetResourceID(id.AccountName, id.ShareName))
d.Set("quota", props.ShareQuota)
if err := d.Set("metadata", storage.FlattenMetaData(props.MetaData)); err != nil {
return fmt.Errorf("Error flattening `metadata`: %+v", err)
}
if err := d.Set("acl", flattenStorageShareACLs(acls)); err != nil {
return fmt.Errorf("Error flattening `acl`: %+v", err)
}
// Deprecated: remove in 2.0
d.Set("resource_group_name", resourceGroup)
return nil
}
func resourceArmStorageShareUpdate(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
storageClient := meta.(*ArmClient).Storage
id, err := shares.ParseResourceID(d.Id())
if err != nil {
return err
}
resourceGroup, err := storageClient.FindResourceGroup(ctx, id.AccountName)
if err != nil {
return fmt.Errorf("Error locating Resource Group for Storage Share %q (Account %s): %s", id.ShareName, id.AccountName, err)
}
if resourceGroup == nil {
log.Printf("[WARN] Unable to determine Resource Group for Storage Share %q (Account %s) - assuming removed & removing from state", id.ShareName, id.AccountName)
d.SetId("")
return nil
}
client, err := storageClient.FileSharesClient(ctx, *resourceGroup, id.AccountName)
if err != nil {
return fmt.Errorf("Error building File Share Client for Storage Account %q (Resource Group %q): %s", id.AccountName, *resourceGroup, err)
}
if d.HasChange("quota") {
log.Printf("[DEBUG] Updating the Quota for File Share %q (Storage Account %q)", id.ShareName, id.AccountName)
quota := d.Get("quota").(int)
if _, err := client.SetProperties(ctx, id.AccountName, id.ShareName, quota); err != nil {
return fmt.Errorf("Error updating Quota for File Share %q (Storage Account %q): %s", id.ShareName, id.AccountName, err)
}
log.Printf("[DEBUG] Updated the Quota for File Share %q (Storage Account %q)", id.ShareName, id.AccountName)
}
if d.HasChange("metadata") {
log.Printf("[DEBUG] Updating the MetaData for File Share %q (Storage Account %q)", id.ShareName, id.AccountName)
metaDataRaw := d.Get("metadata").(map[string]interface{})
metaData := storage.ExpandMetaData(metaDataRaw)
if _, err := client.SetMetaData(ctx, id.AccountName, id.ShareName, metaData); err != nil {
return fmt.Errorf("Error updating MetaData for File Share %q (Storage Account %q): %s", id.ShareName, id.AccountName, err)
}
log.Printf("[DEBUG] Updated the MetaData for File Share %q (Storage Account %q)", id.ShareName, id.AccountName)
}
if d.HasChange("acl") {
log.Printf("[DEBUG] Updating the ACL's for File Share %q (Storage Account %q)", id.ShareName, id.AccountName)
aclsRaw := d.Get("acl").(*schema.Set).List()
acls := expandStorageShareACLs(aclsRaw)
if _, err := client.SetACL(ctx, id.AccountName, id.ShareName, acls); err != nil {
return fmt.Errorf("Error updating ACL's for File Share %q (Storage Account %q): %s", id.ShareName, id.AccountName, err)
}
log.Printf("[DEBUG] Updated the ACL's for File Share %q (Storage Account %q)", id.ShareName, id.AccountName)
}
return resourceArmStorageShareRead(d, meta)
}
func resourceArmStorageShareDelete(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
storageClient := meta.(*ArmClient).Storage
id, err := shares.ParseResourceID(d.Id())
if err != nil {
return err
}
resourceGroup, err := storageClient.FindResourceGroup(ctx, id.AccountName)
if err != nil {
return fmt.Errorf("Error locating Resource Group for Storage Share %q (Account %s): %s", id.ShareName, id.AccountName, err)
}
if resourceGroup == nil {
log.Printf("[WARN] Unable to determine Resource Group for Storage Share %q (Account %s) - assuming removed & removing from state", id.ShareName, id.AccountName)
d.SetId("")
return nil
}
client, err := storageClient.FileSharesClient(ctx, *resourceGroup, id.AccountName)
if err != nil {
return fmt.Errorf("Error building File Share Client for Storage Account %q (Resource Group %q): %s", id.AccountName, *resourceGroup, err)
}
deleteSnapshots := true
if _, err := client.Delete(ctx, id.AccountName, id.ShareName, deleteSnapshots); err != nil {
return fmt.Errorf("Error deleting File Share %q (Storage Account %q / Resource Group %q): %s", id.ShareName, id.AccountName, *resourceGroup, err)
}
return nil
}
func expandStorageShareACLs(input []interface{}) []shares.SignedIdentifier {
results := make([]shares.SignedIdentifier, 0)
for _, v := range input {
vals := v.(map[string]interface{})
policies := vals["access_policy"].([]interface{})
policy := policies[0].(map[string]interface{})
identifier := shares.SignedIdentifier{
Id: vals["id"].(string),
AccessPolicy: shares.AccessPolicy{
Start: policy["start"].(string),
Expiry: policy["expiry"].(string),
Permission: policy["permissions"].(string),
},
}
results = append(results, identifier)
}
return results
}
func flattenStorageShareACLs(input shares.GetACLResult) []interface{} {
result := make([]interface{}, 0)
for _, v := range input.SignedIdentifiers {
output := map[string]interface{}{
"id": v.Id,
"access_policy": []interface{}{
map[string]interface{}{
"start": v.AccessPolicy.Start,
"expiry": v.AccessPolicy.Expiry,
"permissions": v.AccessPolicy.Permission,
},
},
}
result = append(result, output)
}
return result
}
// Following the naming convention as laid out in the docs https://msdn.microsoft.com/library/azure/dn167011.aspx
func validateArmStorageShareName(v interface{}, k string) (warnings []string, errors []error) {
value := v.(string)
if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"only lowercase alphanumeric characters and hyphens allowed in %q: %q",
k, value))
}
if len(value) < 3 || len(value) > 63 {
errors = append(errors, fmt.Errorf(
"%q must be between 3 and 63 characters: %q", k, value))
}
if regexp.MustCompile(`^-`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q cannot begin with a hyphen: %q", k, value))
}
if regexp.MustCompile(`[-]{2,}`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q does not allow consecutive hyphens: %q", k, value))
}
return warnings, errors
}