forked from awsdocs/aws-doc-sdk-examples
/
s3_delete_buckets.go
102 lines (84 loc) · 2.5 KB
/
s3_delete_buckets.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
This file is licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License. A copy of
the License is located at
http://aws.amazon.com/apache2.0/
This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/
package main
import (
"flag"
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
func deleteBucketsByPrefix(sess *session.Session, prefix string) error {
// Create Amazon S3 service client
svc := s3.New(sess)
// Empty list to hold names of S3 buckets with prefix
bucketList := make([]string, 0)
result, err := svc.ListBuckets(nil)
if err != nil {
return err
}
for _, b := range result.Buckets {
// Does bucket name start with prefix
if strings.HasPrefix(*b.Name, prefix) {
bucketList = append(bucketList, *b.Name)
}
}
for _, b := range bucketList {
// First delete any objects in the bucket
iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{
Bucket: aws.String(b),
})
err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter)
if err != nil {
return err
}
_, err = svc.DeleteBucket(&s3.DeleteBucketInput{
Bucket: aws.String(b),
})
if err != nil {
return err
}
err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{
Bucket: aws.String(b),
})
if err != nil {
return err
}
}
return nil
}
// Deletes any S3 buckets in the default AWS Region
// that start with the given text
//
// Usage:
// go run s3_delete_buckets -p PREFIX
func main() {
prefixPtr := flag.String("p", "", "The prefix of the buckets to delete")
flag.Parse()
prefix := *prefixPtr
if prefix == "" {
fmt.Println("You must supply a bucket prefix")
return
}
// Initialize a session that the SDK uses to load
// credentials from the shared credentials file (~/.aws/credentials)
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
err := deleteBucketsByPrefix(sess, prefix)
if err != nil {
fmt.Println("Could not delete buckets with prefix " + prefix)
} else {
fmt.Println("Deleted buckets with prefix " + prefix)
}
}