forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_arm_virtual_machine_data_disk_attachment.go
302 lines (246 loc) · 9.92 KB
/
resource_arm_virtual_machine_data_disk_attachment.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
package azurerm
import (
"fmt"
"log"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func resourceArmVirtualMachineDataDiskAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceArmVirtualMachineDataDiskAttachmentCreateUpdate,
Read: resourceArmVirtualMachineDataDiskAttachmentRead,
Update: resourceArmVirtualMachineDataDiskAttachmentCreateUpdate,
Delete: resourceArmVirtualMachineDataDiskAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"managed_disk_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
ValidateFunc: azure.ValidateResourceID,
},
"virtual_machine_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateResourceID,
},
"lun": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntAtLeast(0),
},
"caching": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(compute.CachingTypesNone),
string(compute.CachingTypesReadOnly),
string(compute.CachingTypesReadWrite),
}, true),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
},
"create_option": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: string(compute.DiskCreateOptionTypesAttach),
ValidateFunc: validation.StringInSlice([]string{
string(compute.DiskCreateOptionTypesAttach),
string(compute.DiskCreateOptionTypesEmpty),
}, true),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
},
"write_accelerator_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceArmVirtualMachineDataDiskAttachmentCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).vmClient
ctx := meta.(*ArmClient).StopContext
virtualMachineId := d.Get("virtual_machine_id").(string)
parsedVirtualMachineId, err := parseAzureResourceID(virtualMachineId)
if err != nil {
return fmt.Errorf("Error parsing Virtual Machine ID %q: %+v", virtualMachineId, err)
}
resourceGroup := parsedVirtualMachineId.ResourceGroup
virtualMachineName := parsedVirtualMachineId.Path["virtualMachines"]
azureRMLockByName(virtualMachineName, virtualMachineResourceName)
defer azureRMUnlockByName(virtualMachineName, virtualMachineResourceName)
virtualMachine, err := client.Get(ctx, resourceGroup, virtualMachineName, "")
if err != nil {
if utils.ResponseWasNotFound(virtualMachine.Response) {
return fmt.Errorf("Virtual Machine %q (Resource Group %q) was not found", virtualMachineName, resourceGroup)
}
return fmt.Errorf("Error loading Virtual Machine %q (Resource Group %q): %+v", virtualMachineName, resourceGroup, err)
}
managedDiskId := d.Get("managed_disk_id").(string)
managedDisk, err := retrieveDataDiskAttachmentManagedDisk(meta, managedDiskId)
if err != nil {
return fmt.Errorf("Error retrieving Managed Disk %q: %+v", managedDiskId, err)
}
if managedDisk.Sku == nil {
return fmt.Errorf("Error: unable to determine Storage Account Type for Managed Disk %q: %+v", managedDiskId, err)
}
name := *managedDisk.Name
lun := int32(d.Get("lun").(int))
caching := d.Get("caching").(string)
createOption := compute.DiskCreateOptionTypes(d.Get("create_option").(string))
writeAcceleratorEnabled := d.Get("write_accelerator_enabled").(bool)
expandedDisk := compute.DataDisk{
Name: utils.String(name),
Caching: compute.CachingTypes(caching),
CreateOption: createOption,
Lun: utils.Int32(lun),
ManagedDisk: &compute.ManagedDiskParameters{
ID: utils.String(managedDiskId),
StorageAccountType: compute.StorageAccountTypes(string(managedDisk.Sku.Name)),
},
WriteAcceleratorEnabled: utils.Bool(writeAcceleratorEnabled),
}
disks := *virtualMachine.StorageProfile.DataDisks
if d.IsNewResource() {
disks = append(disks, expandedDisk)
} else {
// iterate over the disks and swap it out in-place
existingIndex := -1
for i, disk := range disks {
if *disk.Name == name {
existingIndex = i
break
}
}
if existingIndex == -1 {
return fmt.Errorf("Unable to find Disk %q attached to Virtual Machine %q (Resource Group %q)", name, virtualMachineName, resourceGroup)
}
disks[existingIndex] = expandedDisk
}
virtualMachine.StorageProfile.DataDisks = &disks
// fixes #1600
virtualMachine.Resources = nil
// if there's too many disks we get a 409 back with:
// `The maximum number of data disks allowed to be attached to a VM of this size is 1.`
// which we're intentionally not wrapping, since the errors good.
future, err := client.CreateOrUpdate(ctx, resourceGroup, virtualMachineName, virtualMachine)
if err != nil {
return fmt.Errorf("Error updating Virtual Machine %q (Resource Group %q) with Disk %q: %+v", virtualMachineName, resourceGroup, name, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for Virtual Machine %q (Resource Group %q) to finish updating Disk %q: %+v", virtualMachineName, resourceGroup, name, err)
}
d.SetId(fmt.Sprintf("%s/dataDisks/%s", virtualMachineId, name))
return resourceArmVirtualMachineDataDiskAttachmentRead(d, meta)
}
func resourceArmVirtualMachineDataDiskAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).vmClient
ctx := meta.(*ArmClient).StopContext
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
virtualMachineName := id.Path["virtualMachines"]
name := id.Path["dataDisks"]
virtualMachine, err := client.Get(ctx, resourceGroup, virtualMachineName, "")
if err != nil {
if utils.ResponseWasNotFound(virtualMachine.Response) {
return fmt.Errorf("Virtual Machine %q (Resource Group %q) was not found", virtualMachineName, resourceGroup)
}
return fmt.Errorf("Error loading Virtual Machine %q (Resource Group %q): %+v", virtualMachineName, resourceGroup, err)
}
var disk *compute.DataDisk
if profile := virtualMachine.StorageProfile; profile != nil {
if dataDisks := profile.DataDisks; dataDisks != nil {
for _, dataDisk := range *dataDisks {
// since this field isn't (and shouldn't be) case-sensitive; we're deliberately not using `strings.EqualFold`
if *dataDisk.Name == name {
disk = &dataDisk
break
}
}
}
}
if disk == nil {
log.Printf("[DEBUG] Data Disk %q was not found on Virtual Machine %q (Resource Group %q) - removing from state", name, virtualMachineName, resourceGroup)
d.SetId("")
return nil
}
d.Set("virtual_machine_id", virtualMachine.ID)
d.Set("caching", string(disk.Caching))
d.Set("create_option", string(disk.CreateOption))
d.Set("write_accelerator_enabled", disk.WriteAcceleratorEnabled)
if managedDisk := disk.ManagedDisk; managedDisk != nil {
d.Set("managed_disk_id", managedDisk.ID)
}
if lun := disk.Lun; lun != nil {
d.Set("lun", int(*lun))
}
return nil
}
func resourceArmVirtualMachineDataDiskAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).vmClient
ctx := meta.(*ArmClient).StopContext
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
virtualMachineName := id.Path["virtualMachines"]
name := id.Path["dataDisks"]
azureRMLockByName(virtualMachineName, virtualMachineResourceName)
defer azureRMUnlockByName(virtualMachineName, virtualMachineResourceName)
virtualMachine, err := client.Get(ctx, resourceGroup, virtualMachineName, "")
if err != nil {
if utils.ResponseWasNotFound(virtualMachine.Response) {
return fmt.Errorf("Virtual Machine %q (Resource Group %q) was not found", virtualMachineName, resourceGroup)
}
return fmt.Errorf("Error loading Virtual Machine %q (Resource Group %q): %+v", virtualMachineName, resourceGroup, err)
}
dataDisks := make([]compute.DataDisk, 0)
for _, dataDisk := range *virtualMachine.StorageProfile.DataDisks {
// since this field isn't (and shouldn't be) case-sensitive; we're deliberately not using `strings.EqualFold`
if *dataDisk.Name != name {
dataDisks = append(dataDisks, dataDisk)
}
}
virtualMachine.StorageProfile.DataDisks = &dataDisks
// fixes #1600
virtualMachine.Resources = nil
future, err := client.CreateOrUpdate(ctx, resourceGroup, virtualMachineName, virtualMachine)
if err != nil {
return fmt.Errorf("Error removing Disk %q from Virtual Machine %q (Resource Group %q): %+v", name, virtualMachineName, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for Disk %q to be removed from Virtual Machine %q (Resource Group %q): %+v", name, virtualMachineName, resourceGroup, err)
}
return nil
}
func retrieveDataDiskAttachmentManagedDisk(meta interface{}, id string) (*compute.Disk, error) {
client := meta.(*ArmClient).diskClient
ctx := meta.(*ArmClient).StopContext
parsedId, err := parseAzureResourceID(id)
if err != nil {
return nil, fmt.Errorf("Error parsing Managed Disk ID %q: %+v", id, err)
}
resourceGroup := parsedId.ResourceGroup
name := parsedId.Path["disks"]
resp, err := client.Get(ctx, resourceGroup, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return nil, fmt.Errorf("Error Managed Disk %q (Resource Group %q) was not found!", name, resourceGroup)
}
return nil, fmt.Errorf("Error making Read request on Azure Managed Disk %q (Resource Group %q): %+v", name, resourceGroup, err)
}
return &resp, nil
}