わたねこコーリング

野良プログラマ発、日々のアウトプット

AWS DcoumentDB クラスタに SSH トンネル越しで Node.js プログラムから接続する

小ネタですが表題件、地味にハマったので備忘録として。

下記情報を元に、VPC 外(つまりおうち or 職場のパソコン)で開発中の Node.js プログラムから DocumentDB に接続しようとしたらタイムアウトでなかなか接続できませんですた。

docs.aws.amazon.com

docs.aws.amazon.com

あれこれトライ&エラーを繰り返して、ようやく動作するようになったのが下記コード。

var MongoClient = require('mongodb').MongoClient,
  f = require('util').format,
  fs = require('fs');

//Specify the Amazon DocumentDB cert
var ca = [fs.readFileSync("/somewhere/over/the/rainbow/rds-combined-ca-bundle.pem")];

//Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set, 
//  and specify the read preference as secondary preferred
var client = MongoClient.connect(
'mongodb://<sample-user>:<password>@localhost:27017/?ssl=true', 
{
  useUnifiedTopology: true,
  sslValidate: false,
  sslCA:ca,
  useNewUrlParser: true
},
function(err, client) {
    if(err)
        throw err;
        
    //Specify the database to be used
    db = client.db('sample-database');
    
    //Specify the collection to be used
    col = db.collection('sample-collection');

    //Insert a single document
    col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
      //Find the document that was previously written
      col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
        //Print the result to the screen
        console.log(result);
        
        //Close the connection
        client.close()
      });
   });
});

キモは、MongoClient.connect() に渡す URL とオプションでした(↓)。AWS サンプルコードとの差分はこちら http://mergely.com/TXE4OQbw/ を。

  • URL のパラメータは、DocumentDB コンソールで提供されるものに含まれている ssl_ca_certs やら replicaSet 等は一切取っ払って、ssl=true だけにする。
  • オプションの sslValidate は false に(mongo shell オプションの sslAllowInvalidHostnames に相当するっぽい)。
  • useUnifiedTopology も付与すると吉(将来の設計変更に関するワーニングを抑止できる)。

以上。尚、諸元は以下のとおりです。

  • DocumentDB エンジンバージョン docdb 3.6.0
  • Node.js v12.16.0
  • MonboDB Node.js driver v3.5.6