简体   繁体   English

AWS DotNet SDK 错误:无法从 EC2 实例元数据服务获取 IAM 安全凭证

[英]AWS DotNet SDK Error: Unable to get IAM security credentials from EC2 Instance Metadata Service

I use an example from here in order to retreive a secret from AWS SecretsManager in c# code.我使用此处的一个示例,以便在 c# 代码中从 AWS SecretsManager 检索机密。

I have set credentials locally via AWS CLI, and I am able to retreive secret list using AWS CLI command "aws secretsmanager list-secrets".我已通过 AWS CLI 在本地设置凭据,并且能够使用 AWS CLI 命令“aws secretsmanager list-secrets”检索机密列表。

But c# console app fails with an error:但是 c# 控制台应用程序失败并出现错误:

> Unhandled exception. System.AggregateException: One or more errors occurred. (Unable to get IAM security credentials from EC2 Instance Metadata Service.)
 ---> Amazon.Runtime.AmazonServiceException: Unable to get IAM security credentials from EC2 Instance Metadata Service.
   at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.FetchCredentials()
   at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentials()
   at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentialsAsync()
   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()
   at AWSConsoleApp2.GetSecretValueFirst.GetSecret() in D:\Work\Projects\Training\AWSConsoleApp2\AWSConsoleApp2\GetSecretValueFirst.cs:line 53
   at AWSConsoleApp2.Program.Main(String[] args) in D:\Work\Projects\Training\AWSConsoleApp2\AWSConsoleApp2\Program.cs:line 11

When I change original constructor call当我更改原始构造函数调用时

IAmazonSecretsManager client = new AmazonSecretsManagerClient(); IAmazonSecretsManager 客户端 = new AmazonSecretsManagerClient();

with adding inherited parameter of type AWSCredentials添加类型为 AWSCredentials 的继承参数

IAmazonSecretsManager client = new AmazonSecretsManagerClient(new StoredProfileAWSCredentials()); IAmazonSecretsManager 客户端 = new AmazonSecretsManagerClient(new StoredProfileAWSCredentials());

it works fine.它工作正常。

Class StoredProfileAWSCredentials is obsolete but it works to use it. Class StoredProfileAWSCredentials 已过时,但可以正常使用。 I use libraries that work without errors on the other machines and I cannot change them.我使用的库在其他机器上可以正常工作,而且我无法更改它们。

I use credentials for user that belongs to Administrators group and has full access to SecretsMnager.我为属于 Administrators 组且具有对 SecretsMnager 的完全访问权限的用户使用凭据。 Region has set properly in c# code, profile is default.区域已在c#代码中设置好,配置文件是默认的。

Any ideas?有任何想法吗? Thanks for advance感谢您的提前

I had the same issue, here is how I fixed it on my development environment我有同样的问题,这是我在开发环境中修复它的方法

  1. I created an AWS profile using the AWS extension for Visual studio我使用适用于 Visual Studio 的 AWS 扩展创建了一个 AWS 配置文件
  2. Once the profile is set up the credentials are passed using the profile and it worked fine for me设置配置文件后,使用配置文件传递凭据,对我来说效果很好

Point to note here, the user profile accessing the key manager should have a valid security group assigned for the Secrets manager.这里需要注意的是,访问密钥管理器的用户配置文件应该为 Secrets 管理器分配一个有效的安全组。

Try it out let me know, how it went.试一试告诉我,结果如何。

Same issue and resolved by deleting $HOME/.aws/config and credentials files and recreating with AWS CLI.同样的问题并通过删除 $HOME/.aws/config 和凭证文件并使用 AWS CLI 重新创建来解决。

In my case I was switching laptops from Windows to a new MBP.就我而言,我正在将笔记本电脑从 Windows 切换到新的 MBP。 I had setup my new environment by copying the .aws directory files and confirmed that AWS CLI worked correctly.我通过复制 .aws 目录文件设置了我的新环境,并确认 AWS CLI 工作正常。 Confusingly the dotnet SDK failed with same errors.令人困惑的是,dotnet SDK 因相同的错误而失败。

使用 AWS 提供的数据运行以下命令并按照提示操作:

aws configure

I've run into this issue a number of times, but have not been able to resolve it using the above solutions.我已经多次遇到这个问题,但无法使用上述解决方案解决它。

What has worked for me is explicitly setting my AWS profile using the AWS_PROFILE environment variable and setting it to the profile I want to use.对我有用的是使用AWS_PROFILE环境变量明确设置我的 AWS 配置文件并将其设置为我想要使用的配置文件。

Today I ran into this issue again, where even that didn't work.今天我又遇到了这个问题,即使这样也没有用。 What eventually solved it was setting the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.最终解决它的是设置AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY环境变量。

