【问题标题】:AWS Secret Manager with .Net Core throws socket exception带有 .Net Core 的 AWS Secret Manager 引发套接字异常
【发布时间】:2019-11-12 13:38:57
【问题描述】:

任何人都知道为什么我在尝试从密钥管理器获取 AWS 密钥时收到此错误?它是在 AWS Fargate 中运行的 docker 容器。

未处理的异常:System.AggregateException:一个或多个错误 发生了。 (无效参数)---> System.Net.Http.HttpRequestException:参数无效---> System.Net.Sockets.SocketException:参数无效 System.Net.Http.ConnectHelper.ConnectAsync(字符串主机,Int32 端口, CancellationToken cancelToken)

代码sn-p如下。并且该任务已分配了足够的 IAM 角色。

using System;
using System.IO;
using Amazon;
using Amazon.SecretsManager;
using Amazon.SecretsManager.Model;

namespace AssetView.Contacts.WebApi
{
    public static class SecretManager
    {
        public static string GetSecret(string secretName, string region)
        {
            //string secretName = "av/connectionstring/dev";
            // region = "us-east-1";
            string secret = "";

            MemoryStream memoryStream = new MemoryStream();

            IAmazonSecretsManager client = new AmazonSecretsManagerClient(RegionEndpoint.GetBySystemName(region));

            GetSecretValueRequest request = new GetSecretValueRequest();
            request.SecretId = secretName;
            //request.VersionStage = "AWSCURRENT"; // VersionStage defaults to AWSCURRENT if unspecified.

            GetSecretValueResponse response = null;

            // In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
            // See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
            // We rethrow the exception by default.

            try
            {
                response = client.GetSecretValueAsync(request).Result;
            }
            catch 
            {
                throw;
            }

            // Decrypts secret using the associated KMS CMK.
            // Depending on whether the secret is a string or binary, one of these fields will be populated.
            if (response.SecretString != null)
            {
                secret = response.SecretString;
            }
            else
            {
                memoryStream = response.SecretBinary;
                StreamReader reader = new StreamReader(memoryStream);
                secret = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(reader.ReadToEnd()));
            }

            return secret;
        }
    }
}

api文档不多说:https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/MISecretsManagerGetSecretValueAsyncGetSecretValueRequestCancellationToken.html

【问题讨论】:

    标签: .net-core aws-sdk aws-secrets-manager


    【解决方案1】:

    原来ECStaskrole没有设置获取访问Secret manager的权限!错误日志虽然有点误导。

    更新:像这样创建 am iam 角色:

    Type: "AWS::IAM::Role"
    Properties:
      RoleName: !Join [ '-', [my-ecsTaskrole, !Ref Environment] ]
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          -
            Effect: "Allow"
            Principal:
              Service:
                - "ecs-tasks.amazonaws.com" 
            Action: 
              - "sts:AssumeRole"
      Policies:
        -
          PolicyName: !Join [ '-', [mysecretmanagerpolicy, !Ref Environment] ]
          PolicyDocument:
            {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": [
                            "secretsmanager:Describe*",
                            "secretsmanager:Get*",
                            "secretsmanager:List*"
                        ],
                        "Resource": "*",
                        "Condition": {
                            "StringEquals": {
                                "secretsmanager:ResourceTag/App": "xyz"
                            }
                        }
                    }
                ]
            }
    

    此角色仅授予具有指定标签的机密,但您可以对其进行调整。

    函数抛出错误是因为它需要秘密,无论你是使用角色还是在函数中烘焙它。它应该在那里。

    【讨论】:

    • 您能记住我需要添加到 ecs 角色的策略设置的详细信息吗?遇到完全相同的问题。
    • 任务定义中的“taskrole”应具有适当的 iam 规则以允许访问秘密管理器。请记住 taskrole 与 taskexecutionrole 不同。如果你想要这个政策,我会在某个时候寄给你。我不在我的笔记本电脑附近
    • @OK999 你是如何确定是这个角色的?不错的工作。这是我一段时间以来看到的最模棱两可的错误消息
    【解决方案2】:

    如果其他人遇到此问题,您可以在堆栈跟踪中确定这是与凭据相关的问题 - 请参阅 Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext) 。我确实同意此错误消息非常具有误导性。

        Unhandled exception. System.AggregateException: One or more errors occurred. (An invalid argument was supplied.)
     ---> System.Net.Http.HttpRequestException: An invalid argument was supplied.
     ---> System.Net.Sockets.SocketException (10022): An invalid argument was supplied.
       at System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
       at System.Net.Sockets.DualSocketMultipleConnectAsync..ctor(SocketType socketType, ProtocolType protocolType)
       at System.Net.Sockets.Socket.ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
       at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
       --- End of inner exception stack trace ---
       at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
       at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
       at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
       at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
       at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
       at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
       at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
       at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken)
       at Amazon.Runtime.Internal.HttpHandler`1.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
       at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)
       --- End of inner exception stack trace ---
       at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
       at System.Threading.Tasks.Task`1.get_Result()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-01
      • 2021-06-29
      • 2021-10-20
      • 2020-12-25
      • 2022-07-19
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      相关资源
      最近更新 更多