php - 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)
));
解决方案
您可能需要将 .aws 文件夹移动到服务 (apache) 的主文件夹,而不是您的主文件夹。aws sdk 找不到它,您收到此错误。但是,aws configure
在 EC2 实例中使用并不是一个好主意。
http://169.254.169.254/latest/meta-data/是只能从 EC2 实例内部获得的元数据 URL 。对于在 EC2(或其他 AWS 计算服务)中运行的服务,您不应使用 AWS 凭证来访问服务。相反,您应该创建一个 IAM 角色并将其添加到实例。在控制台中,您可以使用 Actions 按钮执行此操作:
仅向角色分配所需的权限(S3 读/写)。
您的代码 ( $s3 = new Aws\S3\S3Client
) 将尝试加载默认凭据。它将首先尝试调用元数据服务并获取与 IAM 角色权限对应的临时凭证。
推荐阅读
- javascript - “从一年开始的世纪”中的错误
- java - 当 HTTP 请求采样器失败时运行的 JMeter Beanshell 采样器
- java - Java中具有多个条件字段的动态排序
- c++ - 访问 lambda 之外的捕获变量
- go - 遵循“配置多个调度程序”Kubernetes 指南时发生错误
- sql-server - 多维数据集中的两个维度不相互连接
- ssh - 尝试连接到 PyCharm 中的内部服务器(使用远程解释器)
- angularjs - 如何在 data-ng-options 创建的下拉列表中设置默认选定选项
- java - 在 Java 中处理来自线程的中断
- python - 将具有多个参数的函数的名称从 python 字典调用到另一个函数