I dread the day where I run out of alternative ways to supply credentials to AWS.我害怕有一天我用尽了向 AWS 提供凭证的替代方法。

我有同样的问题,并通过将 Visual Studio 中的 AWS 配置文件的名称更改为默认值来解决它。

The question is not exactly my problem, but it's the first hit on google so I figured I'd chip in just in case.这个问题不完全是我的问题,但它是谷歌的第一次点击,所以我想我会以防万一。

I got the exact above error when issuing发出时我得到了确切的上述错误

dotnet lambda list-layers

It seems like the dotnet cli uses the AWS_PROFILE variable and does not default to AWS_DEFAULT_PROFILE . dotnet cli 似乎使用AWS_PROFILE变量并且不默认为AWS_DEFAULT_PROFILE In my company, the AWS_DEFAULT_PROFILE is mapped to an identity provider, thus I do not manage different access with different profiles and the default profile is empty.在我的公司中, AWS_DEFAULT_PROFILE映射到身份提供商,因此我不使用不同的配置文件管理不同的访问,并且default配置文件为空。 As a workaround, run your command like this作为一种解决方法,像这样运行您的命令

AWS_PROFILE=$AWS_DEFAULT_PROFILE dotnet lambda list-layers

This way the CLI will use the correct credentials.这样 CLI 将使用正确的凭据。

make sure you have the latest version of EC2config installed https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_Install.html确保您安装了最新版本的 EC2config https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_Install.html

Thanks谢谢

Just add env variables in control panel AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.只需在控制面板 AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY 中添加环境变量。 The actual value of either is not important.两者的实际值都不重要。 I have set them both to a space (' ').我已将它们都设置为空格('')。 Don't know why it works but it works.不知道为什么它有效,但它有效。 It does seem to take longer to log in. It seems that instead of going to the buggy flow, the SDK tries to use the env vars, fails and about after 30 seconds or so logs in as required.登录似乎确实需要更长的时间。似乎 SDK 没有进入错误的流程,而是尝试使用 env vars,失败并且大约在 30 秒左右后根据需要登录。

Tested it on two different Win10 PCs with no AWS CLI installed or any AWS profile configured.在没有安装 AWS CLI 或配置任何 AWS 配置文件的两台不同的 Win10 PC 上对其进行了测试。 The issue was recreated 100% and the described w/a fixed it.该问题已 100% 重新创建,并且所描述的 w/a 已修复该问题。

I had the same issue and it turned out to be because I had AWS_ACCESS_KEY_ID , AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN uppercased in my credentials file.我遇到了同样的问题,结果证明是因为我的credentials文件中有AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKEN大写。 Changing the keys to lowercase solved it for me.将键更改为小写为我解决了这个问题。

Since AWS SDK credentials configuration is causing a lot of headache, I'll throw in some context.由于 AWS 开发工具包凭证配置引起了很多麻烦,我将介绍一些上下文。 First of all, if you are using dotnet core, use the AWSSDK.Extensions.NETCore.Setup package ( https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-netcore.html ), which will respect your appsettings.json.首先,如果您使用的是 dotnet core,请使用 AWSSDK.Extensions.NETCore.Setup 包( https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg- config-netcore.html ),这将尊重您的 appsettings.json。

{
  "AWS": {
    "Region": "eu-west-1",
    "Profile": "theprofileyouwantouse"
  }
}

csproj: csproj:

  <ItemGroup>
    <PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="3.7.1" />
    <PackageReference Include="AWSSDK.SecurityToken" Version="3.7.1.71" />
  </ItemGroup>

Example:例子:

var config = host.Services.GetService<IConfiguration>();
var options = config.GetAWSOptions();
using var client = options.CreateServiceClient<IAmazonSecurityTokenService>();
var result = await client.GetCallerIdentityAsync(new Amazon.SecurityToken.Model.GetCallerIdentityRequest { });

This will try to pick up encrypted credentials in ~/AppData/Local/AWSToolkit and secondly based on your shared config file (~/.aws/config).这将尝试在 ~/AppData/Local/AWSToolkit 中获取加密凭证,然后根据您的共享配置文件 (~/.aws/config)。 As of november 2021, it does not utilize aws_access_key_id, aws_secret_access_key, aws_session_token in the version 1 shared credentials file (~/.aws/credentials)*截至 2021 年 11 月,它不使用版本 1 共享凭证文件 (~/.aws/credentials) 中的 aws_access_key_id、aws_secret_access_key、aws_session_token*

Next, if the roles you are assuming are AWS SSO, you need the following packages in your csproj file:接下来,如果您承担的角色是 AWS SSO,您的 csproj 文件中需要以下包:

    <PackageReference Include="AWSSDK.SSO" Version="3.7.0.94" />
    <PackageReference Include="AWSSDK.SSOOIDC" Version="3.7.0.94" />

