'Is using InstanceProfileCredentialsProvider correct way to connect to AWS S3 from Ec2 instance?

Until my code works, I have set bucket policy too wide open.

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

I am using Elastic BeanStalk which in turn uses AWS Ec2. The Ec2 instance has aws-elasticbeanstalk-ec2-role which was provided FullAccess to S3 (I understand full access is dangerous).

I'm using the following java code in my webapp which is deployed to Ec2.

AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                  .withCredentials(new InstanceProfileCredentialsProvider(false))
                  .build();
              versionId = s3Client.putObject(new PutObjectRequest("bucketName", name, convFile))
                  .getVersionId();

1) Is this the correct way to connect to S3 from Ec2 in a java code? 2) This documentation confuses me as I'm not sure if I have to set up Environment variables and/or Java system properties and/or The default credential profiles file and/or Amazon ECS container credentials and/or Instance profile credentials ?

Please help me. I'm struck with this issue for almost a week.

PS: Following is the ec2InstanceRole assigned to my profile

Role ARN  arn:aws:iam::111111111111:role/aws-elasticbeanstalk-ec2-role
Role description  
Instance Profile ARNs  arn:aws:iam::111111111111:instance-profile/aws-elasticbeanstalk-ec2-role
Path   /
Creation time  2017-10-17 11:27 PDT

And the policies assigned to above role are

  AmazonS3FullAccess
  AWSElasticBeanstalkWebTier
  AWSElasticBeanstalkMulticontainerDocker
  AWSElasticBeanstalkWorkerTier


Solution 1:[1]

Although your code should work as is, you can remove this part all together: .withCredentials(new InstanceProfileCredentialsProvider(false)) The AWS SDK for Java will automatically pick up the instance profile if you don't specify any credential settings. You can just do this:

AmazonS3 s3Client = AmazonS3ClientBuilder.standard().build();

If that doesn't work, try removing the bucket policy from the S3 bucket completely. You don't need the bucket policy in order to allow the server using the IAM instance profile to access the bucket, and if you have a typo or something in your bucket policy it could be breaking things.

If that doesn't work, add the IAM policy assigned to the IAM instance profile to your question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark B