MongoDB admite utilizar directivas de expansión en archivos de configuración para cargar valores obtenidos externamente. Las directivas de expansión pueden cargar valores para opciones específicas del archivo de configuración o cargar el archivo de configuración completo. Las directivas de expansión ayudan a ocultar información confidencial, como certificados de seguridad y contraseñas.
storage: dbPath: "/var/lib/mongo" systemLog: destination: file path: "/var/log/mongodb/mongod.log" net: bindIp: __exec: "python /home/user/getIPAddresses.py" type: "string" trim: "whitespace" digest: 85fed8997aac3f558e779625f2e51b4d142dff11184308dc6aca06cff26ee9ad digest_key: 68656c6c30303030307365637265746d796f6c64667269656e64 tls: mode: requireTLS certificateKeyFile: "/etc/tls/mongod.pem" certificateKeyFilePassword: __rest: "https://myrestserver.example.net/api/config/myCertKeyFilePassword" type: "string" digest: b08519162ba332985ac18204851949611ef73835ec99067b85723e10113f5c26 digest_key: 6d795365637265744b65795374756666
Para usar las directivas de expansión, debes especificar la opción de línea de comandos --configExpand con la lista completa de directivas de expansión utilizadas:
mongod --config "/path/to/config/mongod.conf" --configExpand "rest,exec"
If you omit the --configExpand option or if you do not specify the complete list of expansion directives used in the configuration file, the mongod returns an error and terminates. You can only specify the --configExpand option on the command line.
Utiliza la directiva de expansión __rest
The __rest expansion directive loads configuration file values from a REST endpoint. __rest supports loading specific values in the configuration file or loading the entire configuration file.
The following configuration file uses the __rest expansion directive to load the setting net.tls.certificateKeyFilePassword value from an external REST endpoint:
storage: dbPath: "/var/lib/mongo" systemLog: destination: file path: "/var/log/mongodb/mongod.log" net: bindIp: 192.51.100.24,127.0.0.1 tls: mode: requireTLS certificateKeyFile: "/etc/tls/mongod.pem" certificateKeyFilePassword: __rest: "https://myrestserver.example.net/api/config/myCertKeyFilePassword" type: "string"
- Permiso de archivo
If the configuration file includes the
__restexpansion, on Linux/macOS, the read access to the configuration file must be limited to the user running themongod/mongosprocess only.- Análisis de expansión
To parse the
__restblocks, start themongodwith the--configExpand "rest"option.The
mongodissues aGETrequest against specified URL. If successful, themongodreplaces the value ofcertificateKeyFilePasswordwith the returned value. If the URL fails to resolve or if theRESTendpoint returns an invalid value, themongodthrows an error and terminates.
The following configuration file uses the __rest expansion directive to load the configuration file from an external REST endpoint. The expansion directive and its options must be the only values specified in the configuration file.
__rest: "https://myrestserver.example.net/api/config/fullConfig" type: "yaml"
- Permiso de archivo
If the configuration file includes the
__restexpansion, on Linux/macOS, the read access to the configuration file must be limited to the user running themongod/mongosprocess only.- Análisis de expansión
To parse the
__restblocks, start themongodwith the--configExpand "rest"option.The
mongodissues aGETrequest against the specified URL. If successful, themongodparses the returned configurationyamlfile and uses it during startup. If the URL fails to resolve or return a properly formattedyamlfile, themongodthrows an error and terminates.
Importante
The value returned by the specified REST endpoint cannot include any additional expansion directives. The mongod does not perform additional processing on the returned data and will terminate with an error code if the returned data includes additional expansion directives.
Utiliza la directiva de expansión __exec
The __exec expansion directive loads configuration file values from a shell or terminal command. __exec supports loading specific values in the configuration file or loading the entire configuration file.
The following example configuration file uses the __exec expansion directive to to load the setting net.tls.certificateKeyFilePassword value from the output of a shell or terminal command:
storage: dbPath: "/var/lib/mongo" systemLog: destination: file path: "/var/log/mongodb/mongod.log" net: bindIp: 192.51.100.24,127.0.0.1 tls: mode: requireTLS certificateKeyFile: "/etc/tls/mongod.pem" certificateKeyFilePassword: __exec: "python /home/myUserName/getPEMPassword.py" type: "string"
- Permiso de archivo
If the configuration file includes the
__execexpansion, on Linux/macOS, the write access to the configuration file must be limited to the user running themongod/mongosprocess only.- Análisis de expansión
To parse the
__execblocks, start themongodwith the--configExpand "exec"option.The
mongodattempts to execute the specified operation. If the command executes successfully, themongodreplaces the value ofcertificateKeyFilePasswordwith the returned value. If the command fails or returns an invalid value for the configuration file setting, themongodthrows an error and terminates.
The following example configuration file uses the __exec expansion directive to load the configuration file from the output of a shell or terminal command. The __exec expansion directive and its options must be the only values specified in the configuration file.
__exec: "python /home/myUserName/getFullConfig.py" type: "yaml"
- Permiso de archivo
If the configuration file includes the
__execexpansion, on Linux/macOS, the write access to the configuration file must be limited to the user running themongod/mongosprocess only.- Análisis de expansión
To parse the
__execblocks, start themongodwith the--configExpand "rest"option.If the command executes successfully, the
mongodparses the returned configurationyamlfile and uses it during startup. If the command fails or returns an invalidyamlfile, themongodthrows an error and terminates.
Importante
The data returned by executing the specified __exec string cannot include any additional expansion directives. The mongod does not perform additional processing on the returned data and will terminate with an error code if the returned data includes additional expansion directives.
Referencia de las directrices de expansión
__restThe
__restexpansion directive loads configuration file values from aRESTendpoint.__restsupports loading specific values in the configuration file or loading the entire configuration file. Themongodthen starts using the externally sourced values as part of its configuration.The
__restexpansion directive has the following syntax:Para especificar un endpoint de
RESTpara un ajuste o ajustes de archivo de configuración:<some configuration file setting>: __rest: "<string>" type: "string" trim: "none|whitespace" digest: "<string>" digest_key: "<string>" Para especificar un endpoint
RESTpara todo el archivo de configuración:__rest: "<string>" type: "yaml" trim: "none|whitespace" Si especificas el archivo de configuración completo vía el endpoint
REST, la directiva de expansión y sus opciones deben ser los únicos valores especificados en el archivo de configuración.
__restrequiere los siguientes campos:CampoTipoDescripciónstring
Required The URL against which the
mongodissues aGETrequest to retrieve the externally sourced value.Para los puntos finales que no son localhost (por ejemplo, un
RESTRESTpunto final alojado en un servidor remoto),__restrequierehttps://URL cifradas () donde tanto la máquina host como el servidor remoto admiten 1 TLS.1 o posterior.Si el
RESTpunto final especificado en la URL requiere autenticación, codifique las credenciales en la URL con el formato estándar de 3986 información de usuario RFC.For localhost
RESTendpoints (e.g. aRESTendpoint listening on the host machine),__restallows unencrypted (http://) URLs.IMPORTANT: The value returned by the specified
RESTendpoint cannot include any additional expansion directives. Themongoddoes not perform additional processing on the returned data and will terminate with an error code if the returned data includes additional expansion directives.typestring
Optional Controls how
__restparses the returned value from the specified URL.Los valores posibles son:
trimstring
Optional Specify
whitespaceto direct__restto trim any leading or trailing whitespace, specifically occurrences of" ","\r","\n","\t","\v", and"\f". Defaults tonone, or no trimming.string
opcional. La salida HMAC-SHA256 del resultado de la expansión, calculada como
HMAC-SHA256(digest_key, message), dondemessagees el valor de la configuración que se va a recuperar.If specified, you must also specify the digest_key.
string
Opcional. La 64representación en cadena hexadecimal de caracteres de la 32clave de byte utilizada para calcular el256 resumen HMAC-SHA del resultado de la expansión.
If specified, you must also specify the digest.
Por ejemplo, supongamos que el
certificateKeyFilePasswordes "superSecret123". Para recuperar esta contraseña mediante una solicitud REST o una llamada al servicio exec, debe generar una clave de resumen y usarla para calcular el resumen de su contraseña.Ejecute el siguiente código en su terminal para generar una clave de resumen de 32bytes:
openssl rand -hex 32 Después de generar una clave de resumen, puede usarla para calcular el resumen de su contraseña:
echo -ne "superSecret123" | openssl dgst -sha256 -mac hmac -macopt hexkey:f38d0d5adfcf1a0575f9fa9051c70a2f88b1bb7562513c9efd7686e9c21ad304 Nota
Para habilitar el análisis de la directiva de expansión
__rest, inicie elmongodcon la opción--configExpand "rest".
For examples, see Use the
__restExpansion Directive.
__execThe
__execexpansion directive loads configuration file values from the output of a shell or terminal command.__execsupports loading specific values in the configuration file or loading the entire configuration file. Themongodthen starts using the externally sourced values as part of its configuration.The
__execexpansion directive has the following syntax:Para especificar un comando shell o de terminal para una configuración específica o configuraciones en un archivo de configuración:
<some configuration file setting>: __exec: "<string>" type: "string" trim: "none|whitespace" Para especificar un shell o comando de terminal para todo el archivo de configuración:
__exec: "<string>" type: "yaml" trim: "none|whitespace" Si se especifica todo el archivo de configuración a través de un comando de terminal o shell, la directiva de expansión y sus opciones deben ser los únicos valores especificados en el archivo de configuración.
__execrequiere los siguientes campos:CampoTipoDescripción__execstring
Required The string which the
mongodexecutes on the terminal or shell to retrieve the externally sourced value.En los hosts Linux y OSX, la ejecución se gestiona mediante POSIX
popen(). En los hosts de Windows, la ejecución se gestiona a través de la API de control de procesos.__execabre una pipe de solo lectura como el mismo usuario que iniciómongodomongos.IMPORTANT: The data returned by executing the specified command cannot include any additional expansion directives. The
mongoddoes not perform additional processing on the returned data and will terminate with an error code if the returned data includes additional expansion directives.typestring
Optional Controls how
__execparses the value returned by the executed command.Los valores posibles son:
trimstring
Optional Specify
whitespaceto direct__execto trim any leading or trailing whitespace, specifically occurrences of" ","\r","\n","\t","\v", and"\f". Defaults tonone, or no trimming.string
opcional. La salida HMAC-SHA256 del resultado de la expansión, calculada como
HMAC-SHA256(digest_key, message), dondemessagees el valor de la configuración que se va a recuperar.If specified, you must also specify the digest_key
string
Optional. The 64-character hexadecimal string representation of the 32-byte key used to calculate the HMAC-SHA256 digest of the expansion result.
If specified, you must also specify the digest
Por ejemplo, supongamos que el
certificateKeyFilePasswordes "superSecret123". Para recuperar esta contraseña mediante una solicitud REST o una llamada al servicio exec, debe generar una clave de resumen y usarla para calcular el resumen de su contraseña.Ejecute el siguiente código en su terminal para generar una clave de resumen de 32bytes:
openssl rand -hex 32 Después de generar una clave de resumen, puede usarla para calcular el resumen de su contraseña:
echo -ne "superSecret123" | openssl dgst -sha256 -mac hmac -macopt hexkey:f38d0d5adfcf1a0575f9fa9051c70a2f88b1bb7562513c9efd7686e9c21ad304 Nota
To enable parsing of the
__execexpansion directives, start themongodwith the--configExpand "exec"option.
For examples, see Use the
__execExpansion Directive.
Genere el archivo de configuración con los valores resueltos de la directiva de expansión
You can test the final output of a configuration file that specifies one or more expansion directives by starting the mongod with the --outputConfig option. A mongod started with --outputConfig outputs the resolved YAML configuration document to stdout and halts. If any expansion directive specified in the configuration file returns additional expansion directives, the mongod throws an error and terminates.
Advertencia
La opción --outputConfig devuelve los valores resueltos para cualquier campo usando una directiva de expansión. Esto incluye cualquier información privada o sensible previamente ocultada mediante una fuente externa para la opción de configuración.
For example, the following configuration file mongod.conf contains a __rest expansion directive:
storage: dbPath: "/var/lib/mongo" systemLog: destination: file path: "/var/log/mongodb/mongod.log" net: port: __rest: "https://mongoconf.example.net:8080/record/1" type: string
La string grabada en la URL especificada es 20128
If the configuration file includes the __rest expansion, on Linux/macOS, the read access to the configuration file must be limited to the user running the mongod / mongos process only.
Inicia el mongod con las opciones --configExpand "rest" y --outputConfig:
mongod -f mongod.conf --configExpand rest --outputConfig
El mongod emite lo siguiente a stdout antes de finalizar:
config: mongod.conf storage: dbPath: "/var/lib/mongo" systemLog: destination: file path: "/var/log/mongodb/mongod.log" net: port: 20128 outputConfig: true