amazon-web-servicesamazon-s3amazon-ec2aws-cliaws-php-sdk

Cannot connect to s3 from ec2 via php sdk - cURL error 7


I am having an issue with my EC2 instance connecting to our S3 Bucket.

On my ec2 instance, I have php, httpd, aws-cli, aws-sdk installed. I am able to reach the index page where the code is located. Credentials file is set up /usr/share/httpd/.aws/credentials

Code I am using from the Getting Started Basic Usage Guide

$sharedConfig = [
    'profile' => 'default',
    'region' => 'us-west-1',
    'version' => 'latest',
    'debug' => true
];

// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk($sharedConfig);

// Use an Aws\Sdk class to create the S3Client object.
$s3Client = $sdk->createS3();

// Send a PutObject request and get the result object.
$result = $s3Client->putObject([
    'Bucket' => 'my-bucket',
    'Key' => 'my-key',
    'Body' => 'this is the body!'
]);

Using the debug mode results in a large text dump. I believe that the main error belongs to the s3 bucket refusing connection from the code.

Entering step attempt, name 'ApiCallAttemptMonitoringMiddleware' ------
 no changes * Trying IP_ADDRESS... * TCP_NODELAY set * Immediate connect fail for IP_ADDRESS: Permission denied * 
Closing connection 0 <- Leaving step attempt, name 'ApiCallAttemptMonitoringMiddleware' --------- error was set to array(13) { ["instance"]=> string(32) "0000000078dd756a0000000053d619cb" ["class"]=> string(28) "Aws\S3\Exception\S3Exception" ["message"]=> string(241) "Error executing "PutObject" on "https://ec2-server-test.s3.us-west-1.amazonaws.com/my-key"; 
AWS HTTP error: cURL error 7: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://ec2-server-test.s3.us-west-1.amazonaws.com/my-key" ["file"]=> string(58) "/var/www/vendor/aws/aws-sdk-php/src/WrappedHttpHandler.php" ["line"]=> int(195) ["trace"]=> string(1925) "#0 /var/www/vendor/aws/aws-sdk-php/src/WrappedHttpHandler.php(100)

Curl error 7: Failed to connect() to host or proxy.

When connecting via SSH to my instance, I am able to correctly run the aws-cli s3 commands and receive the proper response.

This code also works locally on my machine hosting via xampp.


Solution

  • The issue is that the webserver, httpd, was not able to communicate with outside networks. That's why I could use the aws cli and telnet/ ping from the command line, but it was unreachable from the browser.

    After running the command setsebool -P httpd_can_network_connect 1, I was able to connect to my s3 buckets.