loopback-boot icon indicating copy to clipboard operation
loopback-boot copied to clipboard

Configure datasources via env variables

Open bajtos opened this issue 12 years ago • 28 comments

The Twelve-Factor App recommends to store configuration in environment variables - see the section III. Config.

loopback-boot can already read host and port from environment variables. We should extend this mechanism to cover datasource configuration too.

Proposed naming convention:

DATASOURCE_{ds-name}_{option-name}=VALUE

Example:

DATASOURCE_db_host=staging.mysql.com
DATASOURCE_db_user=webapp

DATASOURCE_email_type=SMTP
DATASOURCE_email_host=smtp.gmail.com

bajtos avatar May 29 '14 06:05 bajtos

Hi @dopeddude, sorry for taking long to respond, we have an important deadline ahead us. I will be slow to respond for another two weeks or so.

  1. May be I could not understand your comment well, But I can not imagine why

one will either have to maintain two config files or else force all developers to set env variables, which may not work well when developing multiple apps on the same machine.

Let me try with a sample configuration.

So I was thinking about the following configuration instead, which keeps everything in a single file:

// server/datasources.json
{
    "db": {
        "name": "db",
        "connector": "memory"
    },
    "myDb": {
        // used in production only
        "url": "${POSTGRESQL_URL}",
        // when the url is not set, fall back to development config
        "host": "localhost",
        "database": "some-db-name",
        "password": "some-secret-key",
        "name": "myDb",
        "connector": "postgresql",
        "user": "some-user"
    }
}

Of course, that's only one of possible approaches, and it may make sense to support different conventions too.

Then we need to check connector implementation and verify that that url always overrides individual config options.

This should be an existing problem, if it is not implemented so.

Yes, this is not strictly necessary for the changes proposed in your patch here. It's just that my example described above would not work without it, therefore the changes will have limited use in my opinion.

  1. I also doubt the likelihood that somebody would actually want to use a string like ${FOO} in the configuration But let's say if some use case requires this exact string, then I assume the user should not be setting this FOO variable on the environment. And in that case the string will be left intact and no substitution. Good for him and his use case.

Relying on the environment to not contain FOO variable is very fragile. How is the developer supposed to know what are the all env variables defined on a production box, to ensure they don't accidentally use the same name?

I still think we should substitute unknown variables with empty strings.

Regardless of that, I think we will eventually need to come up with a way how to encode the value so that loopback-boot knows it should not substitute the value. For example $={$FOO}. However, let's defer that for later, when there is actually somebody asking for that feature.

To add another concern, We should also be aware of the fact that there is another dynamic-configuration-params substituion in case of (Code Ref). In that case the placeholders patterns being similar can cause confusion. Like, if the user specifies a pattern like ${FOO}, We do not know if he wants it replace it with the ENV-VARS or he want to replace it with the APP-Config defined as part of the config.json to say.

I was thinking about this. In near future, I'd like to add support for VCAP_APPLICATION that is used by CloudFoundry to provide arbitrary configuration. That will add yet another source of values available for substitution.

I am proposing the following solution: When resolving a variable reference, let's say ${ENV_PROD_PG_URL}, we will check environment variables first, and if there is no variable with such name defined, the we will check app.get() variables from server/config.json. If there the variable is not found in app config either, then we will use undefined for the substituted value.

Thoughts? /cc @rmg @sam-github

bajtos avatar Mar 02 '16 15:03 bajtos

@bajtos Thanks for the response.

As per you:

When resolving a variable reference, let's say ${ENV_PROD_PG_URL}, we will check environment variables first, and if there is no variable with such name defined, the we will check app.get() variables from server/config.json. If there the variable is not found in app config either, then we will use undefined for the substituted value.

This approach looks good to me. But, let's just keep our list of minor limitations ready with this approach just for our future revisit purpose:

  • Currently user does not have support for using a value pattern like ${FOO}. And I agree as you said

"However, let's defer that for later, when there is actually somebody asking for that feature."

  • As the ENV-VARS are essentially just strings, so the substitution for port like variables will also result in string. Which is also a potential candidate for getting deferred.

Let's keep adding more limitations to this list.

And others can also please express their thoughts on this approach, whenever possible.

Regards.

ashwinik001 avatar Mar 09 '16 09:03 ashwinik001

Information placeholder for implementation:

Current implementation of middleware dynamic variable

