SQS - SDKの導入 (Node.js)
ゴール:EC2インスタンスにNode.jsをインストールし、SQSへの接続ができるようになる。
Node.jsをEC2インスタンスにインストールしてみる
こんなエラーが出る
[root@ip-172-31-44-13 awsnodesample]# cat getCredentials.js
var AWS = require("aws-sdk");
AWS.config.getCredentials(function(err) {
if (err) console.log(err.stack);
// credentials not loaded
else {
console.log("Access key:", AWS.config.credentials.accessKeyId);
}
});
[root@ip-172-31-44-13 awsnodesample]#
[root@ip-172-31-44-13 awsnodesample]# node getCredentials.js
CredentialsError: Could not load credentials from any providers
at IncomingMessage.<anonymous> (/home/ec2-user/awsnodesample/node_modules/aws-sdk/lib/util.js:904:34)
at IncomingMessage.emit (node:events:406:35)
at IncomingMessage.emit (node:domain:470:12)
at endReadableNT (node:internal/streams/readable:1329:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
IAMユーザーを作って、アクセスキーとシークレットキーを取得
ダウンロードしたcsvファイルをもとに以下の設定を実施
export AWS_ACCESS_KEY_ID=Access key ID
export AWS_SECRET_ACCESS_KEY=Secret access key
↑を実行してみると
[root@ip-172-31-44-13 awsnodesample]# node getCredentials.js
これがうまくいく😊
リージョンを設定
export AWS_REGION=us-east-2
以下のjsを作成し実行してみる
※test_sqs_0というキューを事前に作成しておいた
[root@ip-172-31-44-13 awsnodesample]# cat sqs_getqueueurl.js
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'us-east-2'});
// Create an SQS service object
var sqs = new AWS.SQS({apiVersion: '2012-11-05'});
var params = {
QueueName: 'test_sqs_0'
};
sqs.getQueueUrl(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data.QueueUrl);
}
});
[root@ip-172-31-44-13 awsnodesample]#
以下のようにURLが取得できた
[root@ip-172-31-44-13 awsnodesample]# node sqs_getqueueurl.js
Success https://sqs.us-east-2.amazonaws.com/157634048600/test_sqs_0
この記事が気に入ったらサポートをしてみませんか?