0
votes

In development environment, below code works perfectly to upload a file to AWS S3 Frankfurt region with credentials set up as mentioned in

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";
}

However in deployed environment, I get Access denied error.

Error executing "PutObject" on "https://s3.eu-west-2.amazonaws.com/mybucket/newfilename.jpeg"; AWS HTTP error: Client error: 403 AccessDenied (client): Access Denied

The only difference from development and deployed is that I do not have a credential file like in dev environment. I wonder how to manage credentials in deployed environment to make this work?

2

2 Answers

1
votes

Reza Mousavi's answer in my view should help.

But I got this fixed by adding AmazonS3FullAccess to aws-elasticbeanstalk-ec2-role. This is done from the

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

Thanks

0
votes

You should create the new API key/secret and assign the right IAM for access to your S3 bucket and publish the new credentials like the document you mentioned before:

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

Also, if your EC2 has a public IP address, you can grant access by the change in your S3 bucket policy:

   {
"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"
            }
        }
    }
]
}