Home > database >  AWS SDK v3 can't get region from profile
AWS SDK v3 can't get region from profile

Time:06-01

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

CodePudding user response:

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.

CodePudding user response:

The S3 Constructor uses the region property on the the level of the configuration object as credentials, thus you should use something like:

const s3Client = new S3({
   credentials: fromIni({
        profile: 'myprofile',
   }),
   region: 'eu-west-1'
});

The fromIni doc doesn't talks about region, I guess it is not meant for this.

About loading the config file, I think you are looking for the environment variable AWS_SHARED_CREDENTIALS_FILE, see here (didn't test it though). However, as @CherryDT commented, you may want to declare it explicitly, it may change depending on the situation.

  • Related