-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This extends cloudmeta package with aws metadata provider. Fixes: #4127
- Loading branch information
1 parent
e740d7f
commit ae265f3
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
// Copyright (C) 2024 ScyllaDB | ||
|
||
package cloudmeta | ||
|
||
import ( | ||
"context" | ||
|
||
"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/pkg/errors" | ||
) | ||
|
||
// AWSMetadata is a wrapper around ec2 metadata client. | ||
type AWSMetadata struct { | ||
ec2meta *ec2metadata.EC2Metadata | ||
} | ||
|
||
// NewAWSMetadata is a constructor for AWSMetadata service. | ||
// testEndpoint can be provided if you want to overwrite the default metadata endpoint, otherwise leave it empty. | ||
func NewAWSMetadata(testEndpoint string) (*AWSMetadata, error) { | ||
session, err := session.NewSession() | ||
if err != nil { | ||
return nil, errors.Wrap(err, "session.NewSession") | ||
} | ||
cfg := aws.NewConfig() | ||
if testEndpoint != "" { | ||
cfg = cfg.WithEndpoint(testEndpoint) | ||
} | ||
return &AWSMetadata{ | ||
ec2meta: ec2metadata.New(session, cfg), | ||
}, nil | ||
} | ||
|
||
// Metadata return InstanceMetadata from aws if available. | ||
func (aws *AWSMetadata) Metadata(ctx context.Context) (InstanceMetadata, error) { | ||
if !aws.ec2meta.AvailableWithContext(ctx) { | ||
return InstanceMetadata{}, nil | ||
} | ||
|
||
instanceData, err := aws.ec2meta.GetInstanceIdentityDocumentWithContext(ctx) | ||
if err != nil { | ||
return InstanceMetadata{}, errors.Wrap(err, "aws.metadataClient.GetInstanceIdentityDocument") | ||
} | ||
|
||
return InstanceMetadata{ | ||
CloudProvider: CloudProviderAWS, | ||
InstanceType: instanceData.InstanceType, | ||
}, nil | ||
} |