-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
281 lines (218 loc) · 12.8 KB
/
app.py
File metadata and controls
281 lines (218 loc) · 12.8 KB
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
import subprocess, sys, io, os, json, random, asyncio, time, uuid, logging, http.client
bicep_code = {
"param_id" : "param id string",
"param_user" : "param user string",
"param_bothstoragetypes" : "param bothstoragetypes int",
"appserviceplan" : "module appserviceplan 'modules/appserviceplan.bicep' = {params: {id : id, user: user}}",
"appserviceblessedimage" : "module appservice 'modules/appserviceblessedimage.bicep' = {params: {id:id, user:user, appServicePlanName: appserviceplan.outputs.appserviceplanname}}",
"appservicewacpublic" : "module appservice 'modules/appservicewebappforcontainerpublic.bicep' = {params: {id:id, user:user, appServicePlanName: appserviceplan.outputs.appserviceplanname}}",
"appservicewacprivate" : "module appservice 'modules/appservicewebappforcontainerprivate.bicep' = {params: {id:id, user:user, appServicePlanName: appserviceplan.outputs.appserviceplanname, azureContainerRegistryName: acr.outputs.acrname, azureContainerRegistryPassword: acr.outputs.password }}",
"acr" :"module acr 'modules/acr.bicep' = {params: {id: id, user: user }}",
"vnet":"module vnet 'modules/vnet.bicep' = {params: {id: id, user: user, appservicename: appservice.outputs.appservicename}}",
"blobstorage" :"module blobstorage 'modules/blobstorage.bicep' = {params: {id : id, user: user, appservicename: appservice.outputs.appservicename, bothstoragetypes: bothstoragetypes}}",
"filestorage" :"module filestorage 'modules/filestorage.bicep' = {params: {id : id, user: user, appservicename: appservice.outputs.appservicename, bothstoragetypes: bothstoragetypes}}",
"appgateway" :"module appgateway 'modules/appgateway.bicep' = {params: {id:id, user:user, vnetname: vnet.outputs.vnetname }}",
"keyvault" : "module keyvault 'modules/keyvault.bicep' = {params: {id : id, user: user, appservicename: appservice.outputs.appservicename}}",
"privateendpoint" : "module privateendpoint 'modules/privateendpoint.bicep' = {params: {id:id, user:user, appservicename: appservice.outputs.appservicename, vnetname: vnet.outputs.vnetname }}"
}
services_pretty = {
"appserviceblessedimage" : "Blessed Image: ",
"appservicewacpublic" : "Web App for Container: ",
"acr" : "Azure Container Registry ",
"vnet" : "Vnet Intergration ",
"privateendpoint" : "Private Endpoint ",
"blobstorage" : "Storage Mount Blob ",
"filestorage": "Storage Mount File Share ",
"appgateway": "App GateWay ",
"keyvault" : "KeyVault "
}
service_name_short = {
"acr" : "acr",
"vnet" : "vnet",
"privateendpoint" : "pe",
"blobstorage" : "blobmnt",
"filestorage": "filemnt",
"appgateway": "appgw",
"keyvault" : "kv"
}
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def generate_rg_name(user_name, services, id):
if len(services) < 2:
return user_name + '-repo-' + id
name = user_name + "-"
for service in services:
if (service not in ['appserviceblessedimage', 'appservicewacpublic']):
name += service_name_short[service]
name += '-'
return name + id
def write_bicep(modules_list):
f = open ('main.bicep', 'a')
for module_name in modules_list:
f.write(bicep_code[module_name])
f.write('\n')
f.close()
def get_az_account_data():
subprocess_use_shell = True if len(sys.argv) > 1 and sys.argv[1] == 'DEBUG' else False
data = subprocess.run(["az", "account", "show"], capture_output=True, shell=subprocess_use_shell)
account_data = json.loads(data.stdout)
subscription_id = account_data['id']
subscription_name = account_data['name']
user_name = account_data['user']['name'].split('@')[0]
return [user_name, subscription_name, subscription_id]
def run_input_loop():
service_selection = set()
appservice_type = ''
while appservice_type == '':
try:
print("Choose App Service Type:\n")
print(services_pretty['appserviceblessedimage'] + bcolors.WARNING + "[1]" + bcolors.ENDC)
print(services_pretty['appservicewacpublic'] + bcolors.WARNING + "[2]" + bcolors.ENDC)
appservice_type = int(input("Enter 1 or 2: "))
if int(appservice_type) not in ([1,2]):
appservice_type = ''
print('\n' + bcolors.FAIL + 'Incorrect value, enter: 1, 2, or 3' + bcolors.ENDC)
except ValueError:
print('\n' + bcolors.FAIL + 'Incorrect value, enter: 1, 2, or 3' + bcolors.ENDC)
match appservice_type:
case 1:
service_selection.add('appserviceblessedimage')
case 2:
service_selection.add('appservicewacpublic')
done = False
while done == False:
print("\nEnter space seperated numbers of the options, if done type: " + bcolors.OKGREEN + "[y/Y]" + bcolors.ENDC)
print("Example Input: 1 2 6\n")
print("Select additional services to add: \n")
print ('Service | Added')
selection_list = ['acr', 'vnet', 'privateendpoint', 'blobstorage', 'filestorage', 'appgateway', 'keyvault']
for i, s in enumerate(selection_list):
if s not in service_selection:
print ("{0:18}| {1}".format(services_pretty[s] + bcolors.WARNING + "[" + str(i + 1) + "]" + bcolors.ENDC, "False"))
else:
print ("{0:18}| {1}".format(services_pretty[s] + bcolors.WARNING + "[" + str(i + 1) + "]" + bcolors.ENDC, (bcolors.OKGREEN + "True" + bcolors.ENDC + " - Re-enter number to remove")))
y = input()
input_string = y.split(" ")
for i in input_string:
if i in ['1', '2', '3', '4', '5', '6', '7']:
service = selection_list[int(i) - 1]
if service not in service_selection:
service_selection.add(service)
else:
service_selection.remove(service)
elif i.upper() == "Y":
done = True
else:
print('\n' + bcolors.FAIL + 'Incorrect value, enter 1 - 7 or Y to finish' + bcolors.ENDC)
return service_selection
def deploy_bicep(deployment_name, user, id, bothstoragetypes, location):
subprocess_use_shell = True if len(sys.argv) > 1 and sys.argv[1] == 'DEBUG' else False
try:
# az group create --verbose --name $name --location eastus
output = subprocess.run(["az", "group", "create", "--verbose", "--name", deployment_name, "--location", location], capture_output=True, shell=subprocess_use_shell)
logging.info(json.loads(output.stdout))
except Exception as e:
print(type(e), e)
print("Your Azure Deployment failed due to the following message:")
print(bcolors.FAIL + str(output.stderr) + bcolors.ENDC)
print("Feel free to file a Github Issues regarding this error, your feedback is appreciated.")
exit()
#az deployment group create --verbose --resource-group $name --template-file main.bicep --parameters id="32" user="kedsouza"
#output = subprocess.run(["az", "deployment", "group", "create", "--verbose", "--resource-group", deployment_name, "--template-file", "main.bicep", "--parameters", ("id=" + id), ("user=" + user) ], capture_output=True, shell=subprocess_use_shell)
try:
#az deployment group create --verbose --resource-group $name --template-file main.bicep --parameters id="32" user="kedsouza"
output = subprocess.run(["az", "deployment", "group", "create", "--verbose", "--resource-group", deployment_name, "--template-file", "main.bicep", "--parameters", ("id=" + id), ("user=" + user), ("bothstoragetypes=" + str(bothstoragetypes)) ], capture_output=True, shell=subprocess_use_shell)
logging.info(json.loads(output.stdout))
except Exception as e:
print(type(e), e)
print("Your Azure Deployment failed due to the following message:")
print(bcolors.FAIL + str(output.stderr) + bcolors.ENDC)
print("Feel free to file a Github Issues regarding this error, your feedback is appreciated.")
exit()
def print_subscription_information(user_name, subscription_name, subscription_id):
print("\nThis is the account information you are running with. If this is not correct please use `az account set` to correct this before continuing.")
print("--------------------------------------------------------------------------------")
print("User: " + bcolors.OKCYAN + " {0}".format(user_name) + bcolors.ENDC)
print("Subscription Name: " + bcolors.OKCYAN + "{0}".format(subscription_name) + bcolors.ENDC)
print("Subscription Id: " + bcolors.OKCYAN + "{0}".format(subscription_id) + bcolors.ENDC)
print("--------------------------------------------------------------------------------\n")
def print_deployment_progress(subscription_id, deploy_name):
print ("\nYour deployment is running view progress by clicking on this link")
print(bcolors.OKBLUE + "https://ms.portal.azure.com/#@fdpo.onmicrosoft.com/resource/subscriptions/{0}/resourceGroups/{1}/deployments".format(subscription_id, deploy_name) + bcolors.ENDC)
print("Waiting for all operations to finish...")
def print_deployment_complete(subscription_id, deploy_name):
print ("\nYour deployment seems complete, you can view the resource group by clicking on this link")
print(bcolors.OKBLUE + "https://ms.portal.azure.com/#@fdpo.onmicrosoft.com/resource/subscriptions/{0}/resourceGroups/{1}/overview".format(subscription_id, deploy_name) + bcolors.ENDC)
def run_any_outstanding_az_cli_commands(services, user, id):
if "acr" in services:
subprocess_use_shell = True if len(sys.argv) > 1 and sys.argv[1] == 'DEBUG' else False
try:
#az acr import --name kedsouzaacr03 --source mcr.microsoft.com/appsvc/php:latest_20221101.1 -t appsvcphp:latest
output = subprocess.run(["az", "acr", "import", "--name", (user + 'acr' + id), "--source", "mcr.microsoft.com/appsvc/php:latest_20221101.1", "-t", "appsvcphp:latest"], capture_output=True, shell=subprocess_use_shell)
except Exception as e:
print(type(e), e)
print("Your Azure Deployment failed due to the following message:")
print(bcolors.FAIL + str(output.stderr) + bcolors.ENDC)
print("Feel free to file a Github Issues regarding this error, your feedback is appreciated.")
exit()
def initalize_main_bicep():
try:
with open('main.bicep', 'x') as file:
# Add default options to the bicep file.
write_bicep(["param_id"])
write_bicep(["param_user"])
write_bicep(["param_bothstoragetypes"])
write_bicep(["appserviceplan"])
except FileExistsError:
with open('main.bicep', 'w') as file:
# Add default options to the bicep file.
write_bicep(["param_id"])
write_bicep(["param_user"])
write_bicep(["param_bothstoragetypes"])
write_bicep(["appserviceplan"])
def review_service_selection(services):
if "acr" in services and "appservicewacpublic" in services:
services.remove('appservicewacpublic')
services.add('appservicewacprivate')
if "privateendpoint" in services and not "vnet" in services:
services.add('vnet')
if "appgateway" in services and not "vnet" in services:
services.add('vnet')
return services
def main():
location = 'northcentralus'
for arg in sys.argv:
if arg[0:8] == 'location':
location = arg[9:]
print("Setting location to:", location)
try:
logging.basicConfig(filename='az_output.log', level=logging.INFO)
user_name, subscription_name, subscription_id = get_az_account_data()
user_name = user_name.split('.')[0].lower()
print_subscription_information(user_name, subscription_name, subscription_id)
services = run_input_loop()
id = str(random.randint(0, 9)) + str(random.randint(0, 9))
resource_group_name = generate_rg_name(user_name, services, id)
initalize_main_bicep()
services = review_service_selection(services)
bothstoragetypes = 0
if "blobstorage" in services and "filestorage" in services:
bothstoragetypes = 1
for service in services:
write_bicep([service])
print_deployment_progress(subscription_id, resource_group_name)
deploy_bicep(resource_group_name, user_name, id, bothstoragetypes, location)
run_any_outstanding_az_cli_commands(services, user_name, id)
print_deployment_complete(subscription_id, resource_group_name)
except KeyboardInterrupt:
exit()
if __name__ == "__main__":
main()