Skip to content

Commit 5e763ea

Browse files
committed
Implement the local-region discovery algorithm ourselves
1 parent 6d6c38a commit 5e763ea

File tree

2 files changed

+24
-22
lines changed

2 files changed

+24
-22
lines changed

s3secrets-helper/go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ go 1.15
55
require (
66
github.com/aws/aws-sdk-go-v2 v1.9.2 // indirect
77
github.com/aws/aws-sdk-go-v2/config v1.8.3
8+
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.6.0 // indirect
89
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.4
910
github.com/aws/aws-sdk-go-v2/service/s3 v1.16.1
1011
github.com/aws/smithy-go v1.8.0

s3secrets-helper/s3/s3.go

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
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+
2339
func 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

Comments
 (0)