JRivera294
JRivera294

Reputation: 309

Upload file to s3 with PHP on a EC2 instance throw credentials error, but works locally

I have tested my function to upload images to s3 on my machine, but when I go to production on ec2, by a strange reason, it doesn't work.

This is the error:

CredentialsException in InstanceProfileProvider.php line 79:Error retrieving credentials from the instance profile metadata server. (Client error: 404)

This is the code:

$destinationPath = 'images/institutions/logos';
    $extension = $data['int_logo']->getClientOriginalExtension();
    $keyname = $destinationPath.'/'.$username.'.'.$extension;
    $bucket = "*****";
    $filepath = $data['int_logo'];

    $s3 = new S3Client([
        'region'  => 'us-west-2',
        'version' => '2006-03-01',
        'scheme' => 'http'
    ]);

    $result = $s3->putObject(array(
        'Bucket'       => $bucket,
        'Key'          => $keyname,
        'SourceFile'   => $filepath,
        'ACL'          => 'public-read'
    ));

    return $result['ObjectURL'];
}

And this is my s3 policy:

{
"Version": "2012-10-17",
"Id": "*******",
"Statement": [
    {
        "Sid": "******",
        "Effect": "Allow",
        "Principal": "*",
        "Action": [
            "s3:GetObject",
            "s3:PutObjectAcl",
            "s3:PutObject"
        ],
        "Resource": "arn:aws:s3:::****/*"
    }
]}

I don't know why it throw an error with the credentials, I'm not using any authentication, everyone can put a file on this bucket. And it works 100% on my machine.

Upvotes: 2

Views: 616

Answers (2)

JRivera294
JRivera294

Reputation: 309

Solution to establish an anonymous connection:

Change:

    $s3 = new S3Client([
        'region'  => 'us-west-2',
        'version' => '2006-03-01',
        'scheme' => 'http',
    ]);

To:

    $s3 = new S3Client([
        'region'  => 'us-west-2',
        'version' => '2006-03-01',
        'scheme' => 'http',
        'credentials' => false
    ]);

I still don't know why my local machine can establish the connection, but the ec2 server can't do it without this line.

Upvotes: 1

Paul A.T. Wilson
Paul A.T. Wilson

Reputation: 860

I have had the same problem in the past. I ended up having to put the following code in, that worked for me:

$s3->path_style = true;

Upvotes: 0

Related Questions