sigs.k8s.io/external-dns@v0.14.1/provider/aws/session.go (about) 1 /* 2 Copyright 2023 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package aws 18 19 import ( 20 "fmt" 21 "strings" 22 23 "github.com/aws/aws-sdk-go/aws" 24 "github.com/aws/aws-sdk-go/aws/credentials/stscreds" 25 "github.com/aws/aws-sdk-go/aws/request" 26 "github.com/aws/aws-sdk-go/aws/session" 27 "github.com/linki/instrumented_http" 28 "github.com/sirupsen/logrus" 29 30 "sigs.k8s.io/external-dns/pkg/apis/externaldns" 31 ) 32 33 // AWSSessionConfig contains configuration to create a new AWS provider. 34 type AWSSessionConfig struct { 35 AssumeRole string 36 AssumeRoleExternalID string 37 APIRetries int 38 } 39 40 func NewSession(awsConfig AWSSessionConfig) (*session.Session, error) { 41 config := aws.NewConfig().WithMaxRetries(awsConfig.APIRetries) 42 43 config.WithHTTPClient( 44 instrumented_http.NewClient(config.HTTPClient, &instrumented_http.Callbacks{ 45 PathProcessor: func(path string) string { 46 parts := strings.Split(path, "/") 47 return parts[len(parts)-1] 48 }, 49 }), 50 ) 51 52 session, err := session.NewSessionWithOptions(session.Options{ 53 Config: *config, 54 SharedConfigState: session.SharedConfigEnable, 55 }) 56 if err != nil { 57 return nil, fmt.Errorf("instantiating AWS session: %w", err) 58 } 59 60 if awsConfig.AssumeRole != "" { 61 if awsConfig.AssumeRoleExternalID != "" { 62 logrus.Infof("Assuming role: %s with external id %s", awsConfig.AssumeRole, awsConfig.AssumeRoleExternalID) 63 session.Config.WithCredentials(stscreds.NewCredentials(session, awsConfig.AssumeRole, func(p *stscreds.AssumeRoleProvider) { 64 p.ExternalID = &awsConfig.AssumeRoleExternalID 65 })) 66 } else { 67 logrus.Infof("Assuming role: %s", awsConfig.AssumeRole) 68 session.Config.WithCredentials(stscreds.NewCredentials(session, awsConfig.AssumeRole)) 69 } 70 } 71 72 session.Handlers.Build.PushBack(request.MakeAddToUserAgentHandler("ExternalDNS", externaldns.Version)) 73 74 return session, nil 75 }