-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
provider_aws_ec2.go
152 lines (128 loc) · 5.05 KB
/
provider_aws_ec2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package add_cloud_metadata
import (
"context"
"fmt"
"net/http"
awssdk "github.com/aws/aws-sdk-go-v2/aws"
awscfg "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/pkg/errors"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/mapstr"
conf "github.com/elastic/elastic-agent-libs/config"
)
type IMDSClient interface {
GetInstanceIdentityDocument(ctx context.Context, params *imds.GetInstanceIdentityDocumentInput, optFns ...func(*imds.Options)) (*imds.GetInstanceIdentityDocumentOutput, error)
}
var NewIMDSClient func(cfg awssdk.Config) IMDSClient = func(cfg awssdk.Config) IMDSClient {
return imds.NewFromConfig(cfg)
}
type EC2Client interface {
DescribeTags(ctx context.Context, params *ec2.DescribeTagsInput, optFns ...func(*ec2.Options)) (*ec2.DescribeTagsOutput, error)
}
var NewEC2Client func(cfg awssdk.Config) EC2Client = func(cfg awssdk.Config) EC2Client {
return ec2.NewFromConfig(cfg)
}
// AWS EC2 Metadata Service
var ec2MetadataFetcher = provider{
Name: "aws-ec2",
Local: true,
Create: func(_ string, config *conf.C) (metadataFetcher, error) {
ec2Schema := func(m map[string]interface{}) mapstr.M {
m["service"] = mapstr.M{
"name": "EC2",
}
return mapstr.M{"cloud": m}
}
fetcher, err := newGenericMetadataFetcher(config, "aws", ec2Schema, fetchRawProviderMetadata)
return fetcher, err
},
}
// fetchRaw queries raw metadata from a hosting provider's metadata service.
func fetchRawProviderMetadata(
ctx context.Context,
client http.Client,
result *result,
) {
logger := logp.NewLogger("add_cloud_metadata")
// LoadDefaultConfig loads the EC2 role credentials
awsConfig, err := awscfg.LoadDefaultConfig(context.TODO(), awscfg.WithHTTPClient(&client))
if err != nil {
logger.Debugf("error loading AWS default configuration: %s.", err)
result.err = errors.Wrapf(err, "failed loading AWS default configuration")
return
}
awsClient := NewIMDSClient(awsConfig)
instanceIdentity, err := awsClient.GetInstanceIdentityDocument(context.TODO(), &imds.GetInstanceIdentityDocumentInput{})
if err != nil {
logger.Debugf("error fetching EC2 Identity Document: %s.", err)
result.err = errors.Wrapf(err, "failed fetching EC2 Identity Document.")
return
}
// AWS Region must be set to be able to get EC2 Tags
awsRegion := instanceIdentity.InstanceIdentityDocument.Region
awsConfig.Region = awsRegion
clusterName, err := fetchEC2ClusterNameTag(awsConfig, instanceIdentity.InstanceIdentityDocument.InstanceID)
if err != nil {
logger.Debugf("error fetching cluster name metadata: %s.", err)
}
accountID := instanceIdentity.InstanceIdentityDocument.AccountID
_, _ = result.metadata.Put("instance.id", instanceIdentity.InstanceIdentityDocument.InstanceID)
_, _ = result.metadata.Put("machine.type", instanceIdentity.InstanceIdentityDocument.InstanceType)
_, _ = result.metadata.Put("region", awsRegion)
_, _ = result.metadata.Put("availability_zone", instanceIdentity.InstanceIdentityDocument.AvailabilityZone)
_, _ = result.metadata.Put("account.id", accountID)
_, _ = result.metadata.Put("image.id", instanceIdentity.InstanceIdentityDocument.ImageID)
// for AWS cluster ID is used cluster ARN: arn:partition:service:region:account-id:resource-type/resource-id, example:
// arn:aws:eks:us-east-2:627286350134:cluster/cluster-name
if clusterName != "" {
clusterARN := fmt.Sprintf("arn:aws:eks:%s:%s:cluster/%v", awsRegion, accountID, clusterName)
_, _ = result.metadata.Put("orchestrator.cluster.name", clusterName)
_, _ = result.metadata.Put("orchestrator.cluster.id", clusterARN)
}
}
func fetchEC2ClusterNameTag(awsConfig awssdk.Config, instanceID string) (string, error) {
svc := NewEC2Client(awsConfig)
input := &ec2.DescribeTagsInput{
Filters: []types.Filter{
{
Name: awssdk.String("resource-id"),
Values: []string{
instanceID,
},
},
{
Name: awssdk.String("key"),
Values: []string{
"eks:cluster-name",
},
},
},
}
tagsResult, err := svc.DescribeTags(context.TODO(), input)
if err != nil {
return "", fmt.Errorf("error fetching EC2 Tags: %w", err)
}
if len(tagsResult.Tags) > 0 {
return *tagsResult.Tags[0].Value, nil
}
return "", nil
}