-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.py
260 lines (243 loc) · 10.5 KB
/
main.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#!/usr/bin/env python
#this is a simple Organization, Workspaces and run counter for Terraform Enterprise
import json
import requests
import os
import pprint
import pandas
import time
from datetime import datetime
from datetime import date
from yaspin import yaspin
pp = pprint.PrettyPrinter()
TFE_ADDR = os.environ.get('TFE_ADDR', 'https://app.terraform.io')
TFE_API_TOKEN = os.environ.get('TFE_API_TOKEN', '')
TFE_SITE_ADMIN = os.environ.get('TFE_SITE_ADMIN', 'false')
TFE_PAGE_COUNT = os.environ.get('TFE_PAGE_COUNT', 100)
TFE_FILTER_START_DATE = os.environ.get('TFE_FILTER_START_DATE', '01.01.2023')
TFE_FILTER_END_DATE = os.environ.get('TFE_FILTER_END_DATE', date.today().strftime('%d.%m.%Y'))
date_start = datetime.strptime(TFE_FILTER_START_DATE, '%d.%m.%Y')
date_end = datetime.strptime(TFE_FILTER_END_DATE, '%d.%m.%Y')
headers = {
'Content-Type': 'application/vnd.api+json',
'Authorization': f"Bearer {TFE_API_TOKEN}"
}
def getOrgCount():
resp = requests.get(TFE_ADDR+'/api/v2/organizations', headers=headers )
if resp.status_code != 200:
# This means something went wrong.
pp.pprint(f"something went wrong while counting Organizations: {resp}")
return ""
todo_item = resp.json()['data']
return len(todo_item)
def getOrganizations():
resp = requests.get(TFE_ADDR+'/api/v2/organizations', headers=headers )
if resp.status_code != 200:
# This means something went wrong.
pp.pprint(f"something went wrong while getting Organizations: {resp}")
return ""
todo_item = resp.json()['data']
return [ item['id'] for item in todo_item ]
@yaspin(text="Loading...")
def getOrgObj():
result = []
resp = requests.get(TFE_ADDR+'/api/v2/organizations', headers=headers )
if resp.status_code != 200:
# This means something went wrong.
pp.pprint(f"something went wrong while creating Org Object: {resp}")
return ""
todo_item = resp.json()['data']
for item in todo_item:
info = {
'name': item['id'],
'total_runs': getRunsTotalCount(item['id']),
'total_applies': getAppliesTotalCount(item['id']),
'workspace_count': getWorkspaceCount(item['id']),
'workspaces': getWorkspaceInfo(item['id']),
'total_rums': getRUMsTotalCount(item['id'])
}
result.append(info)
return result
def getWorkspaceInfo(organisation):
page = 1
retorno = []
resp = requests.get(TFE_ADDR+f'/api/v2/organizations/{organisation}/workspaces?page[size]=100&page[number]={page}', headers=headers )
if resp.status_code != 200:
# This means something went wrong.
pp.pprint(f"something went wrong while getting workspace info: {resp}")
return ""
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
total_pages = metdata["total-pages"]
while page <= total_pages:
todo_item = resp.json()['data']
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
for item in todo_item:
retorno.append(item['id'])
page += 1
resp = requests.get(TFE_ADDR+f'/api/v2/organizations/{organisation}/workspaces?page[size]=100&page[number]={page}', headers=headers )
return retorno
def getWorkspaceCount(organisation):
page = 1
retorno = []
resp = requests.get(TFE_ADDR+f'/api/v2/organizations/{organisation}/workspaces?page[size]=100&page[number]={page}', headers=headers )
if resp.status_code != 200:
# This means something went wrong.
pp.pprint(f"something went wrong while counting workspaces: {resp}")
return ""
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
total_pages = metdata["total-pages"]
while page <= total_pages:
todo_item = resp.json()['data']
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
for item in todo_item:
retorno.append(item['id'])
page += 1
resp = requests.get(TFE_ADDR+f'/api/v2/organizations/{organisation}/workspaces?page[size]=100&page[number]={page}', headers=headers )
return len(retorno)
def getRunsCount(workspace_id):
page = 1
retorno = []
resp = requests.get(TFE_ADDR+f'/api/v2/workspaces/{workspace_id}/runs?page[size]=100&page[number]={page}', headers=headers )
if resp.status_code != 200:
# This means something went wrong.
pp.pprint(f"something went wrong while counting runs: {resp}")
return ""
todo_item = resp.json()['data']
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
total_pages = metdata["total-pages"]
while page <= total_pages:
todo_item = resp.json()['data']
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
for item in todo_item:
creation_date = datetime.strptime(item['attributes']['created-at'][:10], "%Y-%m-%d")
if date_start < creation_date and creation_date <= date_end : retorno.append(item['id'])
page += 1
resp = requests.get(TFE_ADDR+f'/api/v2/workspaces/{workspace_id}/runs?page[size]=100&page[number]={page}', headers=headers )
return len(retorno)
def getAppliesCount(workspace_id):
page = 1
retorno = []
resp = requests.get(TFE_ADDR+f'/api/v2/workspaces/{workspace_id}/runs?page[size]=100&page[number]={page}', headers=headers )
if resp.status_code != 200:
# This means something went wrong.
pp.pprint(f"something went wrong while counting applies: {resp}")
return ""
todo_item = resp.json()['data']
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
total_pages = metdata["total-pages"]
while page <= total_pages:
todo_item = resp.json()['data']
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
for item in todo_item:
creation_date = datetime.strptime(item['attributes']['created-at'][:10], "%Y-%m-%d")
if item['attributes']['status'] == "applied":
if date_start < creation_date and creation_date <= date_end: retorno.append(item['id'])
page += 1
resp = requests.get(TFE_ADDR+f'/api/v2/workspaces/{workspace_id}/runs?page[size]=100&page[number]={page}', headers=headers )
return len(retorno)
def getResourcesCount(workspace_id):
page = 1
retorno = []
resp = requests.get(TFE_ADDR+f'/api/v2/workspaces/{workspace_id}/resources?page[size]=100&page[number]={page}', headers=headers )
if resp.status_code != 200:
# This means something went wrong.
pp.pprint(f"something went wrong while resources applies: {resp}")
return ""
todo_item = resp.json()['data']
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
total_pages = metdata["total-pages"]
while page <= total_pages:
todo_item = resp.json()['data']
metdata = resp.json()['meta']['pagination']
current_page = metdata["current-page"]
for item in todo_item:
creation_date = datetime.strptime(item['attributes']['created-at'][:10], "%Y-%m-%d")
if date_start < creation_date and creation_date <= date_end: retorno.append(item['id'])
page += 1
resp = requests.get(TFE_ADDR+f'/api/v2/workspaces/{workspace_id}/runs?page[size]=100&page[number]={page}', headers=headers )
return len(retorno)
def getRunsTotalCount(organisation):
total_runs = 0
todo_item = getWorkspaceInfo(organisation)
for item in todo_item:
total_runs += getRunsCount(item)
pp.pprint(f"Total runs for {organisation}: {total_runs}")
return total_runs
def getAppliesTotalCount(organisation):
total_applies = 0
todo_item = getWorkspaceInfo(organisation)
for item in todo_item:
total_applies += getAppliesCount(item)
pp.pprint(f"Total applies for {organisation}: {total_applies}")
return total_applies
def getRUMsTotalCount(organisation):
total_rums = 0
todo_item = getWorkspaceInfo(organisation)
for item in todo_item:
total_rums += getResourcesCount(item)
pp.pprint(f"Total RUMs for {organisation}: {total_rums}")
return total_rums
@yaspin(text="Loading...")
def getWorkspacesFromAdmin():
resp = requests.get(TFE_ADDR+f'/api/v2/admin/workspaces', headers=headers )
if resp.status_code != 200:
# This means something went wrong.
pp.pprint(f"something went wrong: {resp}")
todo = resp.json()['meta']
todo_item = resp.json()['meta']['status-counts']
result = []
info = {
"pending": todo_item["pending"],
"plan-queued": todo_item["plan-queued"],
"planning": todo_item["planning"],
"planned": todo_item["planned"],
"confirmed": todo_item["confirmed"],
"apply-queued": todo_item["apply-queued"],
"applying": todo_item["applying"],
"applied": todo_item["applied"],
"discarded": todo_item["discarded"],
"errored": todo_item["errored"],
"canceled": todo_item["canceled"],
"cost-estimating": todo_item["cost-estimating"],
"cost-estimated": todo_item["cost-estimated"],
"policy-checking": todo_item["policy-checking"],
"policy-override": todo_item["policy-override"],
"policy-checked": todo_item["policy-checked"],
"policy-soft-failed": todo_item["policy-soft-failed"],
"planned-and-finished": todo_item["planned-and-finished"],
"none": todo_item["none"],
"total": todo_item["total"]
}
result.append(info)
return result
#Main just has the calls to the above methods, comment out as needed
def main():
if (TFE_SITE_ADMIN == 'true'):
data = pandas.DataFrame(getWorkspacesFromAdmin())
pp.pprint(data)
else :
result = getOrgObj()
totalWorkspaces = 0
totalRuns = 0
totalApplies = 0
for org in result:
totalWorkspaces += org['workspace_count']
totalRuns += org['total_runs']
totalApplies += org['total_applies']
data = pandas.DataFrame(result)
pp.pprint(data[['name','workspace_count','total_runs','total_applies']])
pp.pprint(f"Total workspaces count: {totalWorkspaces}")
pp.pprint(f"Total runs count: {totalRuns}")
pp.pprint(f"Total applies count: {totalApplies}")
pp.pprint(f"from {date_start} to {date_end}")
if __name__ == '__main__':
main()