-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware_lambda_fn.py
180 lines (157 loc) · 6.3 KB
/
middleware_lambda_fn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import json
import urllib3
from urllib3.exceptions import HTTPError
# Create a PoolManager instance for making requests
http = urllib3.PoolManager()
# Function to create a data source with enhanced logging
def create_data_source(grafana_url, token, data_source_name, data_source_uid, data_source_url, basic_auth_password, basic_auth_user):
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
data_source_payload = {
"name": data_source_name,
"type": "prometheus",
"url": data_source_url,
"access": "proxy",
"basicAuth": True,
"basicAuthUser": basic_auth_user,
"secureJsonData": {
"basicAuthPassword": basic_auth_password
},
"jsonData": {
"timeInterval": "5s"
},
"uid": data_source_uid
}
try:
response = http.request(
'POST',
f"{grafana_url}/api/datasources",
headers=headers,
body=json.dumps(data_source_payload)
)
# Log the response status and body for debugging
print("Data Source Creation Response Status:", response.status)
print("Data Source Creation Response Body:", response.data.decode('utf-8'))
# Check for a successful response (HTTP status 200 or 201)
if response.status in [200, 201]:
return response
else:
print("Error creating data source:", response.data.decode('utf-8'))
return None
except HTTPError as e:
print(f"Failed to create data source: {e}")
return None
def create_dashboard(grafana_url, token, data_source_uid, dashboard_title, dashboard_description):
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
try:
# Load the JSON template and update title, description, and data source UID
with open('dashboard.json', 'r') as file:
dashboard_data = json.load(file)
dashboard_data["dashboard"]["title"] = dashboard_title
dashboard_data["dashboard"]["description"] = dashboard_description
# Replace the data source placeholder with the actual UID
json_str = json.dumps(dashboard_data)
json_str = json_str.replace("${DS_PROMETHEUS}", data_source_uid)
updated_dashboard_json = json.loads(json_str)
# Make the request to create the dashboard
response = http.request(
'POST',
f"{grafana_url}/api/dashboards/db",
headers=headers,
body=json.dumps(updated_dashboard_json)
)
# Log response status and body for debugging
print("Dashboard Creation Response Status:", response.status)
print("Dashboard Creation Response Body:", response.data.decode('utf-8'))
# Check if creation was successful (HTTP 200 or 201)
if response.status in [200, 201]:
return response
else:
print("Error creating dashboard:", response.data.decode('utf-8'))
return None
except Exception as e:
print(f"Failed to create dashboard: {e}")
return None
# Lambda handler function
def lambda_handler(event, context):
try:
print(f"Received event: {event}") # Log the received event for debugging
data = json.loads(event['body'])
# Ensure all required fields are present
required_fields = [
"data_source_name", "data_source_uid", "data_source_url",
"dashboard_title", "dashboard_description",
"basic_auth_user", "basic_auth_password",
"grafana_url", "grafana_token"
]
for field in required_fields:
if field not in data:
return {
"statusCode": 400,
"body": json.dumps({
"status": "error",
"message": f"Missing required field: {field}"
})
}
# Assign variables from the data
data_source_name = data["data_source_name"]
data_source_uid = data["data_source_uid"]
data_source_url = data["data_source_url"]
dashboard_title = data["dashboard_title"]
dashboard_description = data["dashboard_description"]
basic_auth_password = data["basic_auth_password"]
basic_auth_user = data["basic_auth_user"]
grafana_url = data["grafana_url"]
grafana_token = data["grafana_token"]
# Create the data source
data_source_response = create_data_source(grafana_url, grafana_token, data_source_name, data_source_uid, data_source_url, basic_auth_password, basic_auth_user)
if data_source_response and data_source_response.status == 200:
# Create the dashboard
dashboard_response = create_dashboard(grafana_url, grafana_token, data_source_uid, dashboard_title, dashboard_description)
if dashboard_response and dashboard_response.status == 200:
return {
"statusCode": 201,
"body": json.dumps({
"status": "success",
"message": "Dashboard successfully created!",
"response": json.loads(dashboard_response.data.decode('utf-8'))
})
}
else:
return {
"statusCode": 500,
"body": json.dumps({
"status": "error",
"message": "Failed to create dashboard."
})
}
else:
return {
"statusCode": 500,
"body": json.dumps({
"status": "error",
"message": "Failed to create data source."
})
}
except json.JSONDecodeError:
return {
"statusCode": 400,
"body": json.dumps({
"status": "error",
"message": "Invalid JSON format."
})
}
except Exception as e:
print(f"Error: {e}")
return {
"statusCode": 500,
"body": json.dumps({
"status": "error",
"message": str(e) # Return the error message for debugging
})
}