How to use ECS credentials with AWS JS SDK

2019-07-08 16:49发布

I'm trying to access a S3 Bucket using the AWS JS SDK but without success.

I got a task definition that uses a task role called Foo. This task role as an attached policy to access to the S3 Bucket:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:GetObject"
      ],
      "Resource": "arn:aws:s3:::foo-bucket"
    }
  ]
}

It says in the AWS Documentation about loading credentials from IAM roles for EC2 that I should configure my instance to use IAM roles. But I can't find anything about that in the AWS documentation.

I tried to define the credentials using the AWS.ECSCredentials class:

const options = {
  apiVersion: '2006-03-01',
  region: bucketSettings.region,
  credentials: new AWS.ECSCredentials({
    httpOptions: { timeout: 5000 }, // 5 second timeout
    maxRetries: 10, // retry 10 times
    retryDelayOptions: { base: 200 }, // see AWS.Config for information
  })
};

this.s3Instance = new AWS.S3(options);

When I try to access a file in the S3 Bucket:

const document = await this.s3Instance
  .getObject({ Bucket: bucketSettings.name, Key: key })
  .promise();

return document;

I still got an

Access Denied

Any idea what I'm missing there?

1条回答
我命由我不由天
2楼-- · 2019-07-08 17:51

There was an error in the policy to access the S3 Bucket (note the /* at the end of the resource):

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

Plus, the credentials option provided to the AWS SDK is not needed:

const options = {
  apiVersion: '2006-03-01',
  region: bucketSettings.region,
};

this.s3Instance = new AWS.S3(options);
查看更多
登录 后发表回答