From c17e8a6dd30890fc371dc90bc2006def46882317 Mon Sep 17 00:00:00 2001 From: ermisw Date: Fri, 31 Mar 2023 12:39:47 +0200 Subject: [PATCH] Initial Commit --- .gitignore | 138 ++++++++++++++++++++++++++++++++++++++ change_hostmonitoring.py | 141 +++++++++++++++++++++++++++++++++++++++ environment.yaml | 30 +++++++++ hosts.csv | 2 + readme.md | 53 +++++++++++++++ requirements.txt | 4 ++ 6 files changed, 368 insertions(+) create mode 100644 .gitignore create mode 100644 change_hostmonitoring.py create mode 100644 environment.yaml create mode 100644 hosts.csv create mode 100644 readme.md create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0738441 --- /dev/null +++ b/.gitignore @@ -0,0 +1,138 @@ +.vscode +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +### Terraform stuff +**/.terraform/* +crash.log +*.tfvars + +#excel reports +*.xlsx \ No newline at end of file diff --git a/change_hostmonitoring.py b/change_hostmonitoring.py new file mode 100644 index 0000000..3719fb3 --- /dev/null +++ b/change_hostmonitoring.py @@ -0,0 +1,141 @@ +import argparse +import csv +import requests +import yaml +from decouple import config +import sys +import json + +def put_request(url, headers,body): + #try: + response = requests.put(url, body, headers=headers,verify=False) + response.raise_for_status() + # except requests.exceptions.HTTPError as errh: + # return "An Http Error occurred:" + repr(errh) + # except requests.exceptions.ConnectionError as errc: + # return "An Error Connecting to the API occurred:" + repr(errc) + # except requests.exceptions.Timeout as errt: + # return "A Timeout Error occurred:" + repr(errt) + # except requests.exceptions.RequestException as err: + # return "An Unknown Error occurred" + repr(err) + + return response + +def get_request(url, headers): + #try: + response = requests.get(url, headers=headers) + response.raise_for_status() + # except requests.exceptions.HTTPError as errh: + # return "An Http Error occurred:" + repr(errh) + # except requests.exceptions.ConnectionError as errc: + # return "An Error Connecting to the API occurred:" + repr(errc) + # except requests.exceptions.Timeout as errt: + # return "A Timeout Error occurred:" + repr(errt) + # except requests.exceptions.RequestException as err: + # return "An Unknown Error occurred" + repr(err) + + return response + +def init_parser(): + parser = argparse.ArgumentParser(description='Activate or deactivate host monitoring by host list') + parser.add_argument('-i', '--inputfile', required=True, help='path to the host list as csv') + parser.add_argument('-a', '--activate', action='store_true', help='activate host monitoring') + parser.add_argument('-d', '--deactivate', action='store_true', help='deactivate host monitoring') + return parser + +def getObject(DTURL,DTTOKEN,hostid): + try: + #get objectid + headers = { + 'Content-Type': 'application/json', + 'Authorization': 'Api-Token ' + DTTOKEN + } + + apiurl=DTURL+"/api/v2/settings/objects?fields=objectId%2Cvalue&scopes="+hostid + object_result=get_request(apiurl,headers).json() + + if len(object_result["items"])==0: + print(hostid+" object could not be modified by script!") + return + + return object_result['items'][0] + + except Exception as err: + print(hostid +"failed during following Exception! "+repr(err)) + +def activate(DTURL,DTTOKEN,objectH, hostid): + try: + #get objectid + headers = { + 'Content-Type': 'application/json', + 'Authorization': 'Api-Token ' + DTTOKEN + } + + apiurl=DTURL+"/api/v2/settings/objects/"+objectH["objectId"] + + objectH["value"]["enabled"]=True + body={"value": objectH["value"]} + + object_result=put_request(apiurl,headers,json.dumps(body)).json() + + except Exception as err: + print(hostid+" failed during following Exception! "+repr(err)) + +def deactivate(DTURL,DTTOKEN,objectH, hostid): + try: + #get objectid + headers = { + 'Content-Type': 'application/json', + 'Authorization': 'Api-Token ' + DTTOKEN + } + + apiurl=DTURL+"/api/v2/settings/objects/"+objectH["objectId"] + + objectH["value"]["enabled"]=False + body={"value": objectH["value"]} + + object_result=put_request(apiurl,headers,json.dumps(body)).json() + + except Exception as err: + print(hostid+" failed during following Exception! "+repr(err)) + + + +def main(): + parser = init_parser() + args = parser.parse_args() + + if args.activate and args.deactivate: + print("You can only activate or deactivate host monitoring, not both at the same time.") + exit() + + if not args.activate and not args.deactivate: + print("You need to specify whether to activate or deactivate host monitoring.") + exit() + + hosts = [] + with open(args.inputfile, newline='') as csvfile: + reader = csv.DictReader(csvfile,["HOSTID", "ENV"]) + for row in reader: + hosts.append(row) + + with open('./environment.yaml') as file: + env_doc = yaml.safe_load(file) + + for row in hosts: + dturl=env_doc[row["ENV"]][1]["env-url"] + token = config(env_doc[row["ENV"]][2]["env-token-name"]) + objectH=getObject(dturl,token,row["HOSTID"]) + + if objectH: + if args.activate: + activate(dturl,token,objectH,row["HOSTID"]) + print(row["HOSTID"] +" monitoring successfully enabled!") + + elif args.deactivate: + deactivate(dturl,token,objectH,row["HOSTID"]) + print(row["HOSTID"] +" monitoring successfully disabled!") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/environment.yaml b/environment.yaml new file mode 100644 index 0000000..fe30d26 --- /dev/null +++ b/environment.yaml @@ -0,0 +1,30 @@ +euprod: + - name: "euprod" + - env-url: "https://xxu26128.live.dynatrace.com" + - env-token-name: "EUPROD_TOKEN_VAR" + - jenkins: "https://jaws.bmwgroup.net/opapm/" +eupreprod: + - name: "eupreprod" + - env-url: "https://qqk70169.live.dynatrace.com" + - env-token-name: "EUPREPROD_TOKEN_VAR" + - jenkins: "https://jaws.bmwgroup.net/opapm/" +napreprod: + - name: "napreprod" + - env-url: "https://onb44935.live.dynatrace.com" + - env-token-name: "NAPREPROD_TOKEN_VAR" + - jenkins: "https://jaws.bmwgroup.net/opapm/" +naprod: + - name: "naprod" + - env-url: "https://wgv50241.live.dynatrace.com" + - env-token-name: "NAPROD_TOKEN_VAR" + - jenkins: "https://jaws.bmwgroup.net/opapm/" +cnprod: + - name: "cnprod" + - env-url: "https://dyna-synth-cn.bmwgroup.com.cn/e/b921f1b9-c00e-4031-b9d1-f5a0d530757b" + - env-token-name: "CNPROD_TOKEN_VAR" + - jenkins: "https://jaws-china.bmwgroup.net/opmaas/" +cnpreprod: + - name: "cnpreprod" + - env-url: "https://dynatracemgd-tsp.bmwgroup.net/e/ab88c03b-b7fc-45f0-9115-9e9ecc0ced35" + - env-token-name: "CNPREPROD_TOKEN_VAR" + - jenkins: "https://jaws-china.bmwgroup.net/opmaas/" \ No newline at end of file diff --git a/hosts.csv b/hosts.csv new file mode 100644 index 0000000..656b10b --- /dev/null +++ b/hosts.csv @@ -0,0 +1,2 @@ +HOST-1234,euprod +HOST-CDB0993E8D0EC4F1,euprod \ No newline at end of file diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..d48872e --- /dev/null +++ b/readme.md @@ -0,0 +1,53 @@ +# HOST MONITOR ACTIVATE/DEACTIVATE +This repository holds the code to activate or deactive host monitoring by using a list of host (csv) + + +# Prerequisites + +## Python packages +Before executing scripts, python requirements have to be satisfied. To do so, execute following command: + pip install -r requirements.txt + +## .env file + +To provide authentication for API calls, create ".env" file in the script directory with following definition: + + = + is name of environment variable. This name should be passed to "environment.yaml" file as "env-token-name" parameter + Example: + environment.yaml file: "- env-token-name: "GLOBAL_CONFIG_TOKEN" + .env file: "GLOBAL_CONFIG_TOKEN=XXXXXXXXXXX" + +# Usage for activating + + python change_hostmonitoring.py -i hosts.csv --activate + +# Usage for deactivating + + python change_hostmonitoring.py -i hosts.csv --deactivate + +# format of the host csv list + +HOSTID, ENVIRONMENT + +example: +HOST-1234,euprod +HOST-CDB0993E8D0EC4F1,euprod + + +# additional files +## createKeyRequestReport.py + +This scripts generates the report. + +## environment.yaml +File containing environments to execute --auto-upload + + Environment name: + name: string #name ov environment + env-url: str #url of environment + env-token-name: str #name of environment variable containing API token + +## requirements.txt + +File containing required python packages \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c51b19e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +python-decouple +pyyaml +requests +argparse \ No newline at end of file