首页 > 解决方案 > Error retrieving credentials from the instance profile metadata server with credentials defined in .aws folder

问题描述

I have a web page on an AWS instance located at /var/www/html/

Until now this website used the keys AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the code itself to access files hosted on S3. For security reasons, I have removed these keys from my code and used the aws configure command to ssh to store them on the server as recommended by AWS.

I see that in my directory ~.aws/ folder has been created with 2 files: credentials and config. Both seem to be correct but in the web logs now I get the following error when trying to access files from S3:

PHP Fatal error: Uncaught Aws\Exception\CredentialsException: Error retrieving credentials from the instance profile metadata server. (Client error: 'GET http://169.254.169.254/latest/meta-data/iam/security-credentials /' resulted in a '404 Not Found resulted in a '404 Not Found' response:

<! DOCTYPE html PUBLIC "- // W3C // DTD XHTML 1.0 Transitional // EN"
"http: // www. (truncated ...)
) in /var/www/html/aws/Aws/Credentials/InstanceProfileProvider.php:88

I don't know what that URL is but I can't access it through the browser.

I have tried it with environment variables: export AWS_ACCESS_KEY_ID = xxxxx...

I have copied the .aws folder to / var / www I have given more permissions to .aws, I have changed the owner and group from root to ec2-user ...

How should I do the configuration so that my code correctly calls S3 and gets the files?

Call example that fails:

$s3 = new Aws\S3\S3Client ([
'version' => 'latest',
'region' => 'eu-central-1'
]);

if ($s3) {
    $result = $ s3-> getObject (array (
                    'Bucket' => AWS_S3_BUCKET,
                    'Key' => $s3_key,
                    'Range' => 'bytes ='. $Startpos .'- '. ($Startpos + 7)
    ));

标签: phpamazon-web-servicesamazon-s3amazon-ec2

解决方案


您可能需要将 .aws 文件夹移动到服务 (apache) 的主文件夹,而不是您的主文件夹。aws sdk 找不到它,您收到此错误。但是,aws configure在 EC2 实例中使用并不是一个好主意。

http://169.254.169.254/latest/meta-data/是只能从 EC2 实例内部获得的元数据 URL 。对于在 EC2(或其他 AWS 计算服务)中运行的服务,您不应使用 AWS 凭证来访问服务。相反,您应该创建一个 IAM 角色并将其添加到实例。在控制台中,您可以使用 Actions 按钮执行此操作:

修改 IAM 角色

仅向角色分配所需的权限(S3 读/写)。

您的代码 ( $s3 = new Aws\S3\S3Client) 将尝试加载默认凭据。它将首先尝试调用元数据服务并获取与 IAM 角色权限对应的临时凭证。


推荐阅读