88 "os"
99
1010 "github.com/aws/aws-sdk-go-v2/config"
11+ "github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
1112 "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
1213 "github.com/aws/aws-sdk-go-v2/service/s3"
1314 "github.com/aws/aws-sdk-go-v2/service/s3/types"
@@ -20,34 +21,34 @@ type Client struct {
2021 bucket string
2122}
2223
24+ func getRegion (ctx context.Context ) (string , error ) {
25+ if region := os .Getenv ("AWS_DEFAULT_REGION" ); len (region ) > 0 {
26+ return region , nil
27+ }
28+
29+ imdsClient := imds .New (imds.Options {})
30+ if result , err := imdsClient .GetRegion (ctx , nil ); err == nil {
31+ if len (result .Region ) > 0 {
32+ return result .Region , nil
33+ }
34+ }
35+
36+ return "" , errors .New ("Unknown current region" )
37+ }
38+
2339func New (log * log.Logger , bucket string ) (* Client , error ) {
2440 ctx := context .Background ()
2541
2642 // Using the current region (or a guess) find where the bucket lives
2743
28- /*
29- There are three region resolvers:
30- - resolveRegion
31- - resolveEC2IMDSRegion
32- - resolveDefaultRegion
33-
34- There are also three config providers:
35- - LoadOptions (programatic provided below)
36- - EnvConfig (reads environment variables)
37- - SharedConfig (reads ~/.aws files)
38-
39- The resolvers are run sequentially until a region is found, not all
40- config providers support each resolver. The absolute order is:
41-
42- - resolveRegion LoadOptions => config.WithRegion() if given
43- - resolveRegion EnvConfig => first of AWS_REGION, AWS_DEFAULT_REGION
44- - resolveRegion SharedConfig => default profile on disk
45- - resolveEC2IMDSRegion LoadOptions => config.WithEC2IMDSRegion() if given
46- - resolveDefaultRegion LoadOptions => config.WithDefaultRegion() if given
47- */
44+ region , err := getRegion (ctx )
45+ if err != nil {
46+ // Ignore error and fallback to us-east-1 for bucket lookup
47+ region = "us-east-1"
48+ }
49+
4850 config , err := config .LoadDefaultConfig (ctx ,
49- config .WithEC2IMDSRegion (),
50- config .WithDefaultRegion ("us-east-1" ),
51+ config .WithRegion (region ),
5152 )
5253 if err != nil {
5354 return nil , err
0 commit comments