diff --git a/pkg/backup/constants/constants.go b/pkg/backup/constants/constants.go index 51a7112cc9..5506083dff 100644 --- a/pkg/backup/constants/constants.go +++ b/pkg/backup/constants/constants.go @@ -100,4 +100,7 @@ const ( ClusterBackupMeta = "clustermeta" ClusterRestoreMeta = "restoremeta" MetaFile = "backupmeta" + + // AWSRegionEnv is the aws region environment variable + AWSRegionEnv = "AWS_REGION" ) diff --git a/pkg/backup/util/aws_ebs.go b/pkg/backup/util/aws_ebs.go index 8656987ab6..009f5f505d 100644 --- a/pkg/backup/util/aws_ebs.go +++ b/pkg/backup/util/aws_ebs.go @@ -15,6 +15,7 @@ package util import ( "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ebs" "github.com/aws/aws-sdk-go/service/ebs/ebsiface" @@ -22,11 +23,13 @@ import ( "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "github.com/pingcap/errors" "github.com/pingcap/tidb-operator/pkg/apis/pingcap/v1alpha1" + "github.com/pingcap/tidb-operator/pkg/backup/constants" "go.uber.org/atomic" "golang.org/x/sync/errgroup" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/klog/v2" + "os" ) // TODO: shall this structure be refactor or reserved for future use? @@ -119,7 +122,17 @@ func NewEC2Session(concurrency uint) (*EC2Session, error) { if err != nil { return nil, errors.Trace(err) } - ec2Session := ec2.New(sess) + + region := os.Getenv(constants.AWSRegionEnv) + if region == "" { + ec2Metadata := ec2metadata.New(sess) + region, err = ec2Metadata.Region() + if err != nil { + return nil, errors.Annotate(err, "get ec2 region") + } + } + + ec2Session := ec2.New(sess, aws.NewConfig().WithRegion(region)) return &EC2Session{EC2: ec2Session, concurrency: concurrency}, nil } @@ -201,6 +214,15 @@ func NewEBSSession(concurrency uint) (*EBSSession, error) { if err != nil { return nil, errors.Trace(err) } - ebsSession := ebs.New(sess) + region := os.Getenv(constants.AWSRegionEnv) + if region == "" { + ec2Metadata := ec2metadata.New(sess) + region, err = ec2Metadata.Region() + if err != nil { + return nil, errors.Annotate(err, "get ec2 region") + } + } + + ebsSession := ebs.New(sess, aws.NewConfig().WithRegion(region)) return &EBSSession{EBS: ebsSession, concurrency: concurrency}, nil }