forked from Azure/azurehpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathazutil.py
323 lines (295 loc) · 11.6 KB
/
azutil.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
import datetime
import json
import os
import shlex
import subprocess
import sys
import time
import azlog
log = azlog.getLogger(__name__)
def _make_subprocess_error_string(res):
return "\n args={}\n return code={}\n stdout={}\n stderr={}".format(res.args, res.returncode, res.stdout.decode("utf-8"), res.stderr.decode("utf-8"))
def get_subscription_id():
cmd = [ "az", "account", "show", "--output", "tsv", "--query", "id" ]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
out = res.stdout.splitlines()
return out[0].decode("utf-8")
def delete_resources(ids):
cmd = [ "az", "resource", "delete", "--ids" ] + ids
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
return res.stdout
def get_vm_private_ip(resource_group, vm_name):
cmd = [
"az", "vm", "list-ip-addresses",
"--resource-group", resource_group,
"--name", vm_name,
"--query", "[0].virtualMachine.network.privateIpAddresses",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
out = res.stdout.splitlines()
return out[0].decode("utf-8")
def get_dns_label(resource_group, public_ip, ignore_errors):
cmd = [
"az", "network", "public-ip", "show",
"--resource-group", resource_group,
"--name", public_ip,
"--query", "dnsSettings.domainNameLabel",
"--output", "tsv"
]
log.debug(" ".join(cmd))
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
if ignore_errors:
return None
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
out = res.stdout.splitlines()
return out[0].decode("utf-8")
def get_fqdn(resource_group, public_ip):
cmd = [
"az", "network", "public-ip", "show",
"--resource-group", resource_group,
"--name", public_ip,
"--query", "dnsSettings.fqdn",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
out = res.stdout.splitlines()
return out[0].decode("utf-8")
def get_vmss_instances(resource_group, vmss_name):
cmd = [
"az", "vmss", "list-instances",
"--resource-group", resource_group,
"--name", vmss_name,
"--query", "[].osProfile.computerName",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
names = [ x.decode("utf-8") for x in res.stdout.splitlines() ]
return names
def create_resource_group(resource_group, location, tags=None):
log.debug("creating resource group")
if tags is None:
tag_args = []
else:
tag_args = [ "--tags" ] + [ f"{t['key']}={t['value']}" for t in tags ]
cmd = [
"az", "group", "create",
"--name", resource_group,
"--location", location
] + tag_args
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
def delete_resource_group(resource_group, nowait):
log.debug("deleting resource group")
cmd = [
"az", "group", "delete",
"--name", resource_group, "--yes"
]
if nowait == True:
cmd.append("--no-wait")
log.debug(" ".join(cmd))
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
def deploy(resource_group, arm_template):
log.debug("deploying template")
deployname = os.path.splitext(
os.path.basename(arm_template)
)[0] + time.strftime("%Y%m%d-%H%M%S")
cmd = [
"az", "deployment", "group", "create",
"--resource-group", resource_group,
"--template-file", arm_template,
"--name", deployname,
"--no-wait"
]
log.debug(" ".join(cmd))
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
return deployname
def get_deployment_status(resource_group, deployname):
cmd = [
"az", "group", "deployment", "operation", "list",
"--resource-group", resource_group,
"--name", deployname,
"--output", "json"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
sys.exit(1)
return json.loads(res.stdout)
def get_keyvault_secret(vault, key):
cmd = [
"az", "keyvault", "secret", "show",
"--name", key, "--vault-name", vault,
"--query", "value", "--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
secret = res.stdout.decode('utf-8').rstrip('\r\n')
return secret
def get_storage_url(account):
cmd = [
"az", "storage", "account", "show",
"--name", account,
"--query", "primaryEndpoints.blob",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
out = res.stdout.splitlines()
if len(out) != 1:
log.error("unexpected output"+_make_subprocess_error_string(res))
url = out[0].decode('utf-8')
return url
def get_storage_key(account):
cmd = [
"az", "storage", "account", "keys", "list",
"--account-name", account,
"--query", "[0].value",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
out = res.stdout.splitlines()
if len(out) != 1:
log.error("unexpected output"+_make_subprocess_error_string(res))
key = out[0].decode('utf-8')
return key
def get_storage_saskey(account, container, permissions, duration="2h"):
log.debug(f"creating sas key: container={container}, permissions={permissions}, length={duration}")
start = (datetime.datetime.utcnow() - datetime.timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%SZ")
# convert integer string to int type
length = int(duration[:-1])
unit = duration[-1]
if unit == "h":
expiry = (datetime.datetime.utcnow() + datetime.timedelta(hours=length)).strftime("%Y-%m-%dT%H:%M:%SZ")
elif unit == "d":
expiry = (datetime.datetime.utcnow() + datetime.timedelta(days=length)).strftime("%Y-%m-%dT%H:%M:%SZ")
elif unit == "y":
expiry = (datetime.datetime.utcnow() + datetime.timedelta(days=(length*365))).strftime("%Y-%m-%dT%H:%M:%SZ")
else:
log.error("unknown duration for saskey (format is X[h|d|y] for X hours, days or years)")
cmd = [
"az", "storage", "container", "generate-sas",
"--account-name", account,
"--name", container,
"--permissions", permissions,
"--start", start,
"--expiry", expiry,
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
out = res.stdout.splitlines()
if len(out) != 1:
log.error("unexpected output"+_make_subprocess_error_string(res))
saskey = out[0].decode('utf-8')
return saskey
def get_log_analytics_workspace(resource_group, name):
cmd = [
"az", "monitor", "log-analytics", "workspace", "list",
"--query", f"[?name=='{name}'&&resourceGroup=='{resource_group}'].customerId",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
out = res.stdout.splitlines()
if len(out) != 1:
log.error("unexpected output"+_make_subprocess_error_string(res))
saskey = out[0].decode('utf-8')
return saskey
def get_log_analytics_key(resource_group, name):
cmd = [
"az", "monitor", "log-analytics", "workspace", "get-shared-keys",
"--workspace-name", name,
"--resource-group", resource_group,
"--query", "primarySharedKey",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
out = res.stdout.splitlines()
if len(out) != 1:
log.error("unexpected output"+_make_subprocess_error_string(res))
saskey = out[0].decode('utf-8')
return saskey
# Return the image id of a managed image object stored into the resource group
def get_image_id(resource_group, name):
cmd = [
"az", "image", "show",
"--name", name,
"--resource-group", resource_group,
"--query", "[id]",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
out = res.stdout.splitlines()
if len(out) != 1:
log.error("unexpected output"+_make_subprocess_error_string(res))
id = out[0].decode('utf-8')
return id
def get_anf_volume_ip(resource_group, account, pool, volume):
cmd = [
"az", "netappfiles", "volume", "show",
"--resource-group", resource_group,
"--account-name", account,
"--pool-name", pool,
"--name", volume,
"--query", "mountTargets[0].ipAddress",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
out = res.stdout.splitlines()
if len(out) != 1:
log.error("unexpected output"+_make_subprocess_error_string(res))
ip = out[0].decode('utf-8')
return ip
def get_acr_key(name):
cmd = [
"az", "acr", "credential", "show",
"--name", name,
"--query", "passwords[0].value",
"--output", "tsv"
]
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode != 0:
log.error("invalid returncode"+_make_subprocess_error_string(res))
out = res.stdout.splitlines()
if len(out) != 1:
log.error("unexpected output"+_make_subprocess_error_string(res))
saskey = out[0].decode('utf-8')
return saskey