Skip to content

Commit

Permalink
fix: aws instance profiles
Browse files Browse the repository at this point in the history
  • Loading branch information
moshloop committed Apr 7, 2022
1 parent 773613a commit f1d9266
Showing 1 changed file with 29 additions and 15 deletions.
44 changes: 29 additions & 15 deletions scrapers/aws/aws_session.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package aws

import (
"context"
"crypto/tls"
"fmt"
"net/http"
Expand All @@ -21,6 +22,17 @@ func isEmpty(val kommons.EnvVar) bool {
}

func NewSession(ctx *v1.ScrapeContext, conn v1.AWSConnection) (*aws.Config, error) {
cfg, err := loadConfig(ctx, conn)
if err != nil {
return nil, err
}
if conn.AssumeRole != "" {
cfg.Credentials = aws.NewCredentialsCache(stscreds.NewAssumeRoleProvider(sts.NewFromConfig(*cfg), conn.AssumeRole))
}
return cfg, nil
}

func loadConfig(ctx *v1.ScrapeContext, conn v1.AWSConnection) (*aws.Config, error) {
namespace := ctx.GetNamespace()
var tr http.RoundTripper
tr = &http.Transport{
Expand All @@ -40,7 +52,21 @@ func NewSession(ctx *v1.ScrapeContext, conn v1.AWSConnection) (*aws.Config, erro
}
tr = httplogger.RoundTripper(tr)
}
cfg, err := config.LoadDefaultConfig(ctx, config.WithHTTPClient(&http.Client{Transport: tr}))

options := []func(*config.LoadOptions) error{
config.WithRegion(conn.Region),
}

if conn.Endpoint != "" {
resolver := aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) {
return aws.Endpoint{
URL: conn.Endpoint,
HostnameImmutable: true,
Source: aws.EndpointSourceCustom,
}, nil
})
options = append(options, config.WithEndpointResolver(resolver))
}

if !isEmpty(conn.AccessKey) {
_, accessKey, err := ctx.Kommons.GetEnvValue(conn.AccessKey, namespace)
Expand All @@ -51,21 +77,9 @@ func NewSession(ctx *v1.ScrapeContext, conn v1.AWSConnection) (*aws.Config, erro
if err != nil {
return nil, fmt.Errorf(fmt.Sprintf("Could not parse EC2 secret key: %v", err))
}

cfg.Credentials = credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")
} else if conn.AssumeRole != "" {
creds := stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), conn.AssumeRole)
cfg.Credentials = aws.NewCredentialsCache(creds)
}
if conn.Region != "" {
cfg.Region = conn.Region
options = append(options, config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")))
}
// if conn.Endpoint != "" {
// cfg.EndpointResolver = aws.EndpointResolverFunc(
// func(service, region string) (aws.Endpoint, error) {
// return aws.Endpoint{URL: conn.Endpoint}, nil
// })
// }

cfg, err := config.LoadDefaultConfig(context.Background(), options...)
return &cfg, err
}

0 comments on commit f1d9266

Please sign in to comment.