-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
435 lines (343 loc) · 18.2 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
from __future__ import print_function
import json
import requests
import configparser
import os
import re
requests.packages.urllib3.disable_warnings() # Added to avoid warnings in output if proxy
def return_error(message):
print("\nERROR: " + message)
exit(1)
def get_parser_from_sections_file(file_name):
file_parser = configparser.ConfigParser()
try: # Checks if the file has the proper format
file_parser.read(file_name)
except (ValueError, configparser.MissingSectionHeaderError, configparser.DuplicateOptionError,
configparser.DuplicateOptionError):
return_error("Unable to read file " + file_name)
return file_parser
def read_value_from_sections_file(file_parser, section, option):
value = {}
value['Exists'] = False
if file_parser.has_option(section, option): # Checks if section and option exist in file
value['Value'] = file_parser.get(section, option)
if not value['Value'] == '': # Checks if NOT blank (so properly updated)
value['Exists'] = True
return value
def read_value_from_sections_file_and_exit_if_not_found(file_name, file_parser, section, option):
value = read_value_from_sections_file(file_parser, section, option)
if not value['Exists']:
return_error("Section \"" + section + "\" and option \"" + option + "\" not found in file " + file_name)
return value['Value']
def load_api_config(iniFilePath):
if not os.path.exists(iniFilePath):
return_error("Config file " + iniFilePath + " does not exist")
iniFileParser = get_parser_from_sections_file(iniFilePath)
api_config = {}
api_config['BaseURL'] = read_value_from_sections_file_and_exit_if_not_found(iniFilePath, iniFileParser, 'URL',
'URL')
api_config['AccessKey'] = read_value_from_sections_file_and_exit_if_not_found(iniFilePath, iniFileParser,
'AUTHENTICATION', 'ACCESS_KEY_ID')
api_config['SecretKey'] = read_value_from_sections_file_and_exit_if_not_found(iniFilePath, iniFileParser,
'AUTHENTICATION', 'SECRET_KEY')
return api_config
# Option for AWS secrets retrieval instead of local file
#import boto3
#from botocore.exceptions import ClientError # Create a Secrets Manager client
# secrets_client = boto3.client('secretsmanager')
#
# try:
# # Retrieve the secret value from Secrets Manager
# get_secret_response = secrets_client.get_secret_value(SecretId=secret_name)
# except ClientError as e:
# # Handle any errors that occur when retrieving the secret value
# print(f"Error retrieving secret {secret_name}: {e}")
# return api_config
# # Decode the secret value (which is a JSON string) into a Python dictionary
# secret_value_dict = json.loads(get_secret_response['SecretString'])
# # Extract the specific values needed for the API configuration
# api_config['BaseURL'] = secret_value_dict['BaseURL']
# api_config['AccessKey'] = secret_value_dict['AccessKey']
# api_config['SecretKey'] = secret_value_dict['SecretKey']
# return api_config
#def get_secret():
# secret_name = "PrismaCloud"
# region_name = "eu-west-1"
# # Create a Secrets Manager client
# session = boto3.session.Session()
# client = session.client(
# service_name='secretsmanager',
# region_name=region_name
# )
# try:
# get_secret_value_response = client.get_secret_value(
# SecretId=secret_name
# )
# except ClientError as e:
# # For a list of exceptions thrown, see
# # https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
# raise e
# # Decrypts secret using the associated KMS key.
# secret = get_secret_value_response['SecretString']
def handle_api_response(apiResponse):
status = apiResponse.status_code
if (status != 200):
return_error("API call failed with HTTP response " + str(status))
def run_api_call_with_payload(action, url, headers_value, payload):
apiResponse = requests.request(action, url, headers=headers_value, data=json.dumps(payload),
verify=False) # verify=False to avoid CA certificate error if proxy between script and console
handle_api_response(apiResponse)
return apiResponse
def run_api_call_without_payload(action, url, headers_value):
apiResponse = requests.request(action, url, headers=headers_value,
verify=False) # verify=False to avoid CA certificate error if proxy between script and console
handle_api_response(apiResponse)
return apiResponse
def login(api_config):
action = "POST"
url = api_config['BaseURL'] + "/login"
headers = {
'Content-Type': 'application/json'
}
payload = {
'username': api_config['AccessKey'],
'password': api_config['SecretKey'],
}
apiResponse = run_api_call_with_payload(action, url, headers, payload)
authentication_response = apiResponse.json()
token = authentication_response['token']
return token
### APIs to interact with Account Groups ###
def get_account_groups(api_config):
action = "GET"
url = api_config['BaseURL'] + "/cloud/group"
headers = {
'x-redlock-auth': api_config['Token']
}
apiResponse = run_api_call_without_payload(action, url, headers)
accountGroups = json.loads(apiResponse.text)
return accountGroups
print(accountGroups)
def update_account_group(api_config, accountGroupName, accountGroupId, accountIds, description):
action = "PUT"
url = api_config['BaseURL'] + "/cloud/group/" + accountGroupId
headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'x-redlock-auth': api_config['Token']
}
payload = {
'accountIds': accountIds,
'name': accountGroupName,
'description': description
}
run_api_call_with_payload(action, url, headers, payload)
def create_account_group(api_config, accountGroupName, accountIds, description):
action = "POST"
url = api_config['BaseURL'] + "/cloud/group/"
headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'x-redlock-auth': api_config['Token']
}
payload = {
'accountIds': accountIds,
'name': accountGroupName,
'description': description
}
run_api_call_with_payload(action, url, headers, payload)
def delete_account_group(api_config, accountGroupId):
action = "DELETE"
url = api_config['BaseURL'] + "/cloud/group/" + accountGroupId
headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'x-redlock-auth': api_config['Token']
}
run_api_call_with_payload(action, url, headers)
### APIs to interact with Cloud Accounts and Organization Accounts ###
def get_cloud_accounts(api_config):
action = "GET"
url = api_config['BaseURL'] + "/cloud/"
headers = {
'x-redlock-auth': api_config['Token']
}
apiResponse = run_api_call_without_payload(action, url, headers)
accounts = json.loads(apiResponse.text)
return accounts
def get_org_cloud_account_from_cloud_account(api_config, cloudAccountId, cloudType):
action = "GET"
url = api_config['BaseURL'] + "/cloud/" + cloudType + "/" + cloudAccountId + "/project"
headers = {
'x-redlock-auth': api_config['Token']
}
apiResponse = run_api_call_without_payload(action, url, headers)
accounts = json.loads(apiResponse.text)
return accounts
### Processing Functions Cloud Accounts###
def get_all_org_cloud_account_per_cloud_type(api_config, cloudAccountList, cloudType):
orgAccounts = []
for cloudAccount in cloudAccountList:
if cloudAccount["accountType"] in ('tenant', 'organization'):
accounts = get_org_cloud_account_from_cloud_account(api_config, cloudAccount["accountId"], cloudType)
for account in accounts:
orgAccounts.append(account)
else:
orgAccounts.append(cloudAccount)
return orgAccounts
def get_all_org_cloud_account_based_name_convention(orgAccountList, nameConvention):
orgAccountsMatching = []
orgAccountsNotMatching = []
for account in orgAccountList:
if re.match(nameConvention, account["name"]):
orgAccountsMatching.append(account)
else:
orgAccountsNotMatching.append(account)
return orgAccountsMatching, orgAccountsNotMatching
def get_cloud_accounts_by_cloud_type(cloudAccountList, cloudType):
cloudAccountsMatching = []
for cloudAccount in cloudAccountList:
if (cloudAccount['cloudType'].lower() == cloudType.lower()):
cloudAccountsMatching.append(cloudAccount)
return cloudAccountsMatching
def get_cloud_accounts_not_having_acount_group(cloudAccountList, accountGroupsList):
cloudAccountsMatching = []
for cloudAccount in cloudAccountList:
accountGroupName = "custom_" + cloudAccount["name"].split()[0]
accountGroupExist = if_accountGroupName_exist_in_accountGroupList(accountGroupName, accountGroupsList)
if not accountGroupExist:
cloudAccountsMatching.append(cloudAccount)
return cloudAccountsMatching
### Processing Functions Account Groups###
def get_name_of_all_accountGroup(accountGroupsList):
accountGroupNames = []
for accountGroup in accountGroupsList:
accountGroupNames.append(accountGroup['name'])
return accountGroupNames
def get_account_groups_of_cloudAccount(cloudAccount, accountGroupsList):
accountGroupsMatching = []
for accountGroup in accountGroupsList:
if accountGroup['id'] in cloudAccount['groupIds']:
accountGroupsMatching.append(accountGroup)
return accountGroupsMatching
def if_accountGroupName_exist_in_accountGroupList(accountGroupName, accountGroupsList):
accountGroupExists = False
for accountGroup in accountGroupsList:
if (accountGroup['name'].lower() == accountGroupName.lower()):
accountGroupExists = True
break
return accountGroupExists
def get_accountGroupData_from_accountGroupList_by_name_equals(accountGroupName, accountGroupsList):
accountGroupExists = False
for accountGroup in accountGroupsList:
if (accountGroup['name'].lower() == accountGroupName.lower()):
accountGroupExists = True
break
if not accountGroupExists:
return_error("Account Group \"" + accountGroupName + "\" does not exist")
return accountGroup
def get_accountIds_from_accountGroup_by_name_contains(nameToSearch, accountGroupData):
accountsMatching = []
for account in accountGroupData['accounts']:
if (nameToSearch.lower() in account['name'].lower()):
accountsMatching.append(account)
print("Number of Cloud Accounts matching \"" + nameToSearch + "\" in Account Group \"" + accountGroupData[
'name'] + "\": " + str(len(accountsMatching)))
if (len(accountsMatching) > 0):
for account in accountsMatching:
print("\t" + account['name'])
return accountsMatching
def delete_item_from_list_if_exists(item, list):
if item in list:
list.remove(item)
return list
def add_item_in_list_if_not_exists(item, list):
if item not in list:
list.append(item)
return list
def delete_account_from_account_group(api_config, account, accountGroup):
accountIds = delete_item_from_list_if_exists(account['accountId'], accountGroup['accountIds'])
print("Deleting account \"" + account['name'] + "\" from Account Group \"" + accountGroup['name'] + "\"")
update_account_group(api_config, accountGroup['name'], accountGroup['id'], accountIds, accountGroup['description'])
def add_account_in_account_group(api_config, account, accountGroup):
accountIds = add_item_in_list_if_not_exists(account['id'], accountGroup['accountIds'])
print("Adding account \"" + account['name'] + "\" to Account Group \"" + accountGroup['name'] + "\"")
update_account_group(api_config, accountGroup['name'], accountGroup['id'], accountIds, accountGroup['description'])
def create_account_groups_based_cloudAccounts(api_config, cloudAccountList, accountGroupsList):
AccountGroupNameList = []
defaultAccountGroup = get_accountGroupData_from_accountGroupList_by_name_equals("Default Account Group",
accountGroupsList)
for cloudAccount in cloudAccountList:
# specify your cloud account group prefix here (e.g. custom_), if required, use the same prefix in assign_account_groups_based_cloudAccounts
NewAccountGroupName = "custom_" + cloudAccount["name"].split()[0]
if NewAccountGroupName not in AccountGroupNameList:
AccountGroupNameList.append(NewAccountGroupName)
create_account_group(api_config, NewAccountGroupName, [cloudAccount["accountId"]],
"Account Group created for Service type " + cloudAccount["name"].split()[0])
delete_account_from_account_group(api_config, cloudAccount, defaultAccountGroup)
print("Account Group " + NewAccountGroupName + " is created and assigned to the cloud Account " +
cloudAccount['name'])
else:
accountGroup = get_accountGroupData_from_accountGroupList_by_name_equals(NewAccountGroupName,
accountGroupsList)
accountId = cloudAccount['accountId']
accountIds = accountGroup['accountIds']
if accountId not in accountIds:
accountIds.append(accountId)
update_account_group(api_config, NewAccountGroupName, accountGroup['id'], accountIds,
"Account Group created for Service type " + cloudAccount["name"].split()[0])
delete_account_from_account_group(api_config, cloudAccount, defaultAccountGroup)
print("The Account Group " + NewAccountGroupName + " is assigned to the cloud Account " + cloudAccount[
'name'])
def assign_account_groups_based_cloudAccounts(api_config, cloudAccountList, accountGroupsList):
AccountGroupNameList = []
defaultAccountGroup = get_accountGroupData_from_accountGroupList_by_name_equals("Default Account Group",
accountGroupsList)
for cloudAccount in cloudAccountList:
# specify your cloud account group prefix here (e.g. custom_), if required
accountGroupName = "custom_" + cloudAccount["name"].split()[0]
accountGroup = get_accountGroupData_from_accountGroupList_by_name_equals(accountGroupName, accountGroupsList)
accountId = cloudAccount['accountId']
accountIds = accountGroup['accountIds']
if accountId not in accountIds:
accountIds.append(accountId)
print("The Account Group " + accountGroupName + " is assigned to the cloud Account " + cloudAccount['name'])
update_account_group(api_config, accountGroupName, accountGroup['id'], accountIds,
"Account Group created for Service type " + cloudAccount["name"].split()[0])
#delete_account_from_account_group(api_config, cloudAccount, defaultAccountGroup)
def main():
# ----------- Load API configuration from .ini file -----------
api_config = load_api_config("API_config.ini")
# ----------- First API call for authentication -----------
token = login(api_config)
api_config['Token'] = token
# ----------- Naming Convention -----------
#nameConvention = "([a-zA-Z0-9]*)[_ ]Subscription*"
# !!! use naming convention variable here to match your specific account name regex for Account group creation and assignments
nameConvention = "ok*"
# ----------- Get Account Groups and Cloud Accounts -----------
# chose your cloud provider aws or azure and uncomment relevant code, azure is currently commented out to work on aws accounts only
accountGroupsList = get_account_groups(api_config)
cloudAccountList = get_cloud_accounts(api_config)
# ----------- Get org Accounts based on Cloud Accounts and cloud type-----------
#azureCloudAccountList = get_cloud_accounts_by_cloud_type(cloudAccountList, 'azure')
awsCloudAccountList = get_cloud_accounts_by_cloud_type(cloudAccountList, 'aws')
#azureAllOrgAccountList = get_all_org_cloud_account_per_cloud_type(api_config, azureCloudAccountList, 'azure')
awsAllOrgAccountList = get_all_org_cloud_account_per_cloud_type(api_config, awsCloudAccountList, 'aws')
# ----------- Filter all cloud accounts in a cloud Type based on the name convention-----------
#(azureOrgAccountsMatching, azureOrgAccountsNotMatching) = get_all_org_cloud_account_based_name_convention(
# azureAllOrgAccountList, nameConvention)
(awsOrgAccountsMatching, awsOrgAccountsNotMatching) = get_all_org_cloud_account_based_name_convention(
awsAllOrgAccountList, nameConvention)
# ----------- List of cloud accounts that doesn't have a matching Account Group-----------
#newAzureAccountList = get_cloud_accounts_not_having_acount_group(azureOrgAccountsMatching, accountGroupsList)
newAwsAccountList = get_cloud_accounts_not_having_acount_group(awsOrgAccountsMatching, accountGroupsList)
# ----------- Create missing account groups and assign them to the source Cloud Account filtered by cloud Type-----------
#create_account_groups_based_cloudAccounts(api_config, newAzureAccountList, accountGroupsList)
create_account_groups_based_cloudAccounts(api_config, newAwsAccountList, accountGroupsList)
# ----------- do a recursive lookup in all cloud accounts of a cloudType matching the name convention specified by nameConvention variable and assign them to the corresponding Account Group-----------
accountGroupsList = get_account_groups(api_config)
#assign_account_groups_based_cloudAccounts(api_config, azureOrgAccountsMatching, accountGroupsList)
assign_account_groups_based_cloudAccounts(api_config, awsOrgAccountsMatching, accountGroupsList)
if __name__ == "__main__":
main()