Skip to content

Commit

Permalink
Allow updating reserved_ip4 for instance resource
Browse files Browse the repository at this point in the history
  • Loading branch information
uzaxirr committed Jul 10, 2024
1 parent a675626 commit 026d1f3
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions civo/instances/resource_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,56 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, m inter
}
}

// If reserved_ipv4 has changed, update the instance with the new reserved IP
if d.HasChange("reserved_ipv4") {
oldReservedIP, newReservedIP := d.GetChange("reserved_ipv4")
instance, err := apiClient.GetInstance(d.Id())
if err != nil {
// Check if the instance no longer exists.
return diag.Errorf("[ERR] instance %s not found", d.Id())
}

// Unassign the old reserved IP if it exists
if oldReservedIP != "" {
ip, err := apiClient.FindIP(oldReservedIP.(string))
if err != nil {
if errors.Is(err, civogo.ZeroMatchesError) {
return diag.Errorf("sorry there is no %s IP in your account", oldReservedIP)
} else if errors.Is(err, civogo.MultipleMatchesError) {
return diag.Errorf("sorry we found more than one IP with that value in your account")
} else {
return diag.Errorf("error finding IP %s: %s", oldReservedIP, err)
}
}

_, err = apiClient.UnassignIP(ip.ID, apiClient.Region)
if err != nil {
return diag.Errorf("[ERR] an error occurred while unassigning reserved IP %s from instance %s: %s", ip.ID, instance.ID, err)
}
log.Printf("[INFO] unassigned reserved IP %s from the instance %s", oldReservedIP, d.Id())
}

// Find the new reserved IP
ip, err := apiClient.FindIP(newReservedIP.(string))
if err != nil {
if errors.Is(err, civogo.ZeroMatchesError) {
return diag.Errorf("sorry there is no %s IP in your account", newReservedIP)
} else if errors.Is(err, civogo.MultipleMatchesError) {
return diag.Errorf("sorry we found more than one IP with that value in your account")
} else {
return diag.Errorf("error finding IP %s: %s", newReservedIP, err)
}
}

// Assign the new reserved IP to the instance
_, err = apiClient.AssignIP(ip.ID, instance.ID, "instance", apiClient.Region)
if err != nil {
return diag.Errorf("[ERR] an error occurred while assigning reserved IP %s to instance %s: %s", ip.ID, instance.ID, err)
}

log.Printf("[INFO] assigned reserved IP %s to the instance %s", newReservedIP, d.Id())
}

// if a firewall is declared we update the instance
if d.HasChange("firewall_id") {
firewallID := d.Get("firewall_id").(string)
Expand Down

0 comments on commit 026d1f3

Please sign in to comment.