-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
storage_table_resource.go
343 lines (286 loc) · 10.7 KB
/
storage_table_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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package storage
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-provider-azurerm/helpers/tf"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/migration"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
"github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts"
"github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables"
)
func resourceStorageTable() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceStorageTableCreate,
Read: resourceStorageTableRead,
Delete: resourceStorageTableDelete,
Update: resourceStorageTableUpdate,
Importer: helpers.ImporterValidatingStorageResourceId(func(id, storageDomainSuffix string) error {
_, err := tables.ParseTableID(id, storageDomainSuffix)
return err
}),
SchemaVersion: 2,
StateUpgraders: pluginsdk.StateUpgrades(map[int]pluginsdk.StateUpgrade{
0: migration.TableV0ToV1{},
1: migration.TableV1ToV2{},
}),
Timeouts: &pluginsdk.ResourceTimeout{
Create: pluginsdk.DefaultTimeout(30 * time.Minute),
Read: pluginsdk.DefaultTimeout(5 * time.Minute),
Update: pluginsdk.DefaultTimeout(30 * time.Minute),
Delete: pluginsdk.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.StorageTableName,
},
"storage_account_name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.StorageAccountName,
},
"acl": {
Type: pluginsdk.TypeSet,
Optional: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"id": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"access_policy": {
Type: pluginsdk.TypeList,
Optional: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"start": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"expiry": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"permissions": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},
},
},
},
},
},
},
},
}
}
func resourceStorageTableCreate(d *pluginsdk.ResourceData, meta interface{}) error {
storageClient := meta.(*clients.Client).Storage
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()
tableName := d.Get("name").(string)
accountName := d.Get("storage_account_name").(string)
aclsRaw := d.Get("acl").(*pluginsdk.Set).List()
acls := expandStorageTableACLs(aclsRaw)
account, err := storageClient.FindAccount(ctx, subscriptionId, accountName)
if err != nil {
return fmt.Errorf("retrieving Account %q for Table %q: %s", accountName, tableName, err)
}
if account == nil {
return fmt.Errorf("locating Storage Account %q", accountName)
}
tablesDataPlaneClient, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod())
if err != nil {
return fmt.Errorf("building Tables Client: %s", err)
}
// Determine the table endpoint, so we can build a data plane ID
endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeTable)
if err != nil {
return fmt.Errorf("determining Tables endpoint: %v", err)
}
// Parse the table endpoint as a data plane account ID
accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix)
if err != nil {
return fmt.Errorf("parsing Account ID: %v", err)
}
id := tables.NewTableID(*accountId, tableName)
exists, err := tablesDataPlaneClient.Exists(ctx, tableName)
if err != nil {
return fmt.Errorf("checking for existing %s: %v", id, err)
}
if exists != nil && *exists {
return tf.ImportAsExistsError("azurerm_storage_table", id.ID())
}
if err = tablesDataPlaneClient.Create(ctx, tableName); err != nil {
return fmt.Errorf("creating %s: %v", id, err)
}
d.SetId(id.ID())
// Setting ACLs only supports shared key authentication (@manicminer, 2024-02-29)
aclClient, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth())
if err != nil {
return fmt.Errorf("building Tables Client: %v", err)
}
if err = aclClient.UpdateACLs(ctx, tableName, acls); err != nil {
return fmt.Errorf("setting ACLs for %s: %v", id, err)
}
return resourceStorageTableRead(d, meta)
}
func resourceStorageTableRead(d *pluginsdk.ResourceData, meta interface{}) error {
storageClient := meta.(*clients.Client).Storage
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := tables.ParseTableID(d.Id(), storageClient.StorageDomainSuffix)
if err != nil {
return err
}
account, err := storageClient.FindAccount(ctx, subscriptionId, id.AccountId.AccountName)
if err != nil {
return fmt.Errorf("retrieving Storage Account %q for Table %q: %v", id.AccountId.AccountName, id.TableName, err)
}
if account == nil {
log.Printf("Unable to determine Resource Group for Storage Storage Table %q (Account %s) - assuming removed & removing from state", id.TableName, id.AccountId.AccountName)
d.SetId("")
return nil
}
client, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod())
if err != nil {
return fmt.Errorf("building Tables Client: %v", err)
}
exists, err := client.Exists(ctx, id.TableName)
if err != nil {
return fmt.Errorf("retrieving %s: %v", id, err)
}
if exists == nil || !*exists {
log.Printf("[DEBUG] %s not found, removing from state", id)
d.SetId("")
return nil
}
// Retrieving ACLs only supports shared key authentication (@manicminer, 2024-02-29)
aclClient, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth())
if err != nil {
return fmt.Errorf("building Tables Client: %v", err)
}
acls, err := aclClient.GetACLs(ctx, id.TableName)
if err != nil {
return fmt.Errorf("retrieving ACLs for %s: %v", id, err)
}
d.Set("name", id.TableName)
d.Set("storage_account_name", id.AccountId.AccountName)
if err = d.Set("acl", flattenStorageTableACLs(acls)); err != nil {
return fmt.Errorf("setting `acl`: %v", err)
}
return nil
}
func resourceStorageTableDelete(d *pluginsdk.ResourceData, meta interface{}) error {
storageClient := meta.(*clients.Client).Storage
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := tables.ParseTableID(d.Id(), storageClient.StorageDomainSuffix)
if err != nil {
return err
}
account, err := storageClient.FindAccount(ctx, subscriptionId, id.AccountId.AccountName)
if err != nil {
return fmt.Errorf("retrieving Storage Account %q for Table %q: %v", id.AccountId.AccountName, id.TableName, err)
}
if account == nil {
return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName)
}
client, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod())
if err != nil {
return fmt.Errorf("building Tables Client: %v", err)
}
if err = client.Delete(ctx, id.TableName); err != nil {
return fmt.Errorf("deleting %s: %v", id, err)
}
return nil
}
func resourceStorageTableUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
storageClient := meta.(*clients.Client).Storage
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := tables.ParseTableID(d.Id(), storageClient.StorageDomainSuffix)
if err != nil {
return err
}
account, err := storageClient.FindAccount(ctx, subscriptionId, id.AccountId.AccountName)
if err != nil {
return fmt.Errorf("retrieving Storage Account %q for Table %q: %v", id.AccountId.AccountName, id.TableName, err)
}
if account == nil {
return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName)
}
if d.HasChange("acl") {
log.Printf("[DEBUG] Updating ACLs for %s", id)
aclsRaw := d.Get("acl").(*pluginsdk.Set).List()
acls := expandStorageTableACLs(aclsRaw)
// Setting ACLs only supports shared key authentication (@manicminer, 2024-02-29)
aclClient, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth())
if err != nil {
return fmt.Errorf("building Tables Client: %v", err)
}
if err = aclClient.UpdateACLs(ctx, id.TableName, acls); err != nil {
return fmt.Errorf("updating ACLs for %s: %v", id, err)
}
log.Printf("[DEBUG] Updated ACLs for %s", id)
}
return resourceStorageTableRead(d, meta)
}
func expandStorageTableACLs(input []interface{}) []tables.SignedIdentifier {
results := make([]tables.SignedIdentifier, 0)
for _, v := range input {
vals := v.(map[string]interface{})
policies := vals["access_policy"].([]interface{})
policy := policies[0].(map[string]interface{})
identifier := tables.SignedIdentifier{
Id: vals["id"].(string),
AccessPolicy: tables.AccessPolicy{
Start: policy["start"].(string),
Expiry: policy["expiry"].(string),
Permission: policy["permissions"].(string),
},
}
results = append(results, identifier)
}
return results
}
func flattenStorageTableACLs(input *[]tables.SignedIdentifier) []interface{} {
result := make([]interface{}, 0)
if input == nil {
return result
}
for _, v := range *input {
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
}