简体   繁体   中英

Can't access S3 bucket using IAM Role from an EC2 instance

I'm trying to download a file from a private S3 bucket using the PHP SDK (on an EC2 instance).

I create an IAM role and attached the AmazonS3FullAccess to it.

I created the S3 bucket and this is the bucket policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::206193043625:role/MyRoleName"
      },
      "Action": [
        "s3:PutObject",
        "s3:GetObject",
        "s3:DeleteObject"
      ],
      "Resource": "arn:aws:s3:::config-files/*"
    }
  ]
}

Then on the PHP side I make a curl request to http://169.254.169.254/latest/meta-data/iam/security-credentials/MyRoleName , I get a JSON back instantiate the S3Client and try to download it, but I'm getting this error message:

Error executing "GetObject" on " https://files.s3.us-west-2.amazonaws.com/us-west-2__config.php "; AWS HTTP error: Client error: GET https://files.s3.us-west-2.amazonaws.com/us-west-2__config.php resulted in a 403 Forbidden response:

AccessDenied

Access DeniedC84D80 (truncated...) AccessDenied (client): Access Denied -

AccessDenied

Access DeniedC84D80DE6B2D35FD6sDWIYK98nSH+Oa8lBH7lD91rfHospDeo0jZKFDdo0CaeY8aX6Wb/s2ja5qeYxCBuLwDJ2AqSl0=

Can anyone point me to a direction?

There is no need to access 169.254.169.254 directly. The AWS SDK for PHP will automatically retrieve credentials.

Simply create the S3 client without specifying any credentials.

Since you've already provided AmazonS3FullAccess role to your EC2 instance, you need not to do anything else(ie accessing metadata api). Directly access your S3 client & it shall work as expected from your compute instance.

For accessing S3 Bucket from EC2 Instance follow the below steps:

* Create an IAM Role with S3 Full Access.
* Launch an EC2 instance with the role attached to it.
* SSH to your EC2 instance with root permissions.
* Type the command:    aws s3 ls. It will display all the buckets which are there in S3.

Since the role is attached to the EC2 instance, there is no need to mention the security credentials.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM