Skip to content

Commit 35f2b23

Browse files
committed
Support volume detachment upon instance update
1 parent cbeb424 commit 35f2b23

File tree

1 file changed

+48
-3
lines changed

1 file changed

+48
-3
lines changed

civo/instances/resource_instance.go

+48-3
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,9 @@ func ResourceInstance() *schema.Resource {
9696
Description: "The ID of the firewall to use, from the current list. If left blank or not sent, the default firewall will be used (open to all)",
9797
},
9898
"volume_type": {
99-
Type: schema.TypeString,
100-
Optional: true,
101-
Default: "ms-xfs-2-replicas",
99+
Type: schema.TypeString,
100+
Optional: true,
101+
//Default: "ms-xfs-2-replicas",
102102
Description: "The type of volume to use, either 'ssd' or 'bssd' (optional; default 'ssd')",
103103
},
104104
"tags": {
@@ -538,6 +538,51 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, m inter
538538
}
539539
}
540540

541+
if d.HasChange("attached_volume") {
542+
oldVolumes, newVolumes := d.GetChange("attached_volume")
543+
oldVolumeList := oldVolumes.([]interface{})
544+
newVolumeList := newVolumes.([]interface{})
545+
546+
// Check if there are any new volumes being attached
547+
for _, newVolume := range newVolumeList {
548+
newVolumeData := newVolume.(map[string]interface{})
549+
found := false
550+
for _, oldVolume := range oldVolumeList {
551+
oldVolumeData := oldVolume.(map[string]interface{})
552+
if newVolumeData["id"] == oldVolumeData["id"] {
553+
found = true
554+
break
555+
}
556+
}
557+
if !found {
558+
// This is a new volume being attached, which is not allowed
559+
return diag.Errorf("Attaching new volumes after instance creation is not allowed. Please create a new civo_volume_attachment resource for attaching additional volume.")
560+
}
561+
}
562+
563+
// Handle volume detachments
564+
for _, oldVolume := range oldVolumeList {
565+
oldVolumeData := oldVolume.(map[string]interface{})
566+
found := false
567+
for _, newVolume := range newVolumeList {
568+
newVolumeData := newVolume.(map[string]interface{})
569+
if oldVolumeData["id"] == newVolumeData["id"] {
570+
found = true
571+
break
572+
}
573+
}
574+
if !found {
575+
// This volume is no longer in the config, so detach it
576+
volumeID := oldVolumeData["id"].(string)
577+
_, err := apiClient.DetachVolume(volumeID)
578+
if err != nil {
579+
return diag.Errorf("Error detaching volume %s: %s", volumeID, err)
580+
}
581+
log.Printf("[INFO] Successfully detached volume %s from instance %s", volumeID, d.Id())
582+
}
583+
}
584+
}
585+
541586
// If reserved_ipv4 has changed, update the instance with the new reserved IP
542587
if d.HasChange("reserved_ipv4") {
543588
oldReservedIP, newReservedIP := d.GetChange("reserved_ipv4")

0 commit comments

Comments
 (0)