forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
media_services_account_resource.go
387 lines (323 loc) · 11 KB
/
media_services_account_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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package media
import (
"fmt"
"log"
"regexp"
"time"
"github.com/Azure/azure-sdk-for-go/services/mediaservices/mgmt/2021-05-01/media"
"github.com/hashicorp/go-azure-helpers/lang/response"
"github.com/kevinklinger/terraform-provider-azurerm/v2/helpers/azure"
"github.com/kevinklinger/terraform-provider-azurerm/v2/helpers/tf"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/clients"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/services/media/parse"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tags"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/pluginsdk"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/suppress"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/validation"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/timeouts"
"github.com/kevinklinger/terraform-provider-azurerm/v2/utils"
)
func resourceMediaServicesAccount() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceMediaServicesAccountCreateUpdate,
Read: resourceMediaServicesAccountRead,
Update: resourceMediaServicesAccountCreateUpdate,
Delete: resourceMediaServicesAccountDelete,
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),
},
Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := parse.MediaServiceID(id)
return err
}),
Schema: map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(
regexp.MustCompile("^[-a-z0-9]{3,24}$"),
"Media Services Account name must be 3 - 24 characters long, contain only lowercase letters and numbers.",
),
},
"location": azure.SchemaLocation(),
"resource_group_name": azure.SchemaResourceGroupName(),
"storage_account": {
Type: pluginsdk.TypeSet,
Required: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"id": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: azure.ValidateResourceID,
},
"is_primary": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: false,
},
},
},
},
//lintignore:XS003
"identity": {
Type: pluginsdk.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"principal_id": {
Type: pluginsdk.TypeString,
Computed: true,
},
"tenant_id": {
Type: pluginsdk.TypeString,
Computed: true,
},
"type": {
Type: pluginsdk.TypeString,
Optional: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: validation.StringInSlice([]string{
string(media.ManagedIdentityTypeSystemAssigned),
}, true),
},
},
},
},
"storage_authentication_type": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{
string(media.StorageAuthenticationSystem),
string(media.StorageAuthenticationManagedIdentity),
}, true),
},
"key_delivery_access_control": {
Type: pluginsdk.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"default_action": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
string(media.DefaultActionDeny),
string(media.DefaultActionAllow),
}, true),
},
"ip_allow_list": {
Type: pluginsdk.TypeSet,
Optional: true,
Elem: &pluginsdk.Schema{
Type: pluginsdk.TypeString,
ValidateFunc: validation.StringIsNotEmpty,
},
},
},
},
},
"tags": tags.Schema(),
},
}
}
func resourceMediaServicesAccountCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Media.ServicesClient
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
resourceId := parse.NewMediaServiceID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string))
if d.IsNewResource() {
existing, err := client.Get(ctx, resourceId.ResourceGroup, resourceId.Name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("checking for existing %s: %+v", resourceId, err)
}
}
if !utils.ResponseWasNotFound(existing.Response) {
return tf.ImportAsExistsError("azurerm_media_services_account", resourceId.ID())
}
}
location := azure.NormalizeLocation(d.Get("location").(string))
t := d.Get("tags").(map[string]interface{})
storageAccountsRaw := d.Get("storage_account").(*pluginsdk.Set).List()
storageAccounts, err := expandMediaServicesAccountStorageAccounts(storageAccountsRaw)
if err != nil {
return err
}
parameters := media.Service{
ServiceProperties: &media.ServiceProperties{
StorageAccounts: storageAccounts,
},
Location: utils.String(location),
Tags: tags.Expand(t),
}
if _, ok := d.GetOk("identity"); ok {
parameters.Identity = expandAzureRmMediaServiceIdentity(d)
}
if v, ok := d.GetOk("storage_authentication_type"); ok {
parameters.StorageAuthentication = media.StorageAuthentication(v.(string))
}
if keyDelivery, ok := d.GetOk("key_delivery_access_control"); ok {
parameters.KeyDelivery = expandKeyDelivery(keyDelivery.([]interface{}))
}
if _, err := client.CreateOrUpdate(ctx, resourceId.ResourceGroup, resourceId.Name, parameters); err != nil {
return fmt.Errorf("creating %s: %+v", resourceId, err)
}
d.SetId(resourceId.ID())
return resourceMediaServicesAccountRead(d, meta)
}
func resourceMediaServicesAccountRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Media.ServicesClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.MediaServiceID(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("[INFO] Media Services Account %q was not found in Resource Group %q - removing from state", id.Name, id.ResourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("retrieving Media Services Account %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, 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))
}
props := resp.ServiceProperties
if props != nil {
accounts := flattenMediaServicesAccountStorageAccounts(props.StorageAccounts)
if e := d.Set("storage_account", accounts); e != nil {
return fmt.Errorf("flattening `storage_account`: %s", e)
}
d.Set("storage_authentication_type", string(props.StorageAuthentication))
}
if err := d.Set("identity", flattenAzureRmMediaServicedentity(resp.Identity)); err != nil {
return fmt.Errorf("flattening `identity`: %s", err)
}
if err := d.Set("key_delivery_access_control", flattenKeyDelivery(resp.KeyDelivery)); err != nil {
return fmt.Errorf("flattening `key_delivery_access_control`: %s", err)
}
return tags.FlattenAndSet(d, resp.Tags)
}
func resourceMediaServicesAccountDelete(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Media.ServicesClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.MediaServiceID(d.Id())
if err != nil {
return err
}
resp, err := client.Delete(ctx, id.ResourceGroup, id.Name)
if err != nil {
if response.WasNotFound(resp.Response) {
return nil
}
return fmt.Errorf("issuing AzureRM delete request for Media Services Account '%s': %+v", id.Name, err)
}
return nil
}
func expandMediaServicesAccountStorageAccounts(input []interface{}) (*[]media.StorageAccount, error) {
results := make([]media.StorageAccount, 0)
foundPrimary := false
for _, accountMapRaw := range input {
accountMap := accountMapRaw.(map[string]interface{})
id := accountMap["id"].(string)
storageType := media.StorageAccountTypeSecondary
if accountMap["is_primary"].(bool) {
if foundPrimary {
return nil, fmt.Errorf("Only one Storage Account can be set as Primary")
}
storageType = media.StorageAccountTypePrimary
foundPrimary = true
}
storageAccount := media.StorageAccount{
ID: utils.String(id),
Type: storageType,
}
results = append(results, storageAccount)
}
return &results, nil
}
func flattenMediaServicesAccountStorageAccounts(input *[]media.StorageAccount) []interface{} {
if input == nil {
return []interface{}{}
}
results := make([]interface{}, 0)
for _, storageAccount := range *input {
output := make(map[string]interface{})
if storageAccount.ID != nil {
output["id"] = *storageAccount.ID
}
output["is_primary"] = storageAccount.Type == media.StorageAccountTypePrimary
results = append(results, output)
}
return results
}
func expandAzureRmMediaServiceIdentity(d *pluginsdk.ResourceData) *media.ServiceIdentity {
identities := d.Get("identity").([]interface{})
if identities[0] == nil {
return nil
}
identity := identities[0].(map[string]interface{})
identityType := identity["type"].(string)
return &media.ServiceIdentity{
Type: media.ManagedIdentityType(identityType),
}
}
func flattenAzureRmMediaServicedentity(identity *media.ServiceIdentity) []interface{} {
if identity == nil {
return make([]interface{}, 0)
}
result := make(map[string]interface{})
result["type"] = string(identity.Type)
if identity.PrincipalID != nil {
result["principal_id"] = *identity.PrincipalID
}
if identity.TenantID != nil {
result["tenant_id"] = *identity.TenantID
}
return []interface{}{result}
}
func expandKeyDelivery(input []interface{}) *media.KeyDelivery {
if len(input) == 0 {
return nil
}
keyDelivery := input[0].(map[string]interface{})
defaultAction := keyDelivery["default_action"].(string)
var ipAllowList *[]string
if v := keyDelivery["ip_allow_list"]; v != nil {
ips := keyDelivery["ip_allow_list"].(*pluginsdk.Set).List()
ipAllowList = utils.ExpandStringSlice(ips)
}
return &media.KeyDelivery{
AccessControl: &media.AccessControl{
DefaultAction: media.DefaultAction(defaultAction),
IPAllowList: ipAllowList,
},
}
}
func flattenKeyDelivery(input *media.KeyDelivery) []interface{} {
if input == nil && input.AccessControl != nil {
return make([]interface{}, 0)
}
return []interface{}{
map[string]interface{}{
"default_action": string(input.AccessControl.DefaultAction),
"ip_allow_list": utils.FlattenStringSlice(input.AccessControl.IPAllowList),
},
}
}