Initial Commit

master
ermisw 2023-03-31 12:39:47 +02:00
commit c17e8a6dd3
6 changed files with 368 additions and 0 deletions

138
.gitignore vendored Normal file
View File

@ -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

141
change_hostmonitoring.py Normal file
View File

@ -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()

30
environment.yaml Normal file
View File

@ -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/"

2
hosts.csv Normal file
View File

@ -0,0 +1,2 @@
HOST-1234,euprod
HOST-CDB0993E8D0EC4F1,euprod
1 HOST-1234 euprod
2 HOST-CDB0993E8D0EC4F1 euprod

53
readme.md Normal file
View File

@ -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:
<ENV NAME>=<ENV TOKEN>
<ENV NAME> 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

4
requirements.txt Normal file
View File

@ -0,0 +1,4 @@
python-decouple
pyyaml
requests
argparse