move to env var for configuration

This commit is contained in:
Hauke Petersen
2020-01-22 11:14:08 +01:00
parent 009768c8d2
commit e2f8447f0e

View File

@@ -16,12 +16,12 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import yaml
import json
import logging
import argparse
from datetime import datetime
import urllib.request
from influxdb import InfluxDBClient
from apscheduler.schedulers.blocking import BlockingScheduler
@@ -30,18 +30,52 @@ from apscheduler.schedulers.blocking import BlockingScheduler
CONFIGFILE = "/opt/steckie/config.yml"
CMD_SENSOR = "cm?cmnd=Status%208"
CFG_DEFAULTS = {
"STECKIE_ITVL": 5,
"INFLUXDB_PORT": 8086,
}
CFG_NEEDED = {
"INFLUXDB_HOST": "hostname",
"INFLUXDB_DB": "database_name",
"INFLUXDB_USER": "username",
"INFLUXDB_USER_PASSWORD": "SuperSecure",
}
CFG_VAR = {
"name": r'STECKIE_DEV_\d+_NAME',
"url": r'STECKIE_DEV_\d+_URL',
}
class Steckie:
def __init__(self, cfgfile):
def __init__(self, env_file):
self.cfg = dict()
env = os.environ
print("Env file: {}".format(env_file))
# read configuration
try:
with open(cfgfile, 'r', encoding="utf-8") as f:
self.cfg.update(yaml.load(f, Loader=yaml.BaseLoader))
except:
logging.error("unable to read config file '{}'".format(cfgfile))
sys.exit(1)
if env_file:
env = self.read_env(env_file)
for val in CFG_DEFAULTS:
self.cfg[val] = env[val] if val in env else CFG_DEFAULTS[val]
for val in CFG_NEEDED:
if val in env:
self.cfg[val] = env[val]
else:
logging.error("unable to read {} fron env".format(val))
sys.exit(1)
if cfgfile:
try:
with open(cfgfile, 'r', encoding="utf-8") as f:
self.cfg.update(yaml.load(f, Loader=yaml.BaseLoader))
except:
logging.error("unable to read config file '{}'".format(cfgfile))
sys.exit(1)
self.scheduler = BlockingScheduler()
self.db = InfluxDBClient(host=self.cfg['db']['host'],
@@ -94,12 +128,12 @@ class Steckie:
def main(args):
logging.basicConfig(format='%(asctime)s %(message)s',
level=logging.WARNING)
steckie = Steckie(args.cfgfile)
steckie = Steckie(args.env_file)
steckie.run()
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("cfgfile", default=CONFIGFILE, nargs='?', help="output dump")
p.add_argument("env_file", default=None, nargs="?", help="output dump")
args = p.parse_args()
main(args)