Skip to content

Instantly share code, notes, and snippets.

@niski84
Created April 23, 2024 21:58
Show Gist options
  • Save niski84/5d9d6760ae9cba9fb37755d8af874704 to your computer and use it in GitHub Desktop.
Save niski84/5d9d6760ae9cba9fb37755d8af874704 to your computer and use it in GitHub Desktop.
forcefully detach ebs from ec2
package main
import (
"context"
"fmt"
"log"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ec2"
)
func main() {
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
log.Fatalf("Unable to load SDK config, %v", err)
}
ec2Client := ec2.NewFromConfig(cfg)
// Assume this part includes logic to handle instances and their volumes
// Example handling snippet from above would be here
}
func forceDetachVolume(client *ec2.Client, volumeId, instanceId string) error {
input := &ec2.DetachVolumeInput{
VolumeId: aws.String(volumeId),
InstanceId: aws.String(instanceId),
Force: aws.Bool(true),
}
_, err := client.DetachVolume(context.TODO(), input)
if err != nil {
return fmt.Errorf("failed to force detach volume: %v", err)
}
fmt.Printf("Forcefully detached volume %s from instance %s\n", volumeId, instanceId)
return nil
}
func deleteOrDetachVolume(client *ec2.Client, instanceId, volumeId string) {
_, err := client.DeleteVolume(context.TODO(), &ec2.DeleteVolumeInput{
VolumeId: aws.String(volumeId),
})
if err != nil {
if strings.Contains(err.Error(), "currently attached to") {
log.Printf("Volume %s is still attached, attempting to force detach...\n", volumeId)
if err := forceDetachVolume(client, volumeId, instanceId); err != nil {
log.Printf("Failed to force detach volume %s: %v", volumeId, err)
}
} else {
log.Printf("Failed to delete volume %s: %v", volumeId, err)
}
} else {
fmt.Printf("Deleted volume %s successfully\n", volumeId)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment