mirror of
https://github.com/TheNetworkGuy/netbox-zabbix-sync.git
synced 2025-12-19 03:42:23 -06:00
Removed YAML config logic, added python config logic with default fallback. Added ENV variable support for config parameters.
This commit is contained in:
@@ -2,7 +2,9 @@
|
||||
Module for parsing configuration from the top level config.yaml file
|
||||
"""
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
from importlib import util
|
||||
from os import environ
|
||||
from logging import getLogger
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"templates_config_context": False,
|
||||
@@ -18,20 +20,43 @@ DEFAULT_CONFIG = {
|
||||
}
|
||||
|
||||
|
||||
def load_config(config_path="config.yaml"):
|
||||
"""Loads config from YAML file and combines it with default config"""
|
||||
# Get data from default config.
|
||||
config = DEFAULT_CONFIG.copy()
|
||||
# Set config path
|
||||
config_file = Path(config_path)
|
||||
# Check if file exists
|
||||
if config_file.exists():
|
||||
try:
|
||||
with open(config_file, "r", encoding="utf-8") as f:
|
||||
user_config = yaml.safe_load(f) or {}
|
||||
config.update(user_config)
|
||||
except OSError:
|
||||
# Probably some I/O error with user permissions etc.
|
||||
# Ignore for now and return default config
|
||||
pass
|
||||
return config
|
||||
def load_config():
|
||||
"""Returns combined config from all sources"""
|
||||
# Overwrite default config with config.py
|
||||
conf = load_config_file(config_default=DEFAULT_CONFIG)
|
||||
# Overwrite default config and config.py with environment variables
|
||||
for key in conf:
|
||||
value_setting = load_env_variable(key)
|
||||
if value_setting is not None:
|
||||
conf[key] = value_setting
|
||||
return conf
|
||||
|
||||
|
||||
def load_env_variable(config_environvar):
|
||||
"""Returns config from environment variable"""
|
||||
if config_environvar in environ:
|
||||
return environ[config_environvar]
|
||||
return None
|
||||
|
||||
|
||||
def load_config_file(config_default, config_file="config.py"):
|
||||
"""Returns config from config.py file"""
|
||||
# Check if config.py exists and load it
|
||||
# If it does not exist, return the default config
|
||||
config_path = Path(config_file)
|
||||
if config_path.exists():
|
||||
dconf = config_default.copy()
|
||||
# Dynamically import the config module
|
||||
spec = util.spec_from_file_location("config", config_path)
|
||||
config_module = util.module_from_spec(spec)
|
||||
spec.loader.exec_module(config_module)
|
||||
# Update DEFAULT_CONFIG with variables from the config module
|
||||
for key in dconf:
|
||||
if hasattr(config_module, key):
|
||||
dconf[key] = getattr(config_module, key)
|
||||
return dconf
|
||||
else:
|
||||
getLogger(__name__).warning(
|
||||
"Config file %s not found. Using default config "
|
||||
"and environment variables.", config_file)
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user