forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_arm_storage_account.go
648 lines (536 loc) · 18.3 KB
/
resource_arm_storage_account.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
package azurerm
import (
"fmt"
"log"
"regexp"
"strings"
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2017-10-01/storage"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
const blobStorageAccountDefaultAccessTier = "Hot"
func resourceArmStorageAccount() *schema.Resource {
return &schema.Resource{
Create: resourceArmStorageAccountCreate,
Read: resourceArmStorageAccountRead,
Update: resourceArmStorageAccountUpdate,
Delete: resourceArmStorageAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
MigrateState: resourceStorageAccountMigrateState,
SchemaVersion: 2,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateArmStorageAccountName,
},
"resource_group_name": resourceGroupNameDiffSuppressSchema(),
"location": locationSchema(),
"account_kind": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(storage.Storage),
string(storage.BlobStorage),
string(storage.StorageV2),
}, true),
Default: string(storage.Storage),
},
"account_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "This field has been split into `account_tier` and `account_replication_type`",
ValidateFunc: validateArmStorageAccountType,
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
},
"account_tier": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"Standard",
"Premium",
}, true),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
},
"account_replication_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"LRS",
"ZRS",
"GRS",
"RAGRS",
}, true),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
},
// Only valid for BlobStorage accounts, defaults to "Hot" in create function
"access_tier": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{
string(storage.Cool),
string(storage.Hot),
}, true),
},
"account_encryption_source": {
Type: schema.TypeString,
Optional: true,
Default: string(storage.MicrosoftStorage),
ValidateFunc: validation.StringInSlice([]string{
string(storage.MicrosoftKeyvault),
string(storage.MicrosoftStorage),
}, true),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
},
"custom_domain": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"use_subdomain": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
},
"enable_blob_encryption": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"enable_file_encryption": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"enable_https_traffic_only": {
Type: schema.TypeBool,
Optional: true,
},
"primary_location": {
Type: schema.TypeString,
Computed: true,
},
"secondary_location": {
Type: schema.TypeString,
Computed: true,
},
"primary_blob_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"secondary_blob_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"primary_queue_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"secondary_queue_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"primary_table_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"secondary_table_endpoint": {
Type: schema.TypeString,
Computed: true,
},
// NOTE: The API does not appear to expose a secondary file endpoint
"primary_file_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"primary_access_key": {
Type: schema.TypeString,
Computed: true,
},
"secondary_access_key": {
Type: schema.TypeString,
Computed: true,
},
"primary_connection_string": {
Type: schema.TypeString,
Computed: true,
},
"secondary_connection_string": {
Type: schema.TypeString,
Computed: true,
},
"primary_blob_connection_string": {
Type: schema.TypeString,
Computed: true,
},
"secondary_blob_connection_string": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).storageServiceClient
resourceGroupName := d.Get("resource_group_name").(string)
storageAccountName := d.Get("name").(string)
accountKind := d.Get("account_kind").(string)
location := azureRMNormalizeLocation(d.Get("location").(string))
tags := d.Get("tags").(map[string]interface{})
enableBlobEncryption := d.Get("enable_blob_encryption").(bool)
enableHTTPSTrafficOnly := d.Get("enable_https_traffic_only").(bool)
accountTier := d.Get("account_tier").(string)
replicationType := d.Get("account_replication_type").(string)
storageType := fmt.Sprintf("%s_%s", accountTier, replicationType)
storageAccountEncryptionSource := d.Get("account_encryption_source").(string)
parameters := storage.AccountCreateParameters{
Location: &location,
Sku: &storage.Sku{
Name: storage.SkuName(storageType),
},
Tags: expandTags(tags),
Kind: storage.Kind(accountKind),
AccountPropertiesCreateParameters: &storage.AccountPropertiesCreateParameters{
Encryption: &storage.Encryption{
Services: &storage.EncryptionServices{
Blob: &storage.EncryptionService{
Enabled: utils.Bool(enableBlobEncryption),
}},
KeySource: storage.KeySource(storageAccountEncryptionSource),
},
EnableHTTPSTrafficOnly: &enableHTTPSTrafficOnly,
},
}
if v, ok := d.GetOk("enable_file_encryption"); ok {
parameters.Encryption.Services.File = &storage.EncryptionService{
Enabled: utils.Bool(v.(bool)),
}
}
if _, ok := d.GetOk("custom_domain"); ok {
parameters.CustomDomain = expandStorageAccountCustomDomain(d)
}
// BlobStorage does not support ZRS
if accountKind == string(storage.BlobStorage) {
if string(parameters.Sku.Name) == string(storage.StandardZRS) {
return fmt.Errorf("A `account_replication_type` of `ZRS` isn't supported for Blob Storage accounts.")
}
}
// AccessTier is only valid for BlobStorage and StorageV2 accounts
if accountKind == string(storage.BlobStorage) || accountKind == string(storage.StorageV2) {
accessTier, ok := d.GetOk("access_tier")
if !ok {
// default to "Hot"
accessTier = blobStorageAccountDefaultAccessTier
}
parameters.AccountPropertiesCreateParameters.AccessTier = storage.AccessTier(accessTier.(string))
}
// Create
ctx := meta.(*ArmClient).StopContext
future, err := client.Create(ctx, resourceGroupName, storageAccountName, parameters)
if err != nil {
return fmt.Errorf("Error creating Azure Storage Account %q: %+v", storageAccountName, err)
}
err = future.WaitForCompletion(ctx, client.Client)
if err != nil {
return fmt.Errorf("Error waiting for Azure Storage Account %q to be created: %+v", storageAccountName, err)
}
account, err := client.GetProperties(ctx, resourceGroupName, storageAccountName)
if err != nil {
return fmt.Errorf("Error retrieving Azure Storage Account %q: %+v", storageAccountName, err)
}
if account.ID == nil {
return fmt.Errorf("Cannot read Storage Account %q (resource group %q) ID",
storageAccountName, resourceGroupName)
}
log.Printf("[INFO] storage account %q ID: %q", storageAccountName, *account.ID)
d.SetId(*account.ID)
return resourceArmStorageAccountRead(d, meta)
}
// resourceArmStorageAccountUpdate is unusual in the ARM API where most resources have a combined
// and idempotent operation for CreateOrUpdate. In particular updating all of the parameters
// available requires a call to Update per parameter...
func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
client := meta.(*ArmClient).storageServiceClient
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
storageAccountName := id.Path["storageAccounts"]
resourceGroupName := id.ResourceGroup
accountTier := d.Get("account_tier").(string)
replicationType := d.Get("account_replication_type").(string)
storageType := fmt.Sprintf("%s_%s", accountTier, replicationType)
accountKind := d.Get("account_kind").(string)
if accountKind == string(storage.BlobStorage) {
if storageType == string(storage.StandardZRS) {
return fmt.Errorf("A `account_replication_type` of `ZRS` isn't supported for Blob Storage accounts.")
}
}
d.Partial(true)
if d.HasChange("account_replication_type") {
sku := storage.Sku{
Name: storage.SkuName(storageType),
}
opts := storage.AccountUpdateParameters{
Sku: &sku,
}
_, err := client.Update(ctx, resourceGroupName, storageAccountName, opts)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account type %q: %+v", storageAccountName, err)
}
d.SetPartial("account_replication_type")
}
if d.HasChange("access_tier") {
accessTier := d.Get("access_tier").(string)
opts := storage.AccountUpdateParameters{
AccountPropertiesUpdateParameters: &storage.AccountPropertiesUpdateParameters{
AccessTier: storage.AccessTier(accessTier),
},
}
_, err := client.Update(ctx, resourceGroupName, storageAccountName, opts)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account access_tier %q: %+v", storageAccountName, err)
}
d.SetPartial("access_tier")
}
if d.HasChange("tags") {
tags := d.Get("tags").(map[string]interface{})
opts := storage.AccountUpdateParameters{
Tags: expandTags(tags),
}
_, err := client.Update(ctx, resourceGroupName, storageAccountName, opts)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account tags %q: %+v", storageAccountName, err)
}
d.SetPartial("tags")
}
if d.HasChange("enable_blob_encryption") || d.HasChange("enable_file_encryption") {
encryptionSource := d.Get("account_encryption_source").(string)
opts := storage.AccountUpdateParameters{
AccountPropertiesUpdateParameters: &storage.AccountPropertiesUpdateParameters{
Encryption: &storage.Encryption{
Services: &storage.EncryptionServices{},
KeySource: storage.KeySource(encryptionSource),
},
},
}
if d.HasChange("enable_blob_encryption") {
enableEncryption := d.Get("enable_blob_encryption").(bool)
opts.Encryption.Services.Blob = &storage.EncryptionService{
Enabled: utils.Bool(enableEncryption),
}
d.SetPartial("enable_blob_encryption")
}
if d.HasChange("enable_file_encryption") {
enableEncryption := d.Get("enable_file_encryption").(bool)
opts.Encryption.Services.File = &storage.EncryptionService{
Enabled: utils.Bool(enableEncryption),
}
d.SetPartial("enable_file_encryption")
}
_, err := client.Update(ctx, resourceGroupName, storageAccountName, opts)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account Encryption %q: %+v", storageAccountName, err)
}
}
if d.HasChange("custom_domain") {
customDomain := expandStorageAccountCustomDomain(d)
opts := storage.AccountUpdateParameters{
AccountPropertiesUpdateParameters: &storage.AccountPropertiesUpdateParameters{
CustomDomain: customDomain,
},
}
_, err := client.Update(ctx, resourceGroupName, storageAccountName, opts)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account Custom Domain %q: %+v", storageAccountName, err)
}
}
if d.HasChange("enable_https_traffic_only") {
enableHTTPSTrafficOnly := d.Get("enable_https_traffic_only").(bool)
opts := storage.AccountUpdateParameters{
AccountPropertiesUpdateParameters: &storage.AccountPropertiesUpdateParameters{
EnableHTTPSTrafficOnly: &enableHTTPSTrafficOnly,
},
}
_, err := client.Update(ctx, resourceGroupName, storageAccountName, opts)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account enable_https_traffic_only %q: %+v", storageAccountName, err)
}
d.SetPartial("enable_https_traffic_only")
}
d.Partial(false)
return nil
}
func resourceArmStorageAccountRead(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
client := meta.(*ArmClient).storageServiceClient
endpointSuffix := meta.(*ArmClient).environment.StorageEndpointSuffix
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
name := id.Path["storageAccounts"]
resGroup := id.ResourceGroup
resp, err := client.GetProperties(ctx, resGroup, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
d.SetId("")
return nil
}
return fmt.Errorf("Error reading the state of AzureRM Storage Account %q: %+v", name, err)
}
keys, err := client.ListKeys(ctx, resGroup, name)
if err != nil {
return err
}
accessKeys := *keys.Keys
d.Set("name", resp.Name)
d.Set("resource_group_name", resGroup)
if location := resp.Location; location != nil {
d.Set("location", azureRMNormalizeLocation(*location))
}
d.Set("account_kind", resp.Kind)
if sku := resp.Sku; sku != nil {
d.Set("account_type", sku.Name)
d.Set("account_tier", sku.Tier)
d.Set("account_replication_type", strings.Split(fmt.Sprintf("%v", sku.Name), "_")[1])
}
if props := resp.AccountProperties; props != nil {
d.Set("access_tier", props.AccessTier)
d.Set("enable_https_traffic_only", props.EnableHTTPSTrafficOnly)
if customDomain := props.CustomDomain; customDomain != nil {
if err := d.Set("custom_domain", flattenStorageAccountCustomDomain(customDomain)); err != nil {
return fmt.Errorf("Error flattening `custom_domain`: %+v", err)
}
}
if encryption := props.Encryption; encryption != nil {
if services := encryption.Services; services != nil {
if blob := services.Blob; blob != nil {
d.Set("enable_blob_encryption", blob.Enabled)
}
if file := services.File; file != nil {
d.Set("enable_file_encryption", file.Enabled)
}
}
d.Set("account_encryption_source", string(encryption.KeySource))
}
// Computed
d.Set("primary_location", props.PrimaryLocation)
d.Set("secondary_location", props.SecondaryLocation)
if len(accessKeys) > 0 {
pcs := fmt.Sprintf("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=%s", *resp.Name, *accessKeys[0].Value, endpointSuffix)
d.Set("primary_connection_string", pcs)
}
if len(accessKeys) > 1 {
scs := fmt.Sprintf("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=%s", *resp.Name, *accessKeys[1].Value, endpointSuffix)
d.Set("secondary_connection_string", scs)
}
if endpoints := props.PrimaryEndpoints; endpoints != nil {
d.Set("primary_blob_endpoint", endpoints.Blob)
d.Set("primary_queue_endpoint", endpoints.Queue)
d.Set("primary_table_endpoint", endpoints.Table)
d.Set("primary_file_endpoint", endpoints.File)
pscs := fmt.Sprintf("DefaultEndpointsProtocol=https;BlobEndpoint=%s;AccountName=%s;AccountKey=%s",
*endpoints.Blob, *resp.Name, *accessKeys[0].Value)
d.Set("primary_blob_connection_string", pscs)
}
if endpoints := props.SecondaryEndpoints; endpoints != nil {
if blob := endpoints.Blob; blob != nil {
d.Set("secondary_blob_endpoint", blob)
sscs := fmt.Sprintf("DefaultEndpointsProtocol=https;BlobEndpoint=%s;AccountName=%s;AccountKey=%s",
*blob, *resp.Name, *accessKeys[1].Value)
d.Set("secondary_blob_connection_string", sscs)
} else {
d.Set("secondary_blob_endpoint", "")
d.Set("secondary_blob_connection_string", "")
}
if endpoints.Queue != nil {
d.Set("secondary_queue_endpoint", endpoints.Queue)
} else {
d.Set("secondary_queue_endpoint", "")
}
if endpoints.Table != nil {
d.Set("secondary_table_endpoint", endpoints.Table)
} else {
d.Set("secondary_table_endpoint", "")
}
}
}
d.Set("primary_access_key", accessKeys[0].Value)
d.Set("secondary_access_key", accessKeys[1].Value)
flattenAndSetTags(d, resp.Tags)
return nil
}
func resourceArmStorageAccountDelete(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
client := meta.(*ArmClient).storageServiceClient
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
name := id.Path["storageAccounts"]
resGroup := id.ResourceGroup
_, err = client.Delete(ctx, resGroup, name)
if err != nil {
return fmt.Errorf("Error issuing AzureRM delete request for storage account %q: %+v", name, err)
}
return nil
}
func expandStorageAccountCustomDomain(d *schema.ResourceData) *storage.CustomDomain {
domains := d.Get("custom_domain").([]interface{})
if domains == nil || len(domains) == 0 {
return &storage.CustomDomain{
Name: utils.String(""),
}
}
domain := domains[0].(map[string]interface{})
name := domain["name"].(string)
useSubDomain := domain["use_subdomain"].(bool)
return &storage.CustomDomain{
Name: utils.String(name),
UseSubDomain: utils.Bool(useSubDomain),
}
}
func flattenStorageAccountCustomDomain(input *storage.CustomDomain) []interface{} {
domain := make(map[string]interface{}, 0)
domain["name"] = *input.Name
// use_subdomain isn't returned
return []interface{}{domain}
}
func validateArmStorageAccountName(v interface{}, k string) (ws []string, es []error) {
input := v.(string)
if !regexp.MustCompile(`\A([a-z0-9]{3,24})\z`).MatchString(input) {
es = append(es, fmt.Errorf("name can only consist of lowercase letters and numbers, and must be between 3 and 24 characters long"))
}
return
}
func validateArmStorageAccountType(v interface{}, k string) (ws []string, es []error) {
validAccountTypes := []string{"standard_lrs", "standard_zrs",
"standard_grs", "standard_ragrs", "premium_lrs"}
input := strings.ToLower(v.(string))
for _, valid := range validAccountTypes {
if valid == input {
return
}
}
es = append(es, fmt.Errorf("Invalid storage account type %q", input))
return
}