Преглед на файлове

feat: complete email alerting config and Taiga closure

lanfr144 преди 1 седмица
родител
ревизия
9fc389ea56
променени са 3 файла, в които са добавени 146 реда и са изтрити 0 реда
  1. 2 0
      .env
  2. 89 0
      configure_zabbix_email.py
  3. 55 0
      update_taiga_status.py

+ 2 - 0
.env

@@ -14,3 +14,5 @@ TAIGA_PROJECT_SLUG=your_project_slug
 DB_READER_PASS=reader_pass
 DB_LOADER_PASS=loader_pass
 DB_APP_AUTH_PASS=app_auth_placeholder_pass
+
+ADMIN_EMAIL=lanfr144@gmail.com

+ 89 - 0
configure_zabbix_email.py

@@ -0,0 +1,89 @@
+import requests
+import json
+import os
+
+ZABBIX_API_URL = "http://localhost:8081/api_jsonrpc.php"
+ZABBIX_USER = "Admin"
+ZABBIX_PASSWORD = "zabbix"
+
+def get_email_from_env():
+    if os.path.exists('.env'):
+        with open('.env', 'r') as f:
+            for line in f:
+                if line.startswith('ADMIN_EMAIL='):
+                    return line.strip().split('=', 1)[1]
+    return "lanfr144@gmail.com" # Default fallback
+
+def authenticate():
+    payload = {"jsonrpc": "2.0", "method": "user.login", "params": {"user": ZABBIX_USER, "password": ZABBIX_PASSWORD}, "id": 1}
+    try:
+        response = requests.post(ZABBIX_API_URL, json=payload).json()
+        return response.get('result')
+    except Exception as e:
+        print(f"Error connecting to Zabbix API: {e}")
+        return None
+
+def configure_email(auth_token, email_address):
+    # 1. Update Admin User (ID 1) Media
+    print(f"Configuring Admin user to receive alerts at: {email_address}")
+    user_payload = {
+        "jsonrpc": "2.0",
+        "method": "user.update",
+        "params": {
+            "userid": "1",
+            "medias": [
+                {
+                    "mediatypeid": "1", # Default Email media type
+                    "sendto": [email_address],
+                    "active": 0, # Enabled
+                    "severity": 63, # All severities
+                    "period": "1-7,00:00-24:00"
+                }
+            ]
+        },
+        "id": 2,
+        "auth": auth_token
+    }
+    res = requests.post(ZABBIX_API_URL, json=user_payload).json()
+    if 'result' in res:
+        print("User media successfully updated.")
+    else:
+        print(f"Failed to update user media: {res}")
+        
+    # 2. Enable "Report problems to Zabbix administrators" Action
+    # Usually ID 2 or 3. Let's find it.
+    action_search = {
+        "jsonrpc": "2.0",
+        "method": "action.get",
+        "params": {
+            "output": ["actionid", "name"],
+            "search": {"name": "Report problems to Zabbix administrators"}
+        },
+        "id": 3,
+        "auth": auth_token
+    }
+    actions = requests.post(ZABBIX_API_URL, json=action_search).json().get('result', [])
+    if actions:
+        action_id = actions[0]['actionid']
+        action_enable = {
+            "jsonrpc": "2.0",
+            "method": "action.update",
+            "params": {"actionid": action_id, "status": 0}, # 0 is enabled
+            "id": 4,
+            "auth": auth_token
+        }
+        res_act = requests.post(ZABBIX_API_URL, json=action_enable).json()
+        if 'result' in res_act:
+            print(f"Alert Action '{actions[0]['name']}' successfully enabled.")
+        else:
+            print(f"Failed to enable action: {res_act}")
+    else:
+        print("Could not find default action 'Report problems to Zabbix administrators' to enable.")
+
+if __name__ == "__main__":
+    email = get_email_from_env()
+    token = authenticate()
+    if token:
+        configure_email(token, email)
+    else:
+        print("Could not authenticate to Zabbix on localhost:8081.")

+ 55 - 0
update_taiga_status.py

@@ -0,0 +1,55 @@
+import requests
+import urllib3
+
+urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
+base_url = 'https://192.168.130.161/taiga/api/v1'
+
+def close_sprint_tasks():
+    try:
+        # Authenticate
+        auth = requests.post(f'{base_url}/auth', json={'type': 'normal', 'username': 'FrancoisLange', 'password': 'BTSai123'}, verify=False).json()
+        headers = {'Authorization': f'Bearer {auth["auth_token"]}', 'Content-Type': 'application/json'}
+        proj_id = 21
+
+        # 1. Get Milestone (Sprint 9)
+        milestones = requests.get(f'{base_url}/milestones?project={proj_id}', headers=headers, verify=False).json()
+        sprint9 = next((m for m in milestones if m['name'] == 'Sprint 9'), None)
+        
+        if not sprint9:
+            print("Sprint 9 not found!")
+            return
+            
+        sprint_id = sprint9['id']
+        
+        # 2. Get 'Closed' Task Status ID
+        statuses = requests.get(f'{base_url}/task-statuses?project={proj_id}', headers=headers, verify=False).json()
+        closed_status = next((s for s in statuses if s['is_closed']), None)
+        if not closed_status:
+            print("Could not find a 'Closed' task status for the project.")
+            return
+        
+        closed_status_id = closed_status['id']
+        print(f"Found Closed Status ID: {closed_status_id}")
+
+        # 3. Get all tasks for Sprint 9
+        tasks = requests.get(f'{base_url}/tasks?project={proj_id}&milestone={sprint_id}', headers=headers, verify=False).json()
+        
+        # 4. Close Tasks
+        for task in tasks:
+            if task['status'] != closed_status_id:
+                payload = {
+                    "status": closed_status_id,
+                    "version": task['version']
+                }
+                res = requests.patch(f'{base_url}/tasks/{task["id"]}', json=payload, headers=headers, verify=False).json()
+                print(f"Closed Task TG-{task['ref']}: {task['subject']}")
+            else:
+                print(f"Task TG-{task['ref']} already closed.")
+                
+        print("Successfully updated all Taiga tasks to Closed!")
+        
+    except Exception as e:
+        print(f"Error updating Taiga: {e}")
+
+if __name__ == "__main__":
+    close_sprint_tasks()