https://github.com/strongloop/loopback-boot/blob/90b9211fff1d51d820dc18c79e725ddc3b0f4654/lib/executor.js#L338-L388

server/middleware.json
  "routes": {
    "loopback#rest": {
      "paths": ["${restApiRoot}"]
    }
server/config.json
{
  "restApiRoot": "/api"
}
Current implementation of host and port reading from dynamic sources

https://github.com/strongloop/loopback-boot/blob/90b9211fff1d51d820dc18c79e725ddc3b0f4654/lib/executor.js#L102-L142

  • should keep the precedence same as these
Unknown things that could be concerns (unknown by me only)
  • will ARC overwrite these variables?
  • does anywhere bypass boot and read these config files? loopback:refresh?

davidcheung avatar Mar 21 '16 20:03 davidcheung

I'm having trouble following the current state of this. Also, and perhaps this is NOT something to address with this issue, various service providers specify information on the configured DBs with provider-specific env vars. BlueMix instant runtimes use VCAP_... env vars, for example.

This should be supported either out of the box (possibly via some config mechanism), or via require of a supported module.

By some config mechanism, I mean like:

{
   name: "mysql",
   password: "$(VCAP_PROVIDER["mysql"].password)
  ...

^--- above is totally fake, I don't recall of the top of my head what the VCAP syntax is, but its possible that a survey of bluemix/heroku/openshift/etc. will find that there is some kindof core loopback json config file syntax we could implement that would allow env vars to be referenced and partially unparsed in order to have a generic way to configure an app to run in any (reasonable) cloud environment.

If not, then there will need to be an alternate way to get the ability for LB apps to be runnable easily in BlueMix/Heroku/etc., environments where the configuration is available in the environment, but the LB app developer does not control the env var naming or syntax.

@bajtos should I open another issue for this, or will this issue a good place to discuss that feature?

I also would like to echo @bajtos point about defaults, I would very much want this PR to ensure that the config can have defaults, and env overrides the defaults, so the defaults can be setup for dev envs. And using "named envs" like NODE_ENV=staging is an anti-pattern, IMO.

sam-github avatar Mar 30 '16 16:03 sam-github

@sam-github let's keep this issue focused on environment variables (the 12factor way) and open a new issue for VCAP and other mechanisms.

This is the current status: @jannyHou is improving the connectors to support url or dsn setting that allows users to pass all configuration in a single string, see https://github.com/strongloop/loopback/issues/2089. @davidcheung is looking into loopback-boot and how to implement env-variable injection as described above (see https://github.com/strongloop/loopback-boot/issues/177).

bajtos avatar Mar 31 '16 13:03 bajtos

@davidcheung please consolidate the information from the comments above and the demo meeting, so that it's clear what's done and what still needs to be done.

bajtos avatar Apr 19 '16 15:04 bajtos

Results that came out of this issue:

  • datasources.json now handles dynamic variables ${SOME_STRING}
  • middleware.json and component-config now will resolve dynamic variables from env-vars too
  • upon unresolved dynamic variables, undefined is returned ( this is so it can fallback to other settings )

Improvements to have on current implementation

  • prefixable/suffix

Things still need to be addressed:

  • Supporting cloud platforms out of the box with no need to go into settings and configure abunch of settings, for the use case of where DB services comes in a nested object rather than strings ( something that is extensible that brings more flexibility to dynamic configurations )
  • Goal of having out-of-the-box working with the cloud solution.

davidcheung avatar Apr 22 '16 19:04 davidcheung

I wanted to use this nice feature, but unfortunately there is no way I can see to interpret an environment variable as another type, eg boolean. For example, the Mongodb connector seems to interpret the SSL param as false if you pass it a string.

Ended up using a datasources.local.js file as below. If we used a URL connection string this feature would have worked, but then I'd have to change and re-deploy all our other (non-Loopback) microservices.

module.exports = { 
  mongo: { 
    name: 'mongo', 
    connector: 'mongodb', 
    host: process.env.MONGO_HOST || 'localhost', 
    port: process.env.MONGO_PORT || 27017, 
    user: process.env.MONGO_USER || '', 
    password: process.env.MONGO_PASSWORD || '', 
    database: process.env.MONGO_NAME || 'mydb', 
    ssl: (String(process.env.MONGO_SSL).toLowerCase() === 'true'), // default to false
    allowExtendedOperators: true
  }
}

drewwiens avatar May 21 '18 20:05 drewwiens