我有这个代码:
const uploadAllToS3 = () => {
console.log("upload useless file to s3, just to test access rights");
new AWS.S3().putObject({
Bucket: scheduledJobsConstants.s3BucketName(),
Key: `test/${new Date()}.txt`, Body: "Hello!",
}, (err) => {
console.log(`env:${inspect(process.env)}
provider:${AWS.CredentialProviderChain.defaultProviders}
cred:${inspect(AWS.config.credentials)}
err:${inspect(err)}`.replace(/(\r\n|\n|\r)/gm, ""));
});
};
当这段代码在 ecs 中运行时(它假设一个可以访问 S3 存储桶的角色),我会在日志中得到这个:
日志的 env 部分:
env: {
PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
HOSTNAME: '485bbd95f87d',
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI: '/v2/credentials/be3d4d7c-28b6-47e6-8081-cd746d95cb28',
ECS_CONTAINER_METADATA_FILE: '/opt/ecs/metadata/8c0b731d-49ce-4e19-bf79-64087b433876/ecs-container-metadata.json',
NODE_VERSION: '8.9.4',
YARN_VERSION: '1.3.2',
NPM_CONFIG_PROGRESS: 'false',
HOME: '/root'
}
“AWS_CONTAINER_CREDENTIALS_RELATIVE_URI”存在于环境变量中,所以我认为 sdk 应该能够获取它。
日志的提供者部分只是 sdk 代码中定义的 4 个函数,如果在 env var 中看到“AWS_CONTAINER_CREDENTIALS_RELATIVE_URI”,则其中第 4 个函数将返回“ECSCredentials”。
奇怪的是,日志的 cred 部分在 ECS 中是“null”。当我在本地运行它时(我手动承担一个角色),日志的 cred 部分是“EnvironmentCredentials”,并且文件被上传到 S3。
日志的错误部分是:
{ Forbidden: null
at Request.extractError (/app/node_modules/aws-sdk/lib/services/s3.js:557:35)
at Request.callListeners (/app/node_modules/aws-sdk/lib/sequential_executor.js:105:20) at Request.emit (/app/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/app/node_modules/aws-sdk/lib/request.js:683:14)
at Request.transition (/app/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/app/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /app/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/app/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/app/node_modules/aws-sdk/lib/request.js:685:12)
at Request.callListeners (/app/node_modules/aws-sdk/lib/sequential_executor.js:115:18)
message: null,
code: 'Forbidden',
region: null,
time: 2018-01-14T06:30:00.490Z,
requestId: '4E7121D88BA0FEF1',
extendedRequestId: 'D5uiXf5EI/OLHeaPhYX67C384ba3SF1I950N78hJWw8Vv4XGQ0opSLOQlXaxVFW31g252dx8YUc=',
cfId: undefined,
statusCode: 403,
retryable: false,
retryDelay: 118.50320949834776 }
我的代码或环境变量有什么问题吗?
我应该打印更多日志以帮助诊断此问题吗?
请指教,谢谢。
==========更新==========
我已经在 ECS 中运行了这段代码
const curlCommand = `curl http://169.254.170.2${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`;
exec(curlCommand, (error, stdout, stderr) => {
console.log(`${curlCommand} err:${error} out:${stdout} stderr:${stderr}`);
});
我得到的结果是:
{
"SecretAccessKey": "long string",
"Token": "very long string",
"Expiration": "2018-01-14T08:55:04+0000",
"AccessKeyId": "shorted string"
}
因此,如果 sdk 调用了http://169.254.170.2 ${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI},它应该得到正确的响应。