forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared_image_version_resource.go
354 lines (293 loc) · 12.3 KB
/
shared_image_version_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
package compute
import (
"context"
"fmt"
"log"
"time"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2020-12-01/compute"
"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/location"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/services/compute/parse"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/services/compute/validate"
"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/validation"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/timeouts"
"github.com/kevinklinger/terraform-provider-azurerm/v2/utils"
)
func resourceSharedImageVersion() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceSharedImageVersionCreateUpdate,
Read: resourceSharedImageVersionRead,
Update: resourceSharedImageVersionCreateUpdate,
Delete: resourceSharedImageVersionDelete,
Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := parse.SharedImageVersionID(id)
return err
}),
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.SharedImageVersionName,
},
"gallery_name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.SharedImageGalleryName,
},
"image_name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.SharedImageName,
},
"location": azure.SchemaLocation(),
"resource_group_name": azure.SchemaResourceGroupName(),
"target_region": {
Type: pluginsdk.TypeSet,
Required: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
StateFunc: location.StateFunc,
DiffSuppressFunc: location.DiffSuppressFunc,
},
"regional_replica_count": {
Type: pluginsdk.TypeInt,
Required: true,
},
// The Service API doesn't support to update `storage_account_type`. So it has to recreate the resource for updating `storage_account_type`.
// However, `ForceNew` cannot be used since resource would be recreated while adding or removing `target_region`.
// And `CustomizeDiff` also cannot be used since it doesn't support in a `Set`.
// So currently terraform would directly return the error message from Service API while updating this property. If this property needs to be updated, please recreate this pluginsdk.
"storage_account_type": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
string(compute.StorageAccountTypeStandardLRS),
string(compute.StorageAccountTypeStandardZRS),
}, false),
Default: string(compute.StorageAccountTypeStandardLRS),
},
},
},
},
"os_disk_snapshot_id": {
Type: pluginsdk.TypeString,
Optional: true,
ForceNew: true,
ExactlyOneOf: []string{"os_disk_snapshot_id", "managed_image_id"},
// TODO -- add a validation function when snapshot has its own validation function
},
"managed_image_id": {
Type: pluginsdk.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.Any(
validate.ImageID,
validate.VirtualMachineID,
),
ExactlyOneOf: []string{"os_disk_snapshot_id", "managed_image_id"},
},
"exclude_from_latest": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: false,
},
"tags": tags.Schema(),
},
}
}
func resourceSharedImageVersionCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Compute.GalleryImageVersionsClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
imageVersion := d.Get("name").(string)
imageName := d.Get("image_name").(string)
galleryName := d.Get("gallery_name").(string)
resourceGroup := d.Get("resource_group_name").(string)
if d.IsNewResource() {
existing, err := client.Get(ctx, resourceGroup, galleryName, imageName, imageVersion, "")
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("checking for presence of existing Shared Image Version %q (Image %q / Gallery %q / Resource Group %q): %+v", imageVersion, imageName, galleryName, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_shared_image_version", *existing.ID)
}
}
version := compute.GalleryImageVersion{
Location: utils.String(azure.NormalizeLocation(d.Get("location").(string))),
GalleryImageVersionProperties: &compute.GalleryImageVersionProperties{
PublishingProfile: &compute.GalleryImageVersionPublishingProfile{
ExcludeFromLatest: utils.Bool(d.Get("exclude_from_latest").(bool)),
TargetRegions: expandSharedImageVersionTargetRegions(d),
},
StorageProfile: &compute.GalleryImageVersionStorageProfile{},
},
Tags: tags.Expand(d.Get("tags").(map[string]interface{})),
}
if v, ok := d.GetOk("managed_image_id"); ok {
version.GalleryImageVersionProperties.StorageProfile.Source = &compute.GalleryArtifactVersionSource{
ID: utils.String(v.(string)),
}
}
if v, ok := d.GetOk("os_disk_snapshot_id"); ok {
version.GalleryImageVersionProperties.StorageProfile.OsDiskImage = &compute.GalleryOSDiskImage{
Source: &compute.GalleryArtifactVersionSource{
ID: utils.String(v.(string)),
},
}
}
future, err := client.CreateOrUpdate(ctx, resourceGroup, galleryName, imageName, imageVersion, version)
if err != nil {
return fmt.Errorf("creating Shared Image Version %q (Image %q / Gallery %q / Resource Group %q): %+v", imageVersion, imageName, galleryName, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for the creation of Shared Image Version %q (Image %q / Gallery %q / Resource Group %q): %+v", imageVersion, imageName, galleryName, resourceGroup, err)
}
read, err := client.Get(ctx, resourceGroup, galleryName, imageName, imageVersion, "")
if err != nil {
return fmt.Errorf("retrieving Shared Image Version %q (Image %q / Gallery %q / Resource Group %q): %+v", imageVersion, imageName, galleryName, resourceGroup, err)
}
d.SetId(*read.ID)
return resourceSharedImageVersionRead(d, meta)
}
func resourceSharedImageVersionRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Compute.GalleryImageVersionsClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.SharedImageVersionID(d.Id())
if err != nil {
return err
}
resp, err := client.Get(ctx, id.ResourceGroup, id.GalleryName, id.ImageName, id.VersionName, compute.ReplicationStatusTypesReplicationStatus)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Shared Image Version %q (Image %q / Gallery %q / Resource Group %q) was not found - removing from state", id.VersionName, id.ImageName, id.GalleryName, id.ResourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("retrieving Shared Image Version %q (Image %q / Gallery %q / Resource Group %q): %+v", id.VersionName, id.ImageName, id.GalleryName, id.ResourceGroup, err)
}
d.Set("name", resp.Name)
d.Set("image_name", id.ImageName)
d.Set("gallery_name", id.GalleryName)
d.Set("resource_group_name", id.ResourceGroup)
if location := resp.Location; location != nil {
d.Set("location", azure.NormalizeLocation(*location))
}
if props := resp.GalleryImageVersionProperties; props != nil {
if profile := props.PublishingProfile; profile != nil {
d.Set("exclude_from_latest", profile.ExcludeFromLatest)
if err := d.Set("target_region", flattenSharedImageVersionTargetRegions(profile.TargetRegions)); err != nil {
return fmt.Errorf("setting `target_region`: %+v", err)
}
}
if profile := props.StorageProfile; profile != nil {
if source := profile.Source; source != nil {
d.Set("managed_image_id", source.ID)
}
osDiskSnapShotID := ""
if profile.OsDiskImage != nil && profile.OsDiskImage.Source != nil && profile.OsDiskImage.Source.ID != nil {
osDiskSnapShotID = *profile.OsDiskImage.Source.ID
}
d.Set("os_disk_snapshot_id", osDiskSnapShotID)
}
}
return tags.FlattenAndSet(d, resp.Tags)
}
func resourceSharedImageVersionDelete(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Compute.GalleryImageVersionsClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.SharedImageVersionID(d.Id())
if err != nil {
return err
}
future, err := client.Delete(ctx, id.ResourceGroup, id.GalleryName, id.ImageName, id.VersionName)
if err != nil {
return fmt.Errorf("deleting %s: %+v", *id, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for deletion of %s: %+v", *id, err)
}
// @tombuildsstuff: there appears to be an eventual consistency issue here
timeout, _ := ctx.Deadline()
log.Printf("[DEBUG] Waiting for %s to be eventually deleted", *id)
stateConf := &pluginsdk.StateChangeConf{
Pending: []string{"Exists"},
Target: []string{"NotFound"},
Refresh: sharedImageVersionDeleteStateRefreshFunc(ctx, client, *id),
MinTimeout: 10 * time.Second,
ContinuousTargetOccurence: 10,
Timeout: time.Until(timeout),
}
if _, err := stateConf.WaitForStateContext(ctx); err != nil {
return fmt.Errorf("waiting for %s to be deleted: %+v", *id, err)
}
return nil
}
func sharedImageVersionDeleteStateRefreshFunc(ctx context.Context, client *compute.GalleryImageVersionsClient, id parse.SharedImageVersionId) pluginsdk.StateRefreshFunc {
// Whilst the Shared Image Version is deleted quickly, it appears it's not actually finished replicating at this time
// so the deletion of the parent Shared Image fails with "can not delete until nested resources are deleted"
// ergo we need to poll on this for a bit
return func() (interface{}, string, error) {
res, err := client.Get(ctx, id.ResourceGroup, id.GalleryName, id.ImageName, id.VersionName, "")
if err != nil {
if utils.ResponseWasNotFound(res.Response) {
return "NotFound", "NotFound", nil
}
return nil, "", fmt.Errorf("failed to poll to check if the Shared Image Version has been deleted: %+v", err)
}
return res, "Exists", nil
}
}
func expandSharedImageVersionTargetRegions(d *pluginsdk.ResourceData) *[]compute.TargetRegion {
vs := d.Get("target_region").(*pluginsdk.Set)
results := make([]compute.TargetRegion, 0)
for _, v := range vs.List() {
input := v.(map[string]interface{})
name := input["name"].(string)
regionalReplicaCount := input["regional_replica_count"].(int)
storageAccountType := input["storage_account_type"].(string)
output := compute.TargetRegion{
Name: utils.String(name),
RegionalReplicaCount: utils.Int32(int32(regionalReplicaCount)),
StorageAccountType: compute.StorageAccountType(storageAccountType),
}
results = append(results, output)
}
return &results
}
func flattenSharedImageVersionTargetRegions(input *[]compute.TargetRegion) []interface{} {
results := make([]interface{}, 0)
if input != nil {
for _, v := range *input {
output := make(map[string]interface{})
if v.Name != nil {
output["name"] = azure.NormalizeLocation(*v.Name)
}
if v.RegionalReplicaCount != nil {
output["regional_replica_count"] = int(*v.RegionalReplicaCount)
}
output["storage_account_type"] = string(v.StorageAccountType)
results = append(results, output)
}
}
return results
}