forked from hashicorp/terraform-provider-azurerm
/
resource_arm_container_registry.go
501 lines (412 loc) · 16.7 KB
/
resource_arm_container_registry.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
package azurerm
import (
"fmt"
"log"
"regexp"
"strings"
"github.com/Azure/azure-sdk-for-go/services/containerregistry/mgmt/2017-10-01/containerregistry"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response"
"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/utils"
)
func resourceArmContainerRegistry() *schema.Resource {
return &schema.Resource{
Create: resourceArmContainerRegistryCreate,
Read: resourceArmContainerRegistryRead,
Update: resourceArmContainerRegistryUpdate,
Delete: resourceArmContainerRegistryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
MigrateState: resourceAzureRMContainerRegistryMigrateState,
SchemaVersion: 2,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateAzureRMContainerRegistryName,
},
"resource_group_name": resourceGroupNameSchema(),
"location": locationSchema(),
"sku": {
Type: schema.TypeString,
Optional: true,
Default: string(containerregistry.Classic),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
ValidateFunc: validation.StringInSlice([]string{
string(containerregistry.Classic),
string(containerregistry.Basic),
string(containerregistry.Standard),
string(containerregistry.Premium),
}, true),
},
"admin_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"georeplication_locations": {
Type: schema.TypeSet,
MinItems: 1,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validate.NoEmptyStrings,
},
Set: azureRMHashLocation,
},
"storage_account_id": {
Type: schema.TypeString,
Optional: true,
},
"storage_account": {
Type: schema.TypeList,
Optional: true,
Deprecated: "`storage_account` has been replaced by `storage_account_id`.",
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"access_key": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
},
},
},
},
"login_server": {
Type: schema.TypeString,
Computed: true,
},
"admin_username": {
Type: schema.TypeString,
Computed: true,
},
"admin_password": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"tags": tagsSchema(),
},
CustomizeDiff: func(d *schema.ResourceDiff, v interface{}) error {
sku := d.Get("sku").(string)
geoReplicationLocations := d.Get("georeplication_locations").(*schema.Set)
// if locations have been specified for geo-replication then, the SKU has to be Premium
if geoReplicationLocations != nil && geoReplicationLocations.Len() > 0 && !strings.EqualFold(sku, string(containerregistry.Premium)) {
return fmt.Errorf("ACR geo-replication can only be applied when using the Premium Sku.")
}
return nil
},
}
}
func resourceArmContainerRegistryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).containerRegistryClient
ctx := meta.(*ArmClient).StopContext
log.Printf("[INFO] preparing arguments for AzureRM Container Registry creation.")
resourceGroup := d.Get("resource_group_name").(string)
name := d.Get("name").(string)
if requireResourcesToBeImported && 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 Container Registry %q (Resource Group %q): %s", name, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_container_registry", *existing.ID)
}
}
location := azureRMNormalizeLocation(d.Get("location").(string))
sku := d.Get("sku").(string)
adminUserEnabled := d.Get("admin_enabled").(bool)
tags := d.Get("tags").(map[string]interface{})
geoReplicationLocations := d.Get("georeplication_locations").(*schema.Set)
parameters := containerregistry.Registry{
Location: &location,
Sku: &containerregistry.Sku{
Name: containerregistry.SkuName(sku),
Tier: containerregistry.SkuTier(sku),
},
RegistryProperties: &containerregistry.RegistryProperties{
AdminUserEnabled: utils.Bool(adminUserEnabled),
},
Tags: expandTags(tags),
}
if v, ok := d.GetOk("storage_account_id"); ok {
if strings.ToLower(sku) != strings.ToLower(string(containerregistry.Classic)) {
return fmt.Errorf("`storage_account_id` can only be specified for a Classic (unmanaged) Sku.")
}
parameters.StorageAccount = &containerregistry.StorageAccountProperties{
ID: utils.String(v.(string)),
}
} else {
if strings.ToLower(sku) == strings.ToLower(string(containerregistry.Classic)) {
return fmt.Errorf("`storage_account_id` must be specified for a Classic (unmanaged) Sku.")
}
}
future, err := client.Create(ctx, resourceGroup, name, parameters)
if err != nil {
return fmt.Errorf("Error creating Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for creation of Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
// locations have been specified for geo-replication
if geoReplicationLocations != nil && geoReplicationLocations.Len() > 0 {
// the ACR is being created so no previous geo-replication locations
oldGeoReplicationLocations := []interface{}{}
err = applyGeoReplicationLocations(meta, resourceGroup, name, oldGeoReplicationLocations, geoReplicationLocations.List())
if err != nil {
return fmt.Errorf("Error applying geo replications for Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}
read, err := client.Get(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error retrieving Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Container Registry %q (resource group %q) ID", name, resourceGroup)
}
d.SetId(*read.ID)
return resourceArmContainerRegistryRead(d, meta)
}
func resourceArmContainerRegistryUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).containerRegistryClient
ctx := meta.(*ArmClient).StopContext
log.Printf("[INFO] preparing arguments for AzureRM Container Registry update.")
resourceGroup := d.Get("resource_group_name").(string)
name := d.Get("name").(string)
sku := d.Get("sku").(string)
adminUserEnabled := d.Get("admin_enabled").(bool)
tags := d.Get("tags").(map[string]interface{})
old, new := d.GetChange("georeplication_locations")
hasGeoReplicationChanges := d.HasChange("georeplication_locations")
oldGeoReplicationLocations := old.(*schema.Set)
newGeoReplicationLocations := new.(*schema.Set)
parameters := containerregistry.RegistryUpdateParameters{
RegistryPropertiesUpdateParameters: &containerregistry.RegistryPropertiesUpdateParameters{
AdminUserEnabled: utils.Bool(adminUserEnabled),
},
Sku: &containerregistry.Sku{
Name: containerregistry.SkuName(sku),
Tier: containerregistry.SkuTier(sku),
},
Tags: expandTags(tags),
}
if v, ok := d.GetOk("storage_account_id"); ok {
if !strings.EqualFold(sku, string(containerregistry.Classic)) {
return fmt.Errorf("`storage_account_id` can only be specified for a Classic (unmanaged) Sku.")
}
parameters.StorageAccount = &containerregistry.StorageAccountProperties{
ID: utils.String(v.(string)),
}
} else {
if strings.EqualFold(sku, string(containerregistry.Classic)) {
return fmt.Errorf("`storage_account_id` must be specified for a Classic (unmanaged) Sku.")
}
}
// geo replication is only supported by Premium Sku
if hasGeoReplicationChanges && newGeoReplicationLocations.Len() > 0 && !strings.EqualFold(sku, string(containerregistry.Premium)) {
return fmt.Errorf("ACR geo-replication can only be applied when using the Premium Sku.")
}
// if the registry had replications and is updated to another Sku than premium - remove old locations
if !strings.EqualFold(sku, string(containerregistry.Premium)) && oldGeoReplicationLocations != nil && oldGeoReplicationLocations.Len() > 0 {
err := applyGeoReplicationLocations(meta, resourceGroup, name, oldGeoReplicationLocations.List(), newGeoReplicationLocations.List())
if err != nil {
return fmt.Errorf("Error applying geo replications for Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}
future, err := client.Update(ctx, resourceGroup, name, parameters)
if err != nil {
return fmt.Errorf("Error updating Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for update of Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if strings.EqualFold(sku, string(containerregistry.Premium)) && hasGeoReplicationChanges {
err = applyGeoReplicationLocations(meta, resourceGroup, name, oldGeoReplicationLocations.List(), newGeoReplicationLocations.List())
if err != nil {
return fmt.Errorf("Error applying geo replications for Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}
read, err := client.Get(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error retrieving Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Container Registry %q (resource group %q) ID", name, resourceGroup)
}
d.SetId(*read.ID)
return resourceArmContainerRegistryRead(d, meta)
}
func applyGeoReplicationLocations(meta interface{}, resourceGroup string, name string, oldGeoReplicationLocations []interface{}, newGeoReplicationLocations []interface{}) error {
replicationClient := meta.(*ArmClient).containerRegistryReplicationsClient
ctx := meta.(*ArmClient).StopContext
log.Printf("[INFO] preparing to apply geo-replications for AzureRM Container Registry.")
createLocations := make(map[string]bool)
// loop on the new location values
for _, nl := range newGeoReplicationLocations {
newLocation := azureRMNormalizeLocation(nl)
createLocations[newLocation] = true // the location needs to be created
}
// loop on the old location values
for _, ol := range oldGeoReplicationLocations {
// oldLocation was created from a previous deployment
oldLocation := azureRMNormalizeLocation(ol)
// if the list of locations to create already contains the location
if _, ok := createLocations[oldLocation]; ok {
createLocations[oldLocation] = false // the location do not need to be created, it already exists
}
}
// create new geo-replication locations
for locationToCreate := range createLocations {
// if false, the location does not need to be created, continue
if !createLocations[locationToCreate] {
continue
}
// create the new replication location
replication := containerregistry.Replication{
Location: &locationToCreate,
Name: &locationToCreate,
}
future, err := replicationClient.Create(ctx, resourceGroup, name, locationToCreate, replication)
if err != nil {
return fmt.Errorf("Error creating Container Registry Replication %q (Resource Group %q, Location %q): %+v", name, resourceGroup, locationToCreate, err)
}
if err = future.WaitForCompletionRef(ctx, replicationClient.Client); err != nil {
return fmt.Errorf("Error waiting for creation of Container Registry Replication %q (Resource Group %q, Location %q): %+v", name, resourceGroup, locationToCreate, err)
}
}
// loop on the list of previously deployed locations
for _, ol := range oldGeoReplicationLocations {
oldLocation := azureRMNormalizeLocation(ol)
// if the old location is still in the list of locations, then continue
if _, ok := createLocations[oldLocation]; ok {
continue
}
// the old location is not in the list of locations, delete it
future, err := replicationClient.Delete(ctx, resourceGroup, name, oldLocation)
if err != nil {
return fmt.Errorf("Error deleting Container Registry Replication %q (Resource Group %q, Location %q): %+v", name, resourceGroup, oldLocation, err)
}
if err = future.WaitForCompletionRef(ctx, replicationClient.Client); err != nil {
return fmt.Errorf("Error waiting for deletion of Container Registry Replication %q (Resource Group %q, Location %q): %+v", name, resourceGroup, oldLocation, err)
}
}
return nil
}
func resourceArmContainerRegistryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).containerRegistryClient
replicationClient := meta.(*ArmClient).containerRegistryReplicationsClient
ctx := meta.(*ArmClient).StopContext
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
name := id.Path["registries"]
resp, err := client.Get(ctx, resourceGroup, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Container Registry %q was not found in Resource Group %q", name, resourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("Error making Read request on Azure Container Registry %q (Resource Group %q): %+v", name, resourceGroup, err)
}
d.Set("name", resp.Name)
d.Set("resource_group_name", resourceGroup)
location := resp.Location
if location != nil {
d.Set("location", azureRMNormalizeLocation(*location))
}
d.Set("admin_enabled", resp.AdminUserEnabled)
d.Set("login_server", resp.LoginServer)
if sku := resp.Sku; sku != nil {
d.Set("sku", string(sku.Tier))
}
if account := resp.StorageAccount; account != nil {
d.Set("storage_account_id", account.ID)
}
if *resp.AdminUserEnabled {
credsResp, errList := client.ListCredentials(ctx, resourceGroup, name)
if errList != nil {
return fmt.Errorf("Error making Read request on Azure Container Registry %s for Credentials: %s", name, errList)
}
d.Set("admin_username", credsResp.Username)
for _, v := range *credsResp.Passwords {
d.Set("admin_password", v.Value)
break
}
} else {
d.Set("admin_username", "")
d.Set("admin_password", "")
}
flattenAndSetTags(d, resp.Tags)
replications, err := replicationClient.List(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error making Read request on Azure Container Registry %s for replications: %s", name, err)
}
replicationValues := replications.Values()
// if there is more than one location (the main one and the replicas)
if replicationValues != nil || len(replicationValues) > 1 {
georeplication_locations := &schema.Set{F: schema.HashString}
for _, value := range replicationValues {
if value.Location != nil {
valueLocation := azureRMNormalizeLocation(*value.Location)
if location != nil && valueLocation != azureRMNormalizeLocation(*location) {
georeplication_locations.Add(valueLocation)
}
}
}
d.Set("georeplication_locations", georeplication_locations)
}
return nil
}
func resourceArmContainerRegistryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).containerRegistryClient
ctx := meta.(*ArmClient).StopContext
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
name := id.Path["registries"]
future, err := client.Delete(ctx, resourceGroup, name)
if err != nil {
if response.WasNotFound(future.Response()) {
return nil
}
return fmt.Errorf("Error issuing Azure ARM delete request of Container Registry '%s': %+v", name, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
if response.WasNotFound(future.Response()) {
return nil
}
return fmt.Errorf("Error issuing Azure ARM delete request of Container Registry '%s': %+v", name, err)
}
return nil
}
func validateAzureRMContainerRegistryName(v interface{}, k string) (warnings []string, errors []error) {
value := v.(string)
if !regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"alpha numeric characters only are allowed in %q: %q", k, value))
}
if 5 > len(value) {
errors = append(errors, fmt.Errorf("%q cannot be less than 5 characters: %q", k, value))
}
if len(value) >= 50 {
errors = append(errors, fmt.Errorf("%q cannot be longer than 50 characters: %q %d", k, value, len(value)))
}
return warnings, errors
}