11import { AbstractStartedContainer , ExecResult , GenericContainer , StartedTestContainer , Wait } from "testcontainers" ;
22
3+ import { promises as fs } from "fs" ;
4+ import os from "os" ;
5+ import path from "path" ;
6+ import { FileToCopy } from "testcontainers/src/types" ;
7+
38const MONGODB_PORT = 27017 ;
49
510export class MongoDBContainer extends GenericContainer {
@@ -26,6 +31,29 @@ export class MongoDBContainer extends GenericContainer {
2631
2732 public override async start ( ) : Promise < StartedMongoDBContainer > {
2833 if ( this . username && this . password ) {
34+ const keyfileContainerPath = "/tmp/mongodb-keyfile" ;
35+ const initScriptContainerPath = "/docker-entrypoint-initdb.d/01-init-keyfile.sh" ;
36+
37+ const initKeyfileScript = `#!/bin/bash
38+ set -e
39+ openssl rand -base64 32 > "${ keyfileContainerPath } "
40+ chmod 600 "${ keyfileContainerPath } "` ;
41+
42+ const tempDir = await fs . mkdtemp ( path . join ( os . tmpdir ( ) , "mongo-init-" ) ) ;
43+ const initScriptHostPath = path . join ( tempDir , "01-init-keyfile.sh" ) ;
44+ await fs . writeFile ( initScriptHostPath , initKeyfileScript , { mode : 0o755 } ) ;
45+
46+ const filesToCopy : FileToCopy [ ] = [
47+ {
48+ source : initScriptHostPath ,
49+ target : initScriptContainerPath ,
50+ mode : 0o755 ,
51+ } ,
52+ ] ;
53+
54+ this . withCopyFilesToContainer ( filesToCopy ) ;
55+
56+ this . withCommand ( [ "--replSet" , "rs0" , "--keyFile" , keyfileContainerPath , "--bind_ip_all" ] ) ;
2957 this . withEnvironment ( { MONGO_INITDB_ROOT_USERNAME : this . username , MONGO_INITDB_ROOT_PASSWORD : this . password } ) ;
3058 }
3159
0 commit comments