diff --git a/discovery/aws/ec2.go b/discovery/aws/ec2.go index 539cd84c4f..d6e0fd012d 100644 --- a/discovery/aws/ec2.go +++ b/discovery/aws/ec2.go @@ -27,6 +27,7 @@ import ( awsConfig "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/credentials/stscreds" + "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" "github.com/aws/aws-sdk-go-v2/service/ec2" ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/aws/aws-sdk-go-v2/service/sts" @@ -123,6 +124,7 @@ func (c *EC2SDConfig) UnmarshalYAML(unmarshal func(any) error) error { if err != nil { return err } + if c.Region == "" { cfg, err := awsConfig.LoadDefaultConfig(context.Background()) if err != nil { @@ -134,6 +136,16 @@ func (c *EC2SDConfig) UnmarshalYAML(unmarshal func(any) error) error { // This can happen if the user has set the region in the AWS config file or environment variables. c.Region = cfg.Region } + + if c.Region == "" { + // Try to get the region from the instance metadata service (IMDS). + imdsClient := imds.NewFromConfig(cfg) + region, err := imdsClient.GetRegion(context.Background(), &imds.GetRegionInput{}) + if err != nil { + return err + } + c.Region = region.Region + } } if c.Region == "" {