使用PHP SDK将AWS S3上传到法兰克福地区-拒绝访问错误

时间:2018-07-23 17:11:42

标签: php amazon-web-services amazon-s3

在开发环境中,以下代码可以完美地将文件上传到AWS S3 Frankfurt地区,并按照

中所述设置证书
  

https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html

PHP

require("aws.phar");
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$bucket = 'my bucket';    
$filepath = 'currentfilepath.jpeg';
$filename = 'newfilename.jpeg';

$s3 = S3Client::factory(array(
    'key'    => 'XXX',
    'secret' => 'YYY',
    'region'  => 'eu-west-2',
    'version' => 'latest'       
));

try {
   $result = $s3->putObject(array(
        'Bucket' => $bucket,
        'Key'    => $filename,
        'SourceFile'   => $filepath,
        'ACL'    => 'public-read'
         ));
  var_dump($result);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

但是,在已部署的环境中,出现“拒绝访问”错误。

  

在以下位置执行“ PutObject”时出错   “ https://s3.eu-west-2.amazonaws.com/mybucket/newfilename.jpeg”;   AWS HTTP错误:客户端错误:403 AccessDenied(客户端):访问被拒绝

与开发和部署之间的唯一区别是,我没有开发环境中的凭据文件。我想知道如何在已部署的环境中管理凭据以使其工作吗?

2 个答案:

答案 0 :(得分:1)

我认为Reza Mousavi的回答应该有所帮助。

但是我通过在aws-elasticbeanstalk-ec2-role中添加AmazonS3FullAccess来解决此问题。这是通过

完成的
   IAM control panel >> Roles >> 
   Choose aws-elasticbeanstalk-ec2-role >> Attach Policies:AmazonS3FullAccess

谢谢

答案 1 :(得分:0)

您应该创建新的API密钥/秘密,并为访问S3存储桶分配正确的IAM,并发布新的凭据(如您之前提到的文档):

https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html

此外,如果您的EC2具有公共IP地址,则可以通过更改S3存储桶策略来授予访问权限:

   {
"Version": "2012-10-17",
"Id": "Policy1462808223348",
"Statement": [
    {
        "Sid": "Stmt1462808220978",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::714656454815:role/ecsInstanceRole"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::bucket-name/*",
        "Condition": {
            "IpAddress": {
                "aws:SourceIp": "YOUR-PUBLIC-IP/32"
            }
        }
    }
]
}