Jack M. Jack M. - 5 months ago 17
Perl Question

Configure Dancer from environment variables?

I'm new to Dancer, but I'm trying to configure it to work within a Docker container. As a result, I need to pick up my database settings from the environment.

In my case, I have

DB_PORT_3306_TCP_ADDR
, and
DB_PORT_3306_TCP_PORT
coming from Docker. Unfortunately, the
Dancer::Plugin::Database
module is erroring before I can change the database to use those variables.

use Dancer ':syntax';
use Dancer::Plugin::Database;

if ($ENV{DB_PORT_3306_TCP}) {## Connected via docker.
database->({
driver => 'mysql',
username => 'username',
password => 'password',
host => $ENV{DB_PORT_3306_TCP_ADDR},
port => $ENV{DB_PORT_3306_TCP_PORT},
database => $ENV{DB_ENV_MYSQL_DATABASE},
});
}


So the question is, is there a good way to configure Dancer from environment variables, instead of through static YAML?

Answer

It turns out there is actually a configuration shortcut for accessing the environment. Within your config.yml, __ENV()__ will be replaced with matching environment variables. For example:

Model::PolMaker:
  connect_info:
    driver: mysql
    host: __ENV(DB_PORT_3306_TCP_ADDR)__
    port: __ENV(DB_PORT_3306_TCP_PORT)__
    database: __ENV(DB_DATABASE)__
    user: __ENV(DB_USERNAME)__
    password: __ENV(DB_PASSWORD)__