使用符合AWS要求的凭据进行访问EC2 API。假定凭据是由已经过期或无效的AWS访问密钥和秘密密钥组成的凭据。以下是使用正确凭据进行AWS SDK EC2 API访问的代码示例:
const AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});
// Set the credentials
const credentials = new AWS.SharedIniFileCredentials({profile: 'PROFILE NAME'});
AWS.config.credentials = credentials;
// Create EC2 service object
const ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
// Call EC2 to obtain a list of the latest AMIs
ec2.describeInstances(function(err, data) {
if (err) {
console.log("Error:", err.stack);
} else {
console.log("Success:", JSON.stringify(data));
}
});
注意,此示例假定你已在计算机上配置了AWS CLI和AWS CLI配置文件。要使用正确的AWS访问密钥和秘密密钥,你可以在AWS IAM控制台中创建一个新的IAM用户,然后为该用户创建访问密钥和秘密密钥。使用此凭据配置AWS CLI(aws configure
),并将上面示例代码中的“PROFILE NAME”替换为AWS CLI配置文件中的[profile]值。