*If you happen to have invertedly added your credentials to your shared credentials file (~/.aws/credentials) as [profile myprofile] instead of just [myprofile] the SDK will not behave as you expected, so delete that. *如果您碰巧将您的凭据反向添加到您的共享凭据文件 (~/.aws/credentials) 作为 [profile myprofile] 而不仅仅是 [myprofile] SDK 将不会像您预期的那样运行,因此请删除它。 If your credentials file is fine, then you don't have to touch it, but keep in mind that the SDK will noe use the cached credentials if any found in that file.如果您的凭据文件没问题,那么您不必触摸它,但请记住,如果在该文件中找到任何缓存凭据,SDK 将不会使用。

Now, the author does not use the AWSSDK.Extensions.NETCore.Setup package, which means that we are getting a slightly different credentials resolving path.现在,作者没有使用 AWSSDK.Extensions.NETCore.Setup 包,这意味着我们得到的凭证解析路径略有不同。 Most importantly: appsettings.json is not respected, this means you must specify the profile you want to use differently, for example by using the AWS_PROFILE environment variable.最重要的是:appsettings.json 不受尊重,这意味着您必须指定要以不同方式使用的配置文件,例如使用 AWS_PROFILE 环境变量。

Secondly, we are landing directly in the FallbackCredentialsFactory.cs which does this when resolving credentials:其次,我们直接登陆 FallbackCredentialsFactory.cs,它在解析凭据时执行此操作:

            CredentialsGenerators = new List<CredentialsGenerator>
            {
#if BCL
                () => new AppConfigAWSCredentials(),            // Test explicit keys/profile name first.
#endif
                () => AssumeRoleWithWebIdentityCredentials.FromEnvironmentVariables(),
                // Attempt to load the default profile.  It could be Basic, Session, AssumeRole, or SAML.
                () => GetAWSCredentials(credentialProfileChain),
                () => new EnvironmentVariablesAWSCredentials(), // Look for credentials set in environment vars.
                () => ECSEC2CredentialsWrapper(proxy),      // either get ECS credentials or instance profile credentials
            };

Now the last step in resolving credentials "ECSEC2" has a fallback which returns this:现在解析凭据“ECSEC2”的最后一步有一个回退,它返回:

DefaultInstanceProfileAWSCredentials.Instance

Which leads us to the error which the author sees.这导致我们看到作者看到的错误。

Summary:概括:

  1. If you are not using AWSSDK.Extensions.NETCore.Setup, specify the profile using an ENV-variable in launch.json or launchSettings.json if you are going to use the default constructor like the author如果您不使用 AWSSDK.Extensions.NETCore.Setup,请在 launch.json 或 launchSettings.json 中使用 ENV 变量指定配置文件,如果您要像作者一样使用默认构造函数
  2. Rember to add the AWS SSO packages if needed如果需要,请记住添加 AWS SSO 包

In the project defaults.json, verify the profile value.在项目 defaults.json 中,验证profile值。 in my case it was empty "profile": "" .就我而言,它是空"profile": "" After setting the profile name, was able to publish设置配置文件名称后,能够发布

I was deploying to a dot net core web application to an on prem server over IIS and had the same exact issue.我正在通过 IIS 将 dot net core web 应用程序部署到本地服务器,并且遇到了同样的问题。 No matter what I did the application would not recognize my credentials configured via AWS CLI (aws configure).无论我做什么,应用程序都无法识别我通过 AWS CLI (aws configure) 配置的凭证。

I ended up setting AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY with my keys via the Windows environment variables and restarting the server.我最终通过 Windows 环境变量使用我的密钥设置 AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY 并重新启动服务器。

The following article was very helpful in understanding the AWS SDK credential loading Client Factory https://www.stevejgordon.co.uk/credential-loading-and-the-aws-sdk-for-dotnet-deep-dive以下文章对了解 AWS SDK 凭据加载客户端工厂非常有帮助https://www.stevejgordon.co.uk/credential-loading-and-the-aws-sdk-for-dotnet-deep-dive

