Search code examples
javascriptamazon-s3aws-sdkamazon-ecs

How to use ECS credentials with AWS JS SDK


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?


Solution

  • 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);