A library that offers a simple method of loading and accessing environmental variables and `.env` file values.
Project description
secretbox
A library that offers a simple method of loading and accessing environmental variables, .env
file values, and other sources of secrets. The class stores values to state when load methods are called.
Loaded values are also injected into the local environ. This is to assist with adjacent libraries that reference os.environ
values by default. Required values can be kept in a .env
file instead of managing a script to load them into the environment.
Pending v2 release (Oct 15, 2021):
Version 2 is on its way. This version will introduce API changes. The tradeoff of small code changes to adjust for these changes is a new level of flexibility for future secret sources.
If you've only used .get()
and created an instance of SecretBox with SecretBox(autoload=true)
then you should not notice a change!
Planned method changes includes:
- Remove -
load()
- Remove -
load_env_vars()
- Remove -
load_env_file()
- Remove -
load_aws_store()
Planned class fingerprint changes include:
- Remove - parameter
filename: str
- Remove - parameter
aws_sstore_name: Optional[str]
- Remove - parameter
aws_region_name: Optional[str]
- Add -
**kwargs: Any
Planned changes to loader behavior:
- AWS Users:
autoload=True
will no longer include AWS secret manager.- Fix: include the following call to load AWS secret manager
secrets = SecretBox(auto_load=True) secrets.load_from(["awssecrets"], aws_sstore_name="", aws_region_name="")
- Fix: include the following call to load AWS secret manager
Requirements
- Python >=3.6
Optional Dependencies
- boto3
- boto3-stubs[secretsmanager]
Install
$ pip install secretbox
Optional AWS Secret Manager support
$ pip install secretbox[aws]
Example use with auto_load
from secretbox import SecretBox
secrets = SecretBox(auto_load=True)
def main() -> int:
"""Main function"""
my_sevice_password = secrets.get("SERVICE_PW")
# More code
return 0
if __name__ == "__main__":
raise SystemExit(main())
Default Behavior:
- On initialization the
SecretBox()
class does nothing. By calling.load()
we cause the class to load all the currently available environ variables. It also looks for and loads, if found, a.env
file in the working directory. From there we can access those values with.get("KEY_NAME")
.
SecretBox arguments:
SecretBox(filename: str = ".env", aws_sstore_name: Optional[str] = None, aws_region: Optional[str] = None, auto_load: bool = False)
filename (depreciated pending v2 release)
- You can specify a
.env
formatted file and location, overriding the default behavior to load the.env
from the working directory
aws_sstore_name (depreciated pending v2 release)
- When provided, an attempt to load values from named AWS secrets manager will be made. Requires
aws_region
to be provided. Requiresboto3
andboto3-stubs[secretsmanager]
to be installed - Note: Can be provided with the
AWS_SSTORE_NAME
environment variable.
aws_region_name (depreciated pending v2 release)
- When provided, an attempt to load values from the given AWS secrets manager found in this region will be made. Requires
aws_sstore_name
to be provided. Requiresboto3
andboto3-stubs[secretsmanager]
to be installed - Note: Can be provided with the
AWS_REGION_NAME
environment variable.
auto_load
- v1 behavior (pending change): Loads environment variables, .env file, and AWS (if provided)
- v2 behavior: Loads environment variables and .env file
load_debug
- When true, internal logger level is set to DEBUG. Secret values are truncated, however do not leave this on for production deployments.
Load Order
Secret values are loaded, and over-written if pre-existing, in the following order:
- Local environment variables
.env
file- AWS secret store [optional]
SecretBox methods:
.get(key: str, default: str = "") -> str
- Returns the string value of the loaded value by key name. If the key does not exist, an empty string will be returned
""
or the provided optional default value. - Note: This method pulls from the instance's state and does not reflect changes to the environment before/after loading.
.load_from(loaders: list[str], **kwargs: Any) -> None
- Runs load_values from each of the listed loadered in the order they appear
- Loader options:
- environ
- Loads the current environmental variables into secretbox.
- envfile
- Loads .env file. Optional
filename
kwarg can override the default load of the current working directory.env
file.
- Loads .env file. Optional
- awssecret
- Loads secrets from an AWS secret manager. Requires
aws_sstore_name
andaws_region_name
keywords to be provided or for those values to be in the environment variables underAWS_SSTORE_NAME
andAWS_REGION_NAME
.aws_sstore
is the name of the store, not the arn.
- Loads secrets from an AWS secret manager. Requires
- environ
.load() (depreciated pending v2 release)
- Runs all importer methods. If optional dependencies are not installed, e.g. boto3, the importer is skipped.
.load_env_vars() (depreciated pending v2 release)
- Loads all existing
os.environ
values into state.
.load_env_file() (depreciated pending v2 release)
- Loads
.env
file or any file provided with thefilename
argument on initialization.
.load_aws_store() (depreciated pending v2 release)
- Loads secrets from AWS secret manager. Requires
aws_sstore_name
andaws_region
to have been provided. Will raiseNotImplementedError
if library requirements are missing.
.env
file format
Current format for the .env
file supports strings only and is parsed in the following order:
- Each seperate line is considered a new possible key/value set
- Each set is delimted by the first
=
found - Leading and trailing whitespace are removed
- Matched leading/trailing single quotes or double quotes will be stripped from values (not keys).
I'm open to suggestions on standards to follow here.
This .env
example:
# Comments are ignored
KEY=value
Invalid lines without the equal sign delimiter will also be ignored
Will be parsed as:
{"KEY": "value"}
This .env
example:
PASSWORD = correct horse battery staple
USER_NAME="not_admin"
MESSAGE = ' Totally not an "admin" account logging in'
Will be parsed as:
{
"PASSWORD": "correct horse battery staple",
"USER_NAME": "not_admin",
"MESSAGE": ' Toally not an "admin" account logging in',
}
Local developer installation
It is highly recommended to use a venv
for installation. Leveraging a venv
will ensure the installed dependency files will not impact other python projects.
Clone this repo and enter root directory of repo:
$ git clone https://github.com/Preocts/secretbox
$ cd secretbox
Create and activate venv
:
# Linux/MacOS
python3 -m venv venv
. venv/bin/activate
# Windows
python -m venv venv
venv\Scripts\activate.bat
# or
py -m venv venv
venv\Scripts\activate.bat
Your command prompt should now have a (venv)
prefix on it.
Install editable library and development requirements:
# Linux/MacOS
pip install -r requirements-dev.txt
pip install --editable .[aws,tests]
# Windows
python -m pip install -r requirements-dev.txt
python -m pip install --editable .[aws,test]
# or
py -m pip install -r requirements-dev.txt
py -m pip install --editable .[aws,test]
Install pre-commit hooks to local repo:
pre-commit install
pre-commit autoupdate
Run tests
tox
To exit the venv
:
deactivate
Makefile
This repo has a Makefile with some quality of life scripts if your system supports make
.
install
: Clean all artifacts, update pip, install requirements with no updatesupdate
: Clean all artifacts, update pip, update requirements, install everythingclean-pyc
: Deletes python/mypy artifactsclean-tests
: Deletes tox, coverage, and pytest artifactsbuild-dist
: Build source distribution and wheel distribution
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file secretbox-1.6.1.tar.gz
.
File metadata
- Download URL: secretbox-1.6.1.tar.gz
- Upload date:
- Size: 11.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3007c0e4e8d08667f3f8cef9ec98cb53bd23b72ed98149855bd5c1169b56bb42 |
|
MD5 | a58d6a2795798a5a17b4398cf8ec67c5 |
|
BLAKE2b-256 | 6ccaf083723e0d355e0a8122be50216a5428fda05c6e1698e882933f9a3bd146 |
File details
Details for the file secretbox-1.6.1-py3-none-any.whl
.
File metadata
- Download URL: secretbox-1.6.1-py3-none-any.whl
- Upload date:
- Size: 10.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b68b4ba004fa680671e5d6288b6c9d3dd18b9ae282e954b49e10edd9a088d5e5 |
|
MD5 | 5bcd0e3441e1695469453dac1223f879 |
|
BLAKE2b-256 | 69ac6c7ff360ff1b295989d6bb88f4c848843f36e1a2e02f317001d10d0c84a8 |