In my case the config and credentials files were set up correctly in C:/Users//.aws folder so they should have been found by default.在我的情况下,配置和凭据文件已在 C:/Users//.aws 文件夹中正确设置,因此默认情况下应该可以找到它们。 However, on a previous project I had set up different credentials (no longer valid) in C:/Users//AppData/Local/AWSToolkit referred to in AWS documentation as the AWS SDK Store.但是,在之前的项目中,我在 C:/Users//AppData/Local/AWSToolkit 中设置了不同的凭证(不再有效),在 AWS 文档中称为 AWS SDK Store。 The SDK store is always checked first and then falls back to the default user credentials file.始终首先检查 SDK 存储,然后回退到默认用户凭据文件。 See the following: https://aws.amazon.com/blogs/developer/referencing-credentials-using-profiles/ .请参阅以下内容: https ://aws.amazon.com/blogs/developer/referencing-credentials-using-profiles/。 The simplest solution in my case was simply to delete the files in the AWSToolkit folder.在我的案例中,最简单的解决方案就是删除 AWSToolkit 文件夹中的文件。 As an alternative I could have set up the SDK Store correctly.作为替代方案,我可以正确设置 SDK 商店。

I had the same problem in .NET core 5 with AWS and I solved it by :我在使用 AWS 的 .NET core 5 中遇到了同样的问题,我通过以下方式解决了它:

what I had :我有什么:

I had config and credentials files in C:\Users\.aws.我在 C:\Users\.aws 中有配置和凭据文件。

In StartUp.cs after initialized AWS options I added:在初始化 AWS 选项后的 StartUp.cs中,我添加了:

#if Debuge
   options.Profile="default";
   options.ProfileLocations="C:\\Users\\.aws\\credentials";
#endif

If anyone is using docker-compose and getting this error, I added this to my docker-compose.override.yml file and it was able to read my credentials如果有人在使用 docker-compose 并收到此错误,我将其添加到我的 docker-compose.override.yml 文件中,并且它能够读取我的凭据

volumes:
  - ~/.aws/:/root/.aws:ro

I had the same issue - Amazon.Runtime.AmazonServiceException: 'Unable to get IAM security credentials from EC2 Instance Metadata Service.'我遇到了同样的问题 - Amazon.Runtime.AmazonServiceException:“无法从 EC2 实例元数据服务获取 IAM 安全凭证。”

I was working with Dot Net Core Microservice, I got this error.我正在使用 Dot Net Core 微服务,我收到了这个错误。

Solution - I removed the AWS credentials path which was mentioned in all the different setting files like appsettings.Debug.json and appsettings.Development.json.解决方案 - 我删除了所有不同设置文件(如 appsettings.Debug.json 和 appsettings.Development.json)中提到的 AWS 凭证路径。

This AWS credentials path should be mentioned in only the file appsettings.json.此 AWS 凭证路径应仅在文件 appsettings.json 中提及。 remove from all other files.从所有其他文件中删除。

Posting this here as it is at least the 2nd time I've caused the error via a self-inflicted misconfiguration.将此发布在这里,因为这至少是我第二次通过自我造成的错误配置导致错误。

VS 2022
AWS Toolkit 1.38.0.0

None of the existing answers worked, but they did point to a few configuration issues.现有答案均无效,但它们确实指出了一些配置问题。 One or more of these configuration settings did/could cause the error:这些配置设置中的一项或多项确实/可能导致错误:

AWS Toolkit Explorer AWS 工具包资源管理器

When using the AWS Toolkit Explorer to define the profile, make sure the correct profile is selected.使用 AWS Toolkit Explorer 定义配置文件时,请确保选择了正确的配置文件。

Personally, I no longer define a default profile.就个人而言,我不再定义default配置文件。 I use named profiles for all credentials.我对所有凭据使用命名配置文件。 This is especially useful when dealing with multiple profiles (I have at least 10+).这在处理多个配置文件(我至少有 10 个以上)时特别有用。

Environmental Variables环境变量

I've found the most consistent way to run an AWS process locally (or as a service) is to set the AWS_PROFILE Environmental Variable.我发现在本地(或作为服务)运行 AWS 进程的最一致的方法是设置AWS_PROFILE环境变量。 Example:例子:

Environment.SetEnvironmentVariable( "AWS_PROFILE", "<profle_name>", EnvironmentVariableTarget.Process );

In this particular case, I used an old profile name that had been changed.在这种特殊情况下,我使用了一个已更改的旧配置文件名称。 In other words, if you're using an Environmental Variable to set the AWS_PROFILE , make sure the profile name is correct.换句话说,如果您使用环境变量来设置AWS_PROFILE ,请确保配置文件名称是正确的。

When using the Environmental Variable approach, do not set an Environmental Variable for AWS_REGION .使用环境变量方法时,请勿AWS_REGION设置环境变量。 The AWS_PROFILE defines the region when the profile is correctly defined.正确定义配置文件时, AWS_PROFILE定义区域。

Other Thoughts...其他想法...

When configured correctly, there should be no need for any other AWS environmental variable.正确配置后,应该不需要任何其他 AWS 环境变量。 Not even empty variables for:甚至没有空变量:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_SESSION_TOKEN

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

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