Package: envex
ENV EXtendedenvexis a dotenv.envaware environment variable handler with typing features and Hashicorp vault support.OverviewThis module provides a convenient interface for handling the environment, and therefore configuration of any application
using 12factor.net principals removing many environment-specific variables and security sensitive information from
application code.AnEnvinstance delivers a lot of functionality by providing a type-smart front-end toos.environ,
providing a superset ofos.environfunctionality, including setting default values.From version 2.0, this module also supports transparently fetching values from Hashicorp vault,
which reduces the need to store secrets in plain text on the filesystem.
This functionality is optional, activated automatically when thehvacmodule is installed, and connection and
authentication to Vault succeed.
Only get (no set) operations to Vault are supported.
Values fetched from Vault are cached by default to reduce the overhead of the api call.
If this is of concern to security, caching can be disabled using theenable_cache=Falseparameter to Env.This module provides some features not supported by other dotenv handlers (python-dotenv, etc.) including recursive
expansion of template variables, which can be very useful for DRY.fromenveximportenvassertenv['HOME']=='/Users/username'env['TESTING']='This is a test'assertenv.get('TESTING')=='This is a test'assertenv['TESTING']=='This is a test'assertenv('TESTING')=='This is a test'importosassertos.environ['TESTING']=='This is a test'assertenv.get('UNSET_VAR')isNoneenv.set('UNSET_VAR','this is now set')assertenv.get('UNSET_VAR')isnotNoneenv.setdefault('UNSET_VAR','and this is a default value but only if not set')assertenv.get('UNSET_VAR')=='this is now set'delenv['UNSET_VAR']assertenv.get('UNSET_VAR')isNoneNote that there is a subtle difference betweenenv.get(<variable>, default=<default value>)andenv(<variable>, default=<default value>).
If the variable is unset, the former simply returns the default value,
but the latter also sets the value to the default value in the environment.An Env instance can also read a.env(default name) file and update the application environment accordingly.
It can read this either when created withEnv(readenv=True)or directly by using the methodread_env().
To override the base name of the dot env file, use theDOTENVenvironment variable.
Other kwargs that can be passed toEnvwhen created:environ (env): pass the environment to update, default is os.environ, passing an empty dict will create a new envreadenv (bool): search for and read .env filesenv_file (str): name of the env file,os.environ["DOTENV"]if set, or.envby defaultsearch_path (str or list): a single path or list of paths to search for the env file
search_path may also be passed as a colon-separated list (or semicolon on Windows) of directories to search.parents (bool): search (or not) parents of dirs in the search_pathoverwrite (bool): overwrite already set values read from .env, default is to only set if not currently setupdate (bool): push updates os.environ if true (default) otherwise pool changes internally onlyworking_dirs (bool): add CWD for the current process and PWD of source .env fileexception: (optional) Exception class to raise on error (default isKeyError)errors: bool whether to raise error on missing env_file (default is False)kwargs: (keyword args, optional) additional environment variables to add/overrideIn addition, Env supports a few HashiCorp Vault configuration parameters:url: (str, optional) vault url, default is$VAULT_ADDRtoken: (str, optional) vault token, default is$VAULT_TOKENor content of~/.vault-tokencert: (tuple, optional) (cert, key) path to client certificate and key filesverify: (bool, optional) whether to verify server cert (default is True)base_path: (optional) str base path, or "environment" for secrets (default is None).
This is used to prefix the path to the secret, i.e.f"/secret/{base_path}/key".Some type-smart functions act as an alternative toEnv.getand having to parse the result:fromenveximportenvenv['AN_INTEGER_VALUE']=2875083assertenv.get('AN_INTEGER_VALUE')=='2875083'assertenv.int('AN_INTEGER_VALUE')==2875083assertenv('AN_INTEGER_VALUE',type=int)==2875083env['A_TRUE_VALUE']=Trueassertenv.get('A_TRUE_VALUE')=='True'assertenv.bool('A_TRUE_VALUE')isTrueassertenv('A_TRUE_VALUE',type=bool)isTrueenv['A_FALSE_VALUE']=0assertenv.get('A_FALSE_VALUE')=='0'assertenv.int('A_FALSE_VALUE')==0assertenv.bool('A_FALSE_VALUE')isFalseassertenv('A_FALSE_VALUE',type=bool)isFalseenv['A_FLOAT_VALUE']=287.5083assertenv.get('A_FLOAT_VALUE')=='287.5083'assertenv.float('A_FLOAT_VALUE')==287.5083assertenv('A_FLOAT_VALUE',type=float)==287.5083env['A_LIST_VALUE']='1,"two",3,"four"'assertenv.get('A_LIST_VALUE')=='1,"two",3,"four"'assertenv.list('A_LIST_VALUE')==['1','two','3','four']assertenv('A_LIST_VALUE',type=list)==['1','two','3','four']Environment variables are always stored as strings.
This is enforced by the underlying os.environ, but also true of any
provided environment, which must use theMutableMapping[str, str]contract.VaultIn addition to handling of the os environment and .env files, Env supports fetching secrets from Hashicorp Vault using
the kv.v2 engine.
This provides a secure secrets store, without exposing them in plain text on the filesystem and in particular in
published docker images.
It also prevents storing secrets in the operating system’s environment, which can be inspected by external processes.
Env can read secrets from the environment variables if you set Env(readenv=True).This document does not cover how to set up and configure a vault server, but you can find useful resources on the
following websites:hashicorp.comfor the developer documentation and detailed information and
tutorials on setting up and hosting your own vault server, andvaultproject.iofor information about HashiCorp's managed cloud offering.To access the vault server, you need a token with a role that has read permission for the path to the secrets.
A read only profile is the recommended policy for tokens used at runtime by the application.This library provides a utility calledenv2hvacthat can import (create or update) a typical .env file into vault. The
utility uses a prefix that consists of an application name and an environment name, using the
format // - for example, myapp/prod/DB_PASSWORD. The utility requires that the token has a role
with create permission for the base secrets path on the vault server.
The utility currently assumes that the kv secrets engine is mounted at secret/. The
final path where the secrets are stored will be secret/data///.Environment VariablesThe SecretsManager and Vault client leverage environment variables for their configuration.
This ensures a degree of transparency as it allows the client to use them but mitigates the need for the client code to be aware of their presence.
A summary of these variables is in the following table:VariableDescriptionVAULT_ADDRThe URL of the vault serverVAULT_TOKENThe vault token to use for authenticationVAULT_CACERTThe path to the CA certificate to use for TLS verificationVAULT_CAPATHThe path to a directory of CA certificates to use for TLS verificationVAULT_CLIENT_CERTThe path to the client certificate to use for TLS connectionVAULT_CLIENT_KEYThe path to the client key to use for TLS connection