AWS SDK连接疑问:示例代码如何识别我的AWS账户?
Great question! I totally get why this might feel like magic at first—there’s no obvious account ID or credentials hardcoded in the code, yet it works perfectly. Let’s break down exactly how the AWS SDK for Node.js connects to your account:
The Default Credential Provider Chain
The AWS SDK is built to automatically look for credentials in a specific order (called the credential provider chain) without you having to explicitly pass them into the AWS.S3() constructor. Here’s the order it checks:
- Environment Variables: First, it looks for
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEYset as system environment variables. If these exist, the SDK uses them to authenticate. - Shared Credentials File: If no environment variables are found, it checks the default credentials file. On Linux/macOS, this is located at
~/.aws/credentials; on Windows, it’sC:\Users\<YourUsername>\.aws\credentials. This file is usually created when you run theaws configureCLI command, and it stores your access key, secret key, default region, and output format under a[default]profile (you can also have multiple profiles here). - IAM Roles for AWS Services: If your code is running on an AWS service like an EC2 instance, EKS pod, or ECS task that has an IAM role attached, the SDK will automatically fetch temporary credentials from the instance metadata service (IMDS) or task metadata endpoint. This is super useful for server-side code because you don’t have to manage long-term credentials at all.
- Explicitly Configured Credentials (Not Used Here): While you could hardcode credentials directly in the code (like
new AWS.S3({ accessKeyId: 'YOUR_KEY', secretAccessKey: 'YOUR_SECRET' })), this is strongly discouraged for security reasons—and your sample code doesn’t do this anyway.
Why Your Code Works
In your case, since the code is running locally and successfully uploads to your account, you’ve almost certainly already configured credentials on your machine (most likely via the aws configure command, which populates the ~/.aws/credentials file). The SDK picks up those credentials automatically through the chain above, which is why it knows exactly which AWS account to use.
To confirm this, you can run the following CLI command to see your current configured credentials:
aws configure list
Or you can open the ~/.aws/credentials file directly to view the stored credentials associated with your account.
内容的提问来源于stack exchange,提问作者J Seabolt

