session.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package session
  13. import (
  14. "fmt"
  15. "github.com/aws/aws-sdk-go/aws"
  16. "github.com/aws/aws-sdk-go/aws/credentials"
  17. "github.com/aws/aws-sdk-go/aws/credentials/stscreds"
  18. "github.com/aws/aws-sdk-go/aws/request"
  19. awssess "github.com/aws/aws-sdk-go/aws/session"
  20. "github.com/aws/aws-sdk-go/service/sts"
  21. ctrl "sigs.k8s.io/controller-runtime"
  22. )
  23. // Config contains configuration to create a new AWS provider.
  24. type Config struct {
  25. AssumeRole string
  26. Region string
  27. APIRetries int
  28. }
  29. var log = ctrl.Log.WithName("provider").WithName("aws")
  30. // New creates a new aws session based on the supported input methods.
  31. // https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html#specifying-credentials
  32. func New(sak, aks, region, role string, stsprovider STSProvider) (*awssess.Session, error) {
  33. config := aws.NewConfig()
  34. sessionOpts := awssess.Options{
  35. Config: *config,
  36. }
  37. if sak != "" && aks != "" {
  38. sessionOpts.Config.Credentials = credentials.NewStaticCredentials(aks, sak, "")
  39. sessionOpts.SharedConfigState = awssess.SharedConfigDisable
  40. }
  41. sess, err := awssess.NewSessionWithOptions(sessionOpts)
  42. if err != nil {
  43. return nil, fmt.Errorf("unable to create aws session: %w", err)
  44. }
  45. if region != "" {
  46. log.V(1).Info("using region", "region", region)
  47. sess.Config.WithRegion(region)
  48. }
  49. if role != "" {
  50. log.V(1).Info("assuming role", "role", role)
  51. stsclient := stsprovider(sess)
  52. sess.Config.WithCredentials(stscreds.NewCredentialsWithClient(stsclient, role))
  53. }
  54. sess.Handlers.Build.PushBack(request.WithAppendUserAgent("external-secrets"))
  55. return sess, nil
  56. }
  57. type STSProvider func(*awssess.Session) stscreds.AssumeRoler
  58. func DefaultSTSProvider(sess *awssess.Session) stscreds.AssumeRoler {
  59. return sts.New(sess)
  60. }