AWS S3 Sample Code for credentialProvider Considering IAM Role [AWS SDK for JavaScript]

Tadashi Shigeoka ·  Tue, May 11, 2021

I’ll introduce sample code for using credentialProvider with AWS S3 considering IAM roles.

The sample code is written in TypeScript using aws-sdk npm.

AWS

AWS S3 Sample Code for credentialProvider

import * as AWS from 'aws-sdk';

private createClient() {
  const config: AWS.S3.Types.ClientConfiguration = {
    endpoint: new AWS.Endpoint(process.env.AWS_S3_ENDPOINT),
    credentialProvider: new AWS.CredentialProviderChain(),
    sslEnabled: true,
    signatureVersion: 'v4',
  };

  return new AWS.S3(config);
}

AWS S3 Sample Code for credentialProvider (Also Considering minio)

import * as AWS from 'aws-sdk';

private createClient() {
  const config: AWS.S3.Types.ClientConfiguration = {
    endpoint: new AWS.Endpoint(process.env.AWS_S3_ENDPOINT),
    s3ForcePathStyle: true,
    sslEnabled: true,
    signatureVersion: 'v4',
  };

  if (
    process.env.NODE_ENV === 'development' ||
    process.env.NODE_ENV === 'test'
  ) {
    // NOTE: minio のために @deprecated な property も設定
    config.accessKeyId = process.env.AWS_S3_ACCESS_KEY_ID;
    config.secretAccessKey = process.env.AWS_S3_SECRET_ACCESS_KEY;
  } else {
    config.credentialProvider = new AWS.CredentialProviderChain();
  }

  return new AWS.S3(config);
}

That’s all from the Gemba about using credentialProvider with AWS S3 considering IAM roles.

Reference Information