Created
December 8, 2023 19:15
-
-
Save r--w/b12f983774abfa26cb4dde7a940419b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"flag" | |
"fmt" | |
"log" | |
"time" | |
"github.com/aws/aws-sdk-go-v2/aws" | |
"github.com/aws/aws-sdk-go-v2/config" | |
"github.com/aws/aws-sdk-go-v2/credentials" | |
"github.com/aws/aws-sdk-go-v2/service/s3" | |
) | |
func main() { | |
var bucketName string | |
var accountId string | |
var accessKeyId string | |
var accessKeySecret string | |
flag.StringVar(&bucketName, "bucket", "", "Name of the S3 bucket") | |
flag.StringVar(&accountId, "account", "", "Account ID") | |
flag.StringVar(&accessKeyId, "accessKey", "", "Access Key ID") | |
flag.StringVar(&accessKeySecret, "accessSecret", "", "Access Key Secret") | |
flag.Parse() | |
if bucketName == "" || accountId == "" || accessKeyId == "" || accessKeySecret == "" { | |
log.Fatal("Missing required flags. --bucket, --account, --accessKey, and --accessSecret are required.") | |
} | |
r2Resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) { | |
return aws.Endpoint{ | |
URL: fmt.Sprintf("https://%s.r2.cloudflarestorage.com", accountId), | |
SigningRegion: "auto", | |
}, nil | |
}) | |
cfg, err := config.LoadDefaultConfig(context.TODO(), | |
config.WithEndpointResolverWithOptions(r2Resolver), | |
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyId, accessKeySecret, "")), | |
) | |
if err != nil { | |
log.Fatal(err) | |
} | |
client := s3.NewFromConfig(cfg) | |
listObjectsOutput, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{ | |
Bucket: &bucketName, | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
now := time.Now() | |
for _, object := range listObjectsOutput.Contents { | |
duration := now.Sub(*object.LastModified) | |
if duration.Hours() > float64(24*15) { | |
fmt.Printf("Deleting object: %s, last modified: %s\n", *object.Key, object.LastModified.String()) | |
_, err := client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{ | |
Bucket: &bucketName, | |
Key: object.Key, | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment