Skip to content

Commit

Permalink
Autodetect bucket region
Browse files Browse the repository at this point in the history
  • Loading branch information
beatcracker committed Dec 9, 2022
1 parent edc9fb4 commit 9d59603
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 10 deletions.
23 changes: 18 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,26 @@ var rootCmd = &cobra.Command{
os.Exit(1)
}

if ok := s3.IsBucket(*session, bucketName); !ok {
region, err := s3.GetBucketRegion(bucketName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}

session.Session.Config.Region = &region

ok, err := s3.IsBucket(*session, bucketName)
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}

if !ok {
fmt.Printf("The bucket name `%s` was not found in profile `%s`\n", bucketName, profile)
return
} else {
cli.Grep(session, bucketName, prefix, args[0], ignoreCase)
return
os.Exit(1)
}

cli.Grep(session, bucketName, prefix, args[0], ignoreCase)
},
}

Expand Down
11 changes: 9 additions & 2 deletions config/aws.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
)

Expand All @@ -11,12 +12,18 @@ type AWSSession struct {

// NewAWSParams creates a new AWSSession object
func NewAWSSession(awsProfile string) (*AWSSession, error) {
sess := session.Must(session.NewSessionWithOptions(session.Options{
sess, err := session.NewSessionWithOptions(session.Options{
Config: aws.Config{Region: aws.String("us-east-2")},
Profile: awsProfile,
SharedConfigState: session.SharedConfigEnable,
}))
})

if err != nil {
return nil, err
}

return &AWSSession{
Session: sess,
}, nil

}
28 changes: 25 additions & 3 deletions s3/validators.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,43 @@
package s3

import (
"fmt"
"net/http"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/dabdada/s3-grep/config"
)

// Get bucket region: https://github.com/aws/aws-sdk-go/issues/720
func GetBucketRegion(bucketName string) (string, error) {
res, err := http.Head(fmt.Sprintf("https://%s.s3.amazonaws.com", bucketName))

if err != nil {
return "", err
}

defer res.Body.Close()

header := "X-Amz-Bucket-Region"

if len(res.Header[header]) == 0 {
return "", fmt.Errorf("header not found in response: %s", header)
}

return res.Header.Get(header), nil
}

// IsBucket validator to ensure bucket is available in profile
func IsBucket(session config.AWSSession, bucketName string) bool {
func IsBucket(session config.AWSSession, bucketName string) (bool, error) {
svc := s3.New(session.Session)
headInput := &s3.HeadBucketInput{
Bucket: aws.String(bucketName),
}
_, err := svc.HeadBucket(headInput)

if err != nil {
return false
return false, err
}
return true
return true, err
}

0 comments on commit 9d59603

Please sign in to comment.