NAME
YAML::PP::Schema::Env - schema for serializing environment variables in YAML files
SYNOPSIS
use
YAML::PP;
my
$yp
= YAML::PP->new(
schema
=> [
qw/ + Env /
] );
$ENV
{MY_SECRET_PASSWORD} =
's3cr37!'
;
my
$password
=
$yp
->load_string(
'--- !ENV ${MY_SECRET_PASSWORD}'
);
$password
,
"\n"
;
# output is: s3cr37!
DESCRIPTION
This schema allows interpolation of environment variables when loading YAML files. For this, the tag !ENV
is used. Any following substring matching the ${ENVIRONMENT_VARIABLE}
pattern is replaced by the current environment variable value, or throws an exception if there's no such environment variable.
It's possible to specify a default value within ${...}
, by default separated with a colon. If there's a default value then an environment variable does not need to exist.
This module was influenced by https://pypi.org/project/pyaml-env/, but some things are differently handled here, most notably that missing environment variables cause exceptions by default.
CONFIGURATION
The following options are recognized when initializing the schema:
- defval
-
A global default value which is used if the environment variable does not exist and there's no local default value set. Examples:
YAML::PP->new(
schema
=> [
qw(+ Env defval=)
]);
# the empty string
YAML::PP->new(
schema
=> [
qw(+ Env defval=N/A)
]);
- defsep
-
Another separator than the default
:
. Examples:YAML::PP->new(
schema
=> [
qw(+ Env defsep=!)
]);
YAML::PP->new(
schema
=> [
qw(+ Env defsep=*)
]);
EXAMPLES
Here's a sample YAML file with various replacements:
---
# no replacement in the next line:
noenv: noenv
# replace the environment variable SIMPLE, or throw an exception if it's not defined:
simple: !ENV ${SIMPLE}
# replace two environment variables (ENV1 and ENV2), and may throw an exception:
concat: !ENV
before
${ENV1} middle ${ENV2}
after
# replace the environment variable DEFAULT_TEST, or use "this is the default value" if it does not exist:
with_default: !ENV ${DEFAULT_TEST:this is the
default
value}
If the YAML::PP parser was created with
YAML::PP->new(
schema
=> [
qw(+ Env defsep=! defval=N/A)
]);
then a YAML file
---
env_not_exist1: !ENV ${DOES_NOT_EXIST1}
env_not_exist2: !ENV ${DOES_NOT_EXIST2!
default
value}
would yield the same as the following (if both used environment variables do not exist):
---
env_not_exist1: N/A
env_not_exist2:
default
value
AUTHOR
Slaven Rezic <srezic@cpan.org>