Search code examples
node.jsaws-sdkaws-sdk-nodejs

AWS SDK v3 can't get region from profile


I'm initializing an s3 client with credentials coming from a profile in the shared ini file. I'd like to setup the default region using the same.

~\.aws\credentials

[myprofile]
aws_access_key_id = ...
aws_secret_access_key = ...

~\.aws\config

[profile myprofile]
region = eu-west-1

My code

import {S3} from '@aws-sdk/client-s3';
import {fromIni} from '@aws-sdk/credential-providers';

const s3Client = new S3({
   credentials: fromIni({
        profile: 'myprofile',
   }),
});
await s3Client.listBuckets({});

The error I'm getting is Error: Region is missing and the output of calling fromIni is

{
  accessKeyId: '...',
  secretAccessKey: '...',
  sessionToken: undefined
}

Why region isn't loaded from the shared config file?


UPDATE

fromIni docs notes that

Profiles that appear in both files will not be merged, and the version that appears in the credentials file will be given precedence over the profile found in the config file.

Apart from the obvious break from the usual configuration standards, moving region from config to credentials generates the same error.

~\.aws\credentials

[myprofile]
aws_access_key_id = ...
aws_secret_access_key = ...
region = eu-west-1

Solution

  • The loadSharedConfigFiles helper can read a profile's default region from the local config files, which you can then pass to the client constructor:

    import { fromIni } from '@aws-sdk/credential-providers';
    import { loadSharedConfigFiles } from '@aws-sdk/shared-ini-file-loader';
    
    const profile = 'myprofile';
    
    const s3Client = new S3Client({
      credentials: fromIni({ profile }),
      region: (await loadSharedConfigFiles()).configFile?.[profile]?.region,
    });
    

    The configFile property loads ~/aws/config and credentialsFile loads ~/.aws/credentials.