awsv2.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package aws
  15. import (
  16. "context"
  17. "fmt"
  18. "github.com/aws/aws-sdk-go-v2/aws"
  19. "github.com/aws/aws-sdk-go-v2/config"
  20. "github.com/aws/aws-sdk-go-v2/credentials"
  21. "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
  22. "github.com/aws/aws-sdk-go-v2/service/s3"
  23. api "yunion.io/x/cloudmux/pkg/apis/compute"
  24. "yunion.io/x/pkg/errors"
  25. )
  26. func (client *SAwsClient) getConfig(ctx context.Context, regionId string, assumeRole bool) (aws.Config, error) {
  27. httpClient, err := client.getHttpClient()
  28. if err != nil {
  29. return aws.Config{}, errors.Wrap(err, "getHttpClient")
  30. }
  31. opts := []func(*config.LoadOptions) error{
  32. config.WithRegion(regionId),
  33. config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(client.accessKey, client.accessSecret, "")),
  34. config.WithHTTPClient(httpClient),
  35. }
  36. if assumeRole && len(client.accountId) > 0 {
  37. // need to assumeRole
  38. var env string
  39. switch client.GetAccessEnv() {
  40. case api.CLOUD_ACCESS_ENV_AWS_GLOBAL:
  41. env = "aws"
  42. default:
  43. env = "aws-cn"
  44. }
  45. roleARN := fmt.Sprintf("arn:%s:iam::%s:role/%s", env, client.accountId, client.getAssumeRoleName())
  46. opts = append(opts, config.WithAssumeRoleCredentialOptions(func(options *stscreds.AssumeRoleOptions) {
  47. options.RoleARN = roleARN
  48. }))
  49. }
  50. if client.debug {
  51. opts = append(opts, config.WithClientLogMode(aws.LogSigning|aws.LogRequestWithBody|aws.LogResponseWithBody))
  52. }
  53. cfg, err := config.LoadDefaultConfig(ctx, opts...)
  54. if err != nil {
  55. return aws.Config{}, errors.Wrap(err, "LoadDefaultConfig")
  56. }
  57. return cfg, nil
  58. }
  59. func (r *SRegion) getConfig() (aws.Config, error) {
  60. return r.client.getConfig(context.Background(), r.RegionId, true)
  61. }
  62. func (r *SRegion) GetS3Client() (*s3.Client, error) {
  63. cfg, err := r.getConfig()
  64. if err != nil {
  65. return nil, errors.Wrap(err, "getConfig")
  66. }
  67. return s3.NewFromConfig(cfg), nil
  68. }