Skip to content

Instantly share code, notes, and snippets.

@niski84
Created April 24, 2024 09:03
Show Gist options
  • Save niski84/513330eaecdddbb2b2d01baea641e43a to your computer and use it in GitHub Desktop.
Save niski84/513330eaecdddbb2b2d01baea641e43a to your computer and use it in GitHub Desktop.
show ebs orphaned volumes
package main
import (
"context"
"fmt"
"time"
"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"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
)
// VolumeMetadata holds metadata about an EBS volume.
type VolumeMetadata struct {
VolumeID string
CreationDate time.Time
SizeGB int32
Attached bool
InstanceID string
}
// DescribeVolumes retrieves all volumes and checks for orphaned volumes.
func DescribeVolumes(ctx context.Context) ([]VolumeMetadata, error) {
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return nil, fmt.Errorf("failed to load AWS SDK config: %w", err)
}
ec2Client := ec2.NewFromConfig(cfg)
paginator := ec2.NewDescribeVolumesPaginator(ec2Client, &ec2.DescribeVolumesInput{})
var volumes []VolumeMetadata
fmt.Println("Fetching volumes...")
for paginator.HasMorePages() {
out, err := paginator.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("failed to fetch volumes: %w", err)
}
for _, volume := range out.Volumes {
volumeData := VolumeMetadata{
VolumeID: *volume.VolumeId,
CreationDate: *volume.CreateTime,
SizeGB: volume.Size,
Attached: len(volume.Attachments) > 0,
}
if volumeData.Attached {
volumeData.InstanceID = *volume.Attachments[0].InstanceId
}
volumes = append(volumes, volumeData)
// Logging for each volume
if volumeData.Attached {
fmt.Printf("Volume %s is attached to instance %s.\n", volumeData.VolumeID, volumeData.InstanceID)
} else {
fmt.Printf("Volume %s is orphaned (detached).\n", volumeData.VolumeID)
}
}
}
return volumes, nil
}
func main() {
ctx := context.Background()
volumes, err := DescribeVolumes(ctx)
if err != nil {
fmt.Printf("Error: %s\n", err)
return
}
fmt.Println("Processed all volumes:")
for _, vol := range volumes {
fmt.Printf("VolumeID: %s, Created: %s, Size: %d GB, Attached: %t, InstanceID: %s\n",
vol.VolumeID, vol.CreationDate.Format("2006-01-02"), vol.SizeGB, vol.Attached, vol.InstanceID)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment