I'm trying to upload a file to a S3 bucket. First I create an AmazonS3 client using InstanceProfileCredentialsProvider and I get IAM credentials from the instance metadata:
final AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new InstanceProfileCredentialsProvider(false))
.withRegion("eu-west-1").build();
The role associated to this instance has a policy to access and upload files to a bucket:
{
"Version":"2012-10-17",
"Statement":{
"Action":[
"kms:Decrypt",
"kms:DescribeKey",
"kms:Encrypt",
"kms:GenerateDataKey",
"kms:ReEncryptFrom",
"kms:ReEncryptTo",
"s3:GetObject",
"s3:ListBucket",
"s3:PutObject*"
],
"Effect":"Allow",
"Resource":[
"arn:aws:kms:eu-west-1:[account-id]:key/[key-id]",
"arn:aws:s3:::[bucket-name]",
"arn:aws:s3:::[bucket-name]/[path-were-to-save-file]/*"
]}}
I'm trying to upload the file like this:
final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file);
s3Client.putObject(request);
but I get Access Denied AmazonS3ClientException. Any idea what I am missing?
I also tried to include the kms key to the request:
final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file)
.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams("[key-id]"));
but it tries to retrieve the key from my account:
arn:aws:kms:eu-west-1:[my-account-id]:key/[key-id]
not the account specified in the policy:
arn:aws:kms:eu-west-1:[account-id]:key/[key-id]
and throws KMSNotFoundException