简体   繁体   English

.NET 核心工作者 - 因为启用 Docker 撰写我的服务无法从 appsettings.json 读取 IAM 凭证

[英].NET Core worker - since enabling Docker Compose my service can't read IAM credentials from appsettings.json

I am building a small .NET Core worker service to read messages from an AWS SQS queue.我正在构建一个小型 .NET 核心工作人员服务来读取来自 AWS SQS 队列的消息。 To do this, it requires IAM credentials in the form of an access and secret key.为此,它需要采用访问和密钥形式的 IAM 凭证。 I had originally been running this project as a docker container, and it has been working fine.我最初将这个项目作为 docker 容器运行,并且运行良好。 I wanted to enable the ability to run this container multiple times, so multiple instances of the same service.我想启用多次运行此容器的能力,因此同一服务的多个实例。 I enabled Docker Compose in Visual Studio and it added the base docker compose YAML file to the project.我在 Visual Studio 中启用了 Docker Compose 并将基础 docker compose YAML 文件添加到项目中。 Now when I try to run the solution in debug, I get the following error:现在,当我尝试在调试中运行解决方案时,出现以下错误:

An exception of type 'Amazon.Runtime.AmazonServiceException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Unable to get IAM security credentials from EC2 Instance Metadata Service.'

I am assuming this is because somehow now the solution can't read the access and secret key from my appSettings.json but I'm unsure how to fix this.我假设这是因为不知何故现在解决方案无法从我的 appSettings.json 读取访问密钥和密钥,但我不确定如何解决这个问题。

Here is my DockerFile这是我的 DockerFile

FROM mcr.microsoft.com/dotnet/core/runtime:3.1-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["WorkerServiceDocker.csproj", ""]
RUN dotnet restore "./WorkerServiceDocker.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "WorkerServiceDocker.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WorkerServiceDocker.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
RUN mkdir -p /app/logging
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WorkerServiceDocker.dll"]

Here is the docker compose file created by Visual Studio这是由 Visual Studio 创建的 docker 撰写文件

version: '3.4'

services:
  workerservicedocker:
    image: ${DOCKER_REGISTRY-}workerservicedocker
    build:
      context: .
      dockerfile: Dockerfile

The method that fails is:失败的方法是:

public async void TriggerMessageGetAsync(string queueUrl, int pollingTime)
{
    var _messages = await GetMessagesAsync(queueUrl, pollingTime);
    if (_messages.Count == 0)
    {
        _logger.LogInformation($"No messages found.");
    }
    else
    {
        foreach (var message in _messages)
        {
            _logger.LogInformation($"Message {message.MessageId} received OK");
        }
    }
}

And my configuration is loaded from appSettings.json in the Program.cs我的配置是从 Program.cs 中的 appSettings.json 加载的

public class Program
{
    public static void Main(string[] args)
    {
        Session.InstanceGuid = Guid.NewGuid().ToString();

        File.Create("init.log").Close();
        var logWriter = new StreamWriter("init.log");
        logWriter.WriteLine("Assembly Path: " + Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
        logWriter.WriteLine($"Session Guid: {Session.InstanceGuid}");
        logWriter.WriteLine($"Container DateTime: {DateTime.Now}");
        logWriter.Dispose(); 
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
                services.AddSingleton<ILogger, Logger>(); // Using my own basic wrapper around NLog for the moment, pumped to CloudWatch.
                services.AddAWSService<IAmazonSQS>();
            });
}

When I run in debug using the 'Docker Compose' option, the output indicates that it has found AWS credentials?当我使用“Docker Compose”选项在调试中运行时,output 表明它已找到 AWS 凭证?

  Found AWS options in IConfiguration

AWSSDK: Information: Found AWS options in IConfiguration AWSSDK: Information: Found credentials using the AWS SDK's default credential search AWSSDK:信息:在 IConfiguration 中找到 AWS 选项 AWSSDK:信息:使用 AWS 开发工具包的默认凭证搜索找到凭证

I'm not sure what else to include with this question, but am hoping someone can assist.我不确定这个问题还包括什么,但我希望有人能提供帮助。 I am clearly missing some configuration or option that ensures the access and secret key can be read from my appSettings.json file.我显然缺少一些配置或选项,以确保可以从我的 appSettings.json 文件中读取访问密钥和密钥。 As I said, this was working fine when I was running it as a single docker container from my DockerFile.正如我所说,当我从我的 DockerFile 将它作为单个 docker 容器运行时,它运行良好。

I don't see where you actually instruct AWS to use those credentials, so I will solve that as a likely problem.我没有看到您实际指示 AWS 在哪里使用这些凭证,因此我将把它作为一个可能的问题来解决。

First, your appsettings.json should be in this format for aws creds:首先,您的 appsettings.json 对于 aws 凭据应该采用以下格式:

"AWS": {        
    "AccessKey": "abc",         
    "SecretKey": "xyz",         
    "Region": "ksjs"    
},

And then try this solution ( explicitly setting environment variables before you initialize the aws service)然后尝试此解决方案(在初始化 aws 服务之前显式设置环境变量)

https://github.com/aws/aws-sdk-net/issues/499#issuecomment-276142625 https://github.com/aws/aws-sdk-net/issues/499#issuecomment-276142625

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM