Skip to content

Instantly share code, notes, and snippets.

@alexsasharegan
Created October 1, 2024 04:12
Show Gist options
  • Save alexsasharegan/176211b5130efae3e316ff23be468d77 to your computer and use it in GitHub Desktop.
Save alexsasharegan/176211b5130efae3e316ff23be468d77 to your computer and use it in GitHub Desktop.
Drop all your S3 buckets like it's hot 🔥
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"log"
"os"
"os/exec"
"strings"
"sync"
)
var excludeMap = map[string]struct{}{
"still-in-use-bucket": {},
}
func main() {
dryRunPtr := flag.Bool("dry", false, "perform a dry run listing the buckets to be deleted")
flag.Parse()
dryRun := *dryRunPtr
// Example output (and our exclude list):
// 2019-06-16 11:36:26 bucket-1
// 2020-07-06 15:46:40 example.com
ls := lsCmd()
var lsOut bytes.Buffer
ls.Stdout = &lsOut
if err := ls.Run(); err != nil {
log.Fatalf("failed to list S3 Buckets: %v\n", err)
}
var wg sync.WaitGroup
scanner := bufio.NewScanner(&lsOut)
for scanner.Scan() {
split := strings.Split(scanner.Text(), " ")
if len(split) != 3 {
log.Printf("failed to parse S3 bucket: %s\n", strings.Join(split, " "))
continue
}
bucket := split[2]
errOut := log.New(os.Stderr, fmt.Sprintf("[%s] ", bucket), 0)
if _, has := excludeMap[bucket]; has {
errOut.Println("SKIPPING")
continue
}
wg.Add(1)
go func() {
defer wg.Done()
errOut.Println("DELETING")
if dryRun {
return
}
del := delCmd(bucket)
del.Stdout = errOut.Writer()
del.Stderr = errOut.Writer()
if err := del.Run(); err != nil {
errOut.Printf("delete failed: %v\n", err)
}
}()
}
if err := scanner.Err(); err != nil {
log.Fatalf("scanner error: %v\n", err)
}
wg.Wait()
}
func lsCmd() *exec.Cmd {
return exec.Command("aws", "s3", "ls")
}
func delCmd(bucket string) *exec.Cmd {
return exec.Command("aws", "s3", "rb", fmt.Sprintf("s3://%s", bucket), "--force")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment