AWS SDK for PHP无法读取/root/.aws凭证的问题求助
我正在安装AWS SDK for PHP,根据官方指南,配置和凭证文件应存放在~/.aws目录下,在我的服务器上该路径实际为/root/.aws。按此配置后,使用已知可行的代码上传测试文件至S3时,遇到如下错误:
Fatal error: Uncaught Aws\Exception\CredentialsException: Error retrieving credentials from the instance profile metadata service. (cURL error 7: Failed to connect to 169.254.169.254 port 80: Connection refused ... for http://169.254.169.254/latest/meta-data/iam/security-credentials/)...
将凭证放在/home/mysite/.aws目录下则可正常运行,但这并非理想方案——AWS凭证会被纳入用户每日备份,且凭证不应存放在用户目录附近。尝试修改权限(从600改为644)但问题依旧,请问如何让SDK读取/root/.aws中的凭证?
测试代码如下:
require ('/home/mysite/public_html/lib/composer/vendor/autoload.php'); use Aws\S3\S3Client; $file = '/home/mysite/public_html/images/christmas.jpg'; $sharedConfig = [ 'version' => 'latest', 'region' => 'eu-west-1', ]; // Create an SDK class used to share configuration across clients. $sdk = new Aws\Sdk($sharedConfig); // Create an Amazon S3 client using the shared configuration data. $client = $sdk->createS3(); $result = $client->putObject([ 'Bucket' => 'mybucket', 'Key' => 'full/christmas.jpg', 'CacheControl' => 'max-age=31536000', 'ContentType' => 'image/jpeg', 'SourceFile' => $file, 'ACL' => 'public-read', ]);
1. 直接指定凭证文件路径
在SDK配置中显式添加credentials参数,指向/root/.aws/credentials文件,强制SDK读取该路径的凭证:
$sharedConfig = [ 'version' => 'latest', 'region' => 'eu-west-1', 'credentials' => [ 'file' => '/root/.aws/credentials', ], ];
2. 通过环境变量指定凭证目录
设置环境变量让SDK知晓凭证文件的位置:
- 临时生效(命令行测试用):
export AWS_SHARED_CREDENTIALS_FILE="/root/.aws/credentials" export AWS_CONFIG_FILE="/root/.aws/config"
- 永久生效:将上述两行添加到PHP运行用户的环境配置文件(如
/home/mysite/.bashrc)或服务器全局环境配置中,重启服务后生效。
3. 调整目录与文件权限
确保PHP运行用户能读取/root/.aws下的文件:
- 将
/root/.aws的用户组改为PHP运行用户所在组(假设PHP用户组为mysite):
chown -R root:mysite /root/.aws
- 调整权限,保证组用户有读取权限,同时避免无关用户访问:
chmod 750 /root/.aws chmod 640 /root/.aws/credentials chmod 640 /root/.aws/config
4. 禁用实例元数据服务查找
你的服务器不在AWS EC2上,SDK默认优先尝试的实例元数据服务请求会失败,可在配置中禁用该逻辑,强制SDK使用本地凭证:
$sharedConfig = [ 'version' => 'latest', 'region' => 'eu-west-1', 'credentials' => [ 'use_aws_metadata' => false, ], ];
结合第一种方法指定路径,效果更稳定。
内容的提问来源于stack exchange,提问作者Mark

