How to use RDS MySQL certs with node-db-migrate

Recently I set up a project which uses a MySQL database hosted on Amazon RDS. By default, MySQL traffic is not encrypted, but RDS provides certificates which can be used to encrypt your traffic to RDS. Download the file for your particular region, and then using it with node mysql is quite straightforward by adding an ssl section to your config:

const connection = mysql.createConnection({
  config: {
    host     : 'host,
    database : 'database,
    user     : 'user,
    password : 'password,
    ssl: {
      rejectUnauthorized: true,
      ca: require('./eu-west-1-bundle.pem'),
    },
  }
});

Getting this to work with node-db-migrate is a bit trickier, because its configuration file is a JSON file, and so we cannot use require in the same way as above. The solution is to take the .pem file above, and convert it to a one-line string where the newlines are replaced with \n. The command below from ServerFault will handle this for you if you are running Linux or Mac:

awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' eu-west-1-bundle.pem

Take the result of the above command, and add it directly inline in your database.json file.

  "production": {
    "database": { "ENV": "DB_NAME" },
    "host": { "ENV": "DB_HOST" },
    "user": { "ENV": "DB_USER" },
    "password": { "ENV": "DB_PASS" },
    "port": { "ENV": "DB_PORT" },
    "ssl": {
      "rejectUnauthorized": true,
      "ca": "-----BEGIN CERTIFICATE-----\n..."
    },
    "driver": "mysql",
    "multipleStatements": true
  }

Your migrations will be done over an encrypted connection!