prefect-client 2.14.9__py3-none-any.whl → 2.14.10__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- prefect/__init__.py +4 -1
- prefect/client/orchestration.py +1 -2
- prefect/deployments/runner.py +5 -1
- prefect/engine.py +176 -11
- prefect/events/clients.py +216 -5
- prefect/events/filters.py +214 -0
- prefect/exceptions.py +4 -0
- prefect/infrastructure/base.py +106 -1
- prefect/infrastructure/container.py +52 -0
- prefect/infrastructure/process.py +38 -0
- prefect/infrastructure/provisioners/__init__.py +2 -0
- prefect/infrastructure/provisioners/cloud_run.py +7 -1
- prefect/infrastructure/provisioners/container_instance.py +797 -0
- prefect/states.py +26 -3
- prefect/utilities/services.py +10 -0
- prefect/workers/__init__.py +1 -0
- prefect/workers/block.py +226 -0
- prefect/workers/utilities.py +2 -1
- {prefect_client-2.14.9.dist-info → prefect_client-2.14.10.dist-info}/METADATA +2 -1
- {prefect_client-2.14.9.dist-info → prefect_client-2.14.10.dist-info}/RECORD +23 -20
- {prefect_client-2.14.9.dist-info → prefect_client-2.14.10.dist-info}/LICENSE +0 -0
- {prefect_client-2.14.9.dist-info → prefect_client-2.14.10.dist-info}/WHEEL +0 -0
- {prefect_client-2.14.9.dist-info → prefect_client-2.14.10.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,797 @@
|
|
1
|
+
"""
|
2
|
+
This module defines the ContainerInstancePushProvisioner class, which is responsible for provisioning
|
3
|
+
infrastructure using Azure Container Instances for Prefect work pools.
|
4
|
+
|
5
|
+
The ContainerInstancePushProvisioner class provides methods for provisioning infrastructure and
|
6
|
+
interacting with Azure Container Instances.
|
7
|
+
|
8
|
+
Classes:
|
9
|
+
AzureCLI: A class to handle Azure CLI commands.
|
10
|
+
ContainerInstancePushProvisioner: A class for provisioning infrastructure using Azure Container Instances.
|
11
|
+
|
12
|
+
"""
|
13
|
+
import json
|
14
|
+
import shlex
|
15
|
+
import subprocess
|
16
|
+
from copy import deepcopy
|
17
|
+
from textwrap import dedent
|
18
|
+
from typing import Any, Dict, Optional
|
19
|
+
from uuid import UUID
|
20
|
+
|
21
|
+
from anyio import run_process
|
22
|
+
from rich.console import Console
|
23
|
+
from rich.panel import Panel
|
24
|
+
from rich.progress import Progress, SpinnerColumn, TextColumn
|
25
|
+
from rich.prompt import Confirm
|
26
|
+
|
27
|
+
from prefect.cli._prompts import prompt_select_from_table
|
28
|
+
from prefect.client.orchestration import PrefectClient
|
29
|
+
from prefect.client.schemas.actions import BlockDocumentCreate
|
30
|
+
from prefect.client.utilities import inject_client
|
31
|
+
from prefect.exceptions import ObjectAlreadyExists, ObjectNotFound
|
32
|
+
|
33
|
+
|
34
|
+
class AzureCLI:
|
35
|
+
"""
|
36
|
+
A class for executing Azure CLI commands and handling their output.
|
37
|
+
|
38
|
+
Args:
|
39
|
+
console (Console): A Rich console object for displaying messages.
|
40
|
+
|
41
|
+
Methods:
|
42
|
+
run_command(command, success_message=None, failure_message=None, ignore_if_exists=False, return_json=False)
|
43
|
+
Execute an Azure CLI command.
|
44
|
+
"""
|
45
|
+
|
46
|
+
def __init__(self, console: Console):
|
47
|
+
self._console = console
|
48
|
+
|
49
|
+
async def run_command(
|
50
|
+
self,
|
51
|
+
command: str,
|
52
|
+
success_message: Optional[str] = None,
|
53
|
+
failure_message: Optional[str] = None,
|
54
|
+
ignore_if_exists: bool = False,
|
55
|
+
return_json: bool = False,
|
56
|
+
):
|
57
|
+
"""
|
58
|
+
Runs an Azure CLI command and processes the output.
|
59
|
+
|
60
|
+
Args:
|
61
|
+
command (str): The Azure CLI command to execute.
|
62
|
+
success_message (str, optional): Message to print on success.
|
63
|
+
failure_message (str, optional): Message to print on failure.
|
64
|
+
ignore_if_exists (bool): Whether to ignore errors if a resource already exists.
|
65
|
+
return_json (bool): Whether to return the output as JSON.
|
66
|
+
|
67
|
+
Returns:
|
68
|
+
tuple: A tuple with two elements:
|
69
|
+
- str: Status, either 'created', 'exists', or 'error'.
|
70
|
+
- str or dict or None: The command output or None if an error occurs (depends on return_json).
|
71
|
+
|
72
|
+
Raises:
|
73
|
+
subprocess.CalledProcessError: If the command execution fails.
|
74
|
+
json.JSONDecodeError: If output cannot be decoded as JSON when return_json is True.
|
75
|
+
"""
|
76
|
+
try:
|
77
|
+
result = await run_process(shlex.split(command), check=False)
|
78
|
+
output = result.stdout.decode("utf-8").strip()
|
79
|
+
|
80
|
+
if result.returncode != 0:
|
81
|
+
error_message = result.stderr.decode("utf-8")
|
82
|
+
if ignore_if_exists and "already exists" in error_message:
|
83
|
+
if success_message:
|
84
|
+
self._console.print(
|
85
|
+
f"{success_message} (already exists)", style="yellow"
|
86
|
+
)
|
87
|
+
return ("exists", None)
|
88
|
+
else:
|
89
|
+
if failure_message:
|
90
|
+
self._console.print(
|
91
|
+
f"{failure_message}: {result.stderr.decode('utf-8')}",
|
92
|
+
style="red",
|
93
|
+
)
|
94
|
+
raise subprocess.CalledProcessError(
|
95
|
+
result.returncode,
|
96
|
+
command,
|
97
|
+
output=result.stdout,
|
98
|
+
stderr=result.stderr,
|
99
|
+
)
|
100
|
+
if success_message:
|
101
|
+
self._console.print(success_message, style="green")
|
102
|
+
|
103
|
+
if return_json:
|
104
|
+
try:
|
105
|
+
return json.loads(output)
|
106
|
+
except json.JSONDecodeError as e:
|
107
|
+
self._console.print(f"Failed to decode JSON: {e}", style="red")
|
108
|
+
raise e
|
109
|
+
|
110
|
+
return output
|
111
|
+
|
112
|
+
except subprocess.CalledProcessError as e:
|
113
|
+
self._console.print(f"Command execution failed: {e}", style="red")
|
114
|
+
return
|
115
|
+
|
116
|
+
|
117
|
+
class ContainerInstancePushProvisioner:
|
118
|
+
"""
|
119
|
+
A class responsible for provisioning Azure resources and setting up a push work pool.
|
120
|
+
|
121
|
+
Attributes:
|
122
|
+
_console (Console): A Rich console object for displaying messages and progress.
|
123
|
+
_subscription_id (str): Azure subscription ID.
|
124
|
+
_subscription_name (str): Azure subscription name.
|
125
|
+
_resource_group (str): Azure resource group name.
|
126
|
+
_location (str): Azure resource location.
|
127
|
+
_container_image (str): Docker image for the container instance.
|
128
|
+
azure_cli (AzureCLI): An instance of AzureCLI for running Azure commands.
|
129
|
+
|
130
|
+
Methods:
|
131
|
+
set_location: Sets the location for Azure resource deployment.
|
132
|
+
_verify_az_ready: Verifies if Azure CLI is ready and available.
|
133
|
+
_select_subscription: Selects an Azure subscription interactively or automatically.
|
134
|
+
_create_resource_group: Creates a resource group in Azure.
|
135
|
+
_create_app_registration: Creates an app registration in Azure AD.
|
136
|
+
_generate_secret_for_app: Generates a secret for the app registration.
|
137
|
+
_get_service_principal_object_id: Retrieves the object ID of the service principal associated with the app registration.
|
138
|
+
_assign_contributor_role: Assigns the Contributor role to the service account.
|
139
|
+
_create_container_instance: Creates an Azure Container Instance.
|
140
|
+
_create_aci_credentials_block: Creates an Azure Container Instance credentials block.
|
141
|
+
provision: Orchestrates the provisioning of Azure resources and setup for the push work pool.
|
142
|
+
"""
|
143
|
+
|
144
|
+
DEFAULT_LOCATION = "eastus"
|
145
|
+
RESOURCE_GROUP_NAME = "prefect-aci-push-pool-rg"
|
146
|
+
CONTAINER_IMAGE = "docker.io/prefecthq/prefect:2-latest"
|
147
|
+
APP_REGISTRATION_NAME = "prefect-aci-push-pool-app"
|
148
|
+
|
149
|
+
def __init__(self):
|
150
|
+
self._console = Console()
|
151
|
+
self._subscription_id = None
|
152
|
+
self._subscription_name = None
|
153
|
+
self._location = None
|
154
|
+
self.azure_cli = AzureCLI(self.console)
|
155
|
+
|
156
|
+
@property
|
157
|
+
def console(self) -> Console:
|
158
|
+
return self._console
|
159
|
+
|
160
|
+
@console.setter
|
161
|
+
def console(self, value: Console) -> None:
|
162
|
+
self._console = value
|
163
|
+
|
164
|
+
async def set_location(self):
|
165
|
+
"""
|
166
|
+
Set the Azure resource deployment location to the default or 'eastus' on failure.
|
167
|
+
|
168
|
+
Raises:
|
169
|
+
RuntimeError: If unable to execute the Azure CLI command.
|
170
|
+
"""
|
171
|
+
try:
|
172
|
+
command = (
|
173
|
+
'az account list-locations --query "[?isDefault].name" --output tsv'
|
174
|
+
)
|
175
|
+
output = await self.azure_cli.run_command(command)
|
176
|
+
self._location = output if output else self.DEFAULT_LOCATION
|
177
|
+
except subprocess.CalledProcessError as e:
|
178
|
+
raise RuntimeError("Failed to get default location.") from e
|
179
|
+
|
180
|
+
async def _verify_az_ready(self) -> None:
|
181
|
+
"""
|
182
|
+
Verifies if Azure CLI is installed and ready to use.
|
183
|
+
|
184
|
+
Raises:
|
185
|
+
RuntimeError: If Azure CLI is not installed.
|
186
|
+
subprocess.CalledProcessError: If the Azure CLI command execution fails.
|
187
|
+
"""
|
188
|
+
try:
|
189
|
+
await self.azure_cli.run_command("az --version", ignore_if_exists=True)
|
190
|
+
|
191
|
+
except subprocess.CalledProcessError as e:
|
192
|
+
raise RuntimeError(
|
193
|
+
"Azure CLI is not installed. Please see"
|
194
|
+
" https://docs.microsoft.com/en-us/cli/azure/install-azure-cli"
|
195
|
+
) from e
|
196
|
+
|
197
|
+
accounts = await self.azure_cli.run_command(
|
198
|
+
"az account list --output json",
|
199
|
+
return_json=True,
|
200
|
+
)
|
201
|
+
if not accounts:
|
202
|
+
raise RuntimeError(
|
203
|
+
"No Azure accounts found. Please run `az login` to log in to Azure."
|
204
|
+
)
|
205
|
+
|
206
|
+
async def _select_subscription(self) -> str:
|
207
|
+
"""
|
208
|
+
Selects an Azure subscription for use. If running in interactive mode,
|
209
|
+
the user will be prompted to select a subscription. Otherwise, the current subscription is used.
|
210
|
+
|
211
|
+
Returns:
|
212
|
+
str: The ID of the selected Azure subscription.
|
213
|
+
|
214
|
+
Raises:
|
215
|
+
RuntimeError: If no Azure subscriptions are found or the Azure CLI command execution fails.
|
216
|
+
"""
|
217
|
+
if self._console.is_interactive:
|
218
|
+
with Progress(
|
219
|
+
SpinnerColumn(),
|
220
|
+
TextColumn("Fetching Azure subscriptions..."),
|
221
|
+
transient=True,
|
222
|
+
console=self._console,
|
223
|
+
) as progress:
|
224
|
+
list_projects_task = progress.add_task(
|
225
|
+
"Fetching subscriptions...", total=1
|
226
|
+
)
|
227
|
+
subscriptions_list = await self.azure_cli.run_command(
|
228
|
+
"az account list --output json",
|
229
|
+
failure_message=(
|
230
|
+
"No Azure subscriptions found. Please create an Azure subscription"
|
231
|
+
" and try again."
|
232
|
+
),
|
233
|
+
ignore_if_exists=True,
|
234
|
+
return_json=True,
|
235
|
+
)
|
236
|
+
progress.update(list_projects_task, completed=1)
|
237
|
+
if subscriptions_list:
|
238
|
+
selected_subscription = prompt_select_from_table(
|
239
|
+
self._console,
|
240
|
+
"Please select which Azure subscription to use:",
|
241
|
+
[
|
242
|
+
{"header": "Name", "key": "name"},
|
243
|
+
{"header": "Subscription ID", "key": "id"},
|
244
|
+
],
|
245
|
+
subscriptions_list,
|
246
|
+
)
|
247
|
+
self._subscription_id = selected_subscription["id"]
|
248
|
+
self._subscription_name = selected_subscription["name"]
|
249
|
+
|
250
|
+
else:
|
251
|
+
subscriptions_list = await self.azure_cli.run_command(
|
252
|
+
"az account list --output json",
|
253
|
+
failure_message=(
|
254
|
+
"No Azure subscriptions found. Please create an Azure subscription"
|
255
|
+
" and try again."
|
256
|
+
),
|
257
|
+
ignore_if_exists=True,
|
258
|
+
return_json=True,
|
259
|
+
)
|
260
|
+
if subscriptions_list:
|
261
|
+
self._subscription_id = subscriptions_list[0]["id"]
|
262
|
+
self._subscription_name = subscriptions_list[0]["name"]
|
263
|
+
else:
|
264
|
+
raise RuntimeError(
|
265
|
+
"No Azure subscriptions found. Please create an Azure subscription"
|
266
|
+
" and try again."
|
267
|
+
)
|
268
|
+
|
269
|
+
async def _create_resource_group(self):
|
270
|
+
"""
|
271
|
+
Creates a resource group in Azure using predefined names and locations.
|
272
|
+
|
273
|
+
Raises:
|
274
|
+
subprocess.CalledProcessError: If the Azure CLI command execution fails.
|
275
|
+
"""
|
276
|
+
check_exists_command = (
|
277
|
+
f"az group exists --name {self.RESOURCE_GROUP_NAME} --subscription"
|
278
|
+
f" {self._subscription_id}"
|
279
|
+
)
|
280
|
+
exists_result = await self.azure_cli.run_command(
|
281
|
+
check_exists_command, return_json=True
|
282
|
+
)
|
283
|
+
if exists_result is True:
|
284
|
+
self._console.print(
|
285
|
+
(
|
286
|
+
f"Resource group '{self.RESOURCE_GROUP_NAME}' already exists in"
|
287
|
+
f" subscription {self._subscription_name}."
|
288
|
+
),
|
289
|
+
style="yellow",
|
290
|
+
)
|
291
|
+
return
|
292
|
+
|
293
|
+
resource_group_command = (
|
294
|
+
f"az group create --name '{self.RESOURCE_GROUP_NAME}' --location"
|
295
|
+
f" '{self._location}' --subscription '{self._subscription_id}'"
|
296
|
+
)
|
297
|
+
await self.azure_cli.run_command(
|
298
|
+
resource_group_command,
|
299
|
+
success_message=(
|
300
|
+
f"Resource group '{self.RESOURCE_GROUP_NAME}' created successfully"
|
301
|
+
),
|
302
|
+
failure_message=(
|
303
|
+
f"Failed to create resource group '{self.RESOURCE_GROUP_NAME}' in"
|
304
|
+
f" subscription '{self._subscription_name}'"
|
305
|
+
),
|
306
|
+
ignore_if_exists=True,
|
307
|
+
)
|
308
|
+
|
309
|
+
async def _create_app_registration(self) -> str:
|
310
|
+
"""
|
311
|
+
Creates an app registration in Azure Active Directory.
|
312
|
+
|
313
|
+
Returns:
|
314
|
+
str: The client ID of the newly created app registration.
|
315
|
+
|
316
|
+
Raises:
|
317
|
+
subprocess.CalledProcessError: If the Azure CLI command execution fails.
|
318
|
+
"""
|
319
|
+
# Check if the app registration already exists
|
320
|
+
check_exists_command = (
|
321
|
+
f"az ad app list --display-name {self.APP_REGISTRATION_NAME} --output json"
|
322
|
+
)
|
323
|
+
app_registrations = await self.azure_cli.run_command(
|
324
|
+
check_exists_command,
|
325
|
+
)
|
326
|
+
if app_registrations:
|
327
|
+
if isinstance(app_registrations, str):
|
328
|
+
app_registrations = json.loads(app_registrations)
|
329
|
+
|
330
|
+
existing_app_registration = next(
|
331
|
+
(
|
332
|
+
app
|
333
|
+
for app in app_registrations
|
334
|
+
if app["displayName"] == self.APP_REGISTRATION_NAME
|
335
|
+
),
|
336
|
+
None,
|
337
|
+
)
|
338
|
+
if existing_app_registration:
|
339
|
+
self._console.print(
|
340
|
+
f"App registration '{self.APP_REGISTRATION_NAME}' already exists.",
|
341
|
+
style="yellow",
|
342
|
+
)
|
343
|
+
return existing_app_registration["appId"]
|
344
|
+
|
345
|
+
app_registration_command = (
|
346
|
+
f"az ad app create --display-name {self.APP_REGISTRATION_NAME} "
|
347
|
+
"--output json"
|
348
|
+
)
|
349
|
+
app_registration = await self.azure_cli.run_command(
|
350
|
+
app_registration_command,
|
351
|
+
success_message=(
|
352
|
+
f"App registration '{self.APP_REGISTRATION_NAME}' created successfully"
|
353
|
+
),
|
354
|
+
failure_message=(
|
355
|
+
"Failed to create app registration with name"
|
356
|
+
f" '{self.APP_REGISTRATION_NAME}'"
|
357
|
+
),
|
358
|
+
ignore_if_exists=True,
|
359
|
+
)
|
360
|
+
if app_registration:
|
361
|
+
if isinstance(app_registration, str):
|
362
|
+
app_registration = json.loads(app_registration)
|
363
|
+
return app_registration["appId"]
|
364
|
+
|
365
|
+
else:
|
366
|
+
raise RuntimeError("Failed to create app registration.")
|
367
|
+
|
368
|
+
async def _generate_secret_for_app(self, app_id: str) -> tuple:
|
369
|
+
"""
|
370
|
+
Generates a secret for the app registration.
|
371
|
+
|
372
|
+
Args:
|
373
|
+
app_id (str): The client ID of the app registration for which to generate the secret.
|
374
|
+
|
375
|
+
Returns:
|
376
|
+
tuple: A tuple containing the tenant ID and the generated secret.
|
377
|
+
|
378
|
+
Raises:
|
379
|
+
subprocess.CalledProcessError: If the Azure CLI command execution fails.
|
380
|
+
"""
|
381
|
+
secret_command = (
|
382
|
+
f"az ad app credential reset --id {app_id} --append --output json"
|
383
|
+
)
|
384
|
+
app_secret = await self.azure_cli.run_command(
|
385
|
+
secret_command,
|
386
|
+
success_message=(
|
387
|
+
f"Secret generated for app registration with client ID '{app_id}'"
|
388
|
+
),
|
389
|
+
failure_message=(
|
390
|
+
"Failed to generate secret for app registration with client ID"
|
391
|
+
f" '{app_id}'. If you have already generated 2 secrets for this app"
|
392
|
+
" registration, please delete one from the `prefect-aci-push-pool-app`"
|
393
|
+
" resource and try again."
|
394
|
+
),
|
395
|
+
ignore_if_exists=True,
|
396
|
+
return_json=True,
|
397
|
+
)
|
398
|
+
|
399
|
+
try:
|
400
|
+
return app_secret["tenant"], app_secret["password"]
|
401
|
+
except Exception as e:
|
402
|
+
raise RuntimeError(
|
403
|
+
"Failed to generate a new secret for the app registration."
|
404
|
+
) from e
|
405
|
+
|
406
|
+
async def _get_or_create_service_principal_object_id(self, app_id: str):
|
407
|
+
"""
|
408
|
+
Retrieves or creates a service principal for the given app registration client ID.
|
409
|
+
|
410
|
+
Args:
|
411
|
+
app_id (str): The client ID of the app registration.
|
412
|
+
|
413
|
+
Returns:
|
414
|
+
str: The object ID of the service principal.
|
415
|
+
"""
|
416
|
+
# Try to retrieve the existing service principal
|
417
|
+
command_get_sp = (
|
418
|
+
f"az ad sp list --all --query \"[?appId=='{app_id}']\" --output json"
|
419
|
+
)
|
420
|
+
service_principal = await self.azure_cli.run_command(
|
421
|
+
command_get_sp,
|
422
|
+
return_json=True,
|
423
|
+
)
|
424
|
+
|
425
|
+
if service_principal:
|
426
|
+
return service_principal[0]
|
427
|
+
|
428
|
+
# Service principal does not exist, create it
|
429
|
+
command_create_sp = f"az ad sp create --id {app_id}"
|
430
|
+
await self.azure_cli.run_command(
|
431
|
+
command_create_sp,
|
432
|
+
success_message=f"Service principal created for app ID '{app_id}'",
|
433
|
+
failure_message=f"Failed to create service principal for app ID '{app_id}'",
|
434
|
+
)
|
435
|
+
|
436
|
+
# Retrieve the object ID of the newly created service principal
|
437
|
+
new_service_principal = await self.azure_cli.run_command(
|
438
|
+
command_get_sp,
|
439
|
+
failure_message=(
|
440
|
+
f"Failed to retrieve new service principal for app ID {app_id}"
|
441
|
+
),
|
442
|
+
return_json=True,
|
443
|
+
)
|
444
|
+
|
445
|
+
if new_service_principal:
|
446
|
+
return new_service_principal[0]
|
447
|
+
else:
|
448
|
+
raise Exception(
|
449
|
+
f"Failed to retrieve new service principal for app ID {app_id}"
|
450
|
+
)
|
451
|
+
|
452
|
+
async def _assign_contributor_role(self, app_id: str) -> None:
|
453
|
+
"""
|
454
|
+
Assigns the 'Contributor' role to the service principal associated with a given app ID.
|
455
|
+
|
456
|
+
Args:
|
457
|
+
app_id (str): The client ID of the app registration.
|
458
|
+
"""
|
459
|
+
service_principal = await self._get_or_create_service_principal_object_id(
|
460
|
+
app_id
|
461
|
+
)
|
462
|
+
|
463
|
+
service_principal_id = service_principal["id"]
|
464
|
+
|
465
|
+
if service_principal_id:
|
466
|
+
role = "Contributor"
|
467
|
+
scope = f"/subscriptions/{self._subscription_id}/resourceGroups/{self.RESOURCE_GROUP_NAME}"
|
468
|
+
|
469
|
+
# Check if the role is already assigned
|
470
|
+
check_role_command = (
|
471
|
+
f"az role assignment list --assignee {service_principal_id} --role"
|
472
|
+
f" {role} --scope {scope} --output json"
|
473
|
+
)
|
474
|
+
role_assignments = await self.azure_cli.run_command(
|
475
|
+
check_role_command, return_json=True
|
476
|
+
)
|
477
|
+
if any(
|
478
|
+
ra
|
479
|
+
for ra in role_assignments
|
480
|
+
if ra["roleDefinitionName"] == role and ra["scope"] == scope
|
481
|
+
):
|
482
|
+
self._console.print(
|
483
|
+
(
|
484
|
+
f"Service principal with object ID '{service_principal_id}'"
|
485
|
+
f" already has the '{role}' role assigned in '{scope}'."
|
486
|
+
),
|
487
|
+
style="yellow",
|
488
|
+
)
|
489
|
+
return
|
490
|
+
|
491
|
+
assign_command = (
|
492
|
+
f"az role assignment create --role {role} --assignee-object-id"
|
493
|
+
f" {service_principal_id} --scope {scope}"
|
494
|
+
)
|
495
|
+
await self.azure_cli.run_command(
|
496
|
+
assign_command,
|
497
|
+
success_message=(
|
498
|
+
"Contributor role assigned to service principal with object ID"
|
499
|
+
f" '{service_principal_id}'"
|
500
|
+
),
|
501
|
+
failure_message=(
|
502
|
+
"Failed to assign Contributor role to service principal with"
|
503
|
+
f" object ID '{service_principal_id}'"
|
504
|
+
),
|
505
|
+
ignore_if_exists=True,
|
506
|
+
)
|
507
|
+
|
508
|
+
async def _create_container_instance(self) -> None:
|
509
|
+
"""
|
510
|
+
Creates an Azure Container Instance using predefined settings.
|
511
|
+
|
512
|
+
Raises:
|
513
|
+
subprocess.CalledProcessError: If the Azure CLI command execution fails.
|
514
|
+
"""
|
515
|
+
container_name = "prefect-aci-push-pool-container"
|
516
|
+
|
517
|
+
check_exists_command = (
|
518
|
+
"az container list --resource-group"
|
519
|
+
f" {self.RESOURCE_GROUP_NAME} --subscription"
|
520
|
+
f" {self._subscription_id} --query \"[?name=='{container_name}']\" --output"
|
521
|
+
" json"
|
522
|
+
)
|
523
|
+
|
524
|
+
result = await self.azure_cli.run_command(
|
525
|
+
check_exists_command,
|
526
|
+
return_json=True,
|
527
|
+
)
|
528
|
+
|
529
|
+
if result:
|
530
|
+
self._console.print(
|
531
|
+
(
|
532
|
+
f"Container instance '{container_name}' already exists in"
|
533
|
+
f" subscription '{self._subscription_name}' in location"
|
534
|
+
f" '{self._location}'."
|
535
|
+
),
|
536
|
+
style="yellow",
|
537
|
+
)
|
538
|
+
return
|
539
|
+
|
540
|
+
create_command = (
|
541
|
+
f"az container create --name {container_name} "
|
542
|
+
f"--resource-group {self.RESOURCE_GROUP_NAME} "
|
543
|
+
"--image docker.io/prefecthq/prefect:2-latest "
|
544
|
+
f"--location {self._location} --subscription {self._subscription_id} "
|
545
|
+
"--restart-policy OnFailure --output json"
|
546
|
+
)
|
547
|
+
await self.azure_cli.run_command(
|
548
|
+
create_command,
|
549
|
+
success_message=(
|
550
|
+
f"Container instance '{container_name}' created successfully in"
|
551
|
+
f" resource group '{self.RESOURCE_GROUP_NAME}' in location"
|
552
|
+
f" '{self._location}' in subscription '{self._subscription_name}'"
|
553
|
+
),
|
554
|
+
failure_message=(
|
555
|
+
f"Failed to create container instance '{container_name}' in resource"
|
556
|
+
f" group '{self.RESOURCE_GROUP_NAME}' in location '{self._location}' in"
|
557
|
+
f" subscription '{self._subscription_name}'"
|
558
|
+
),
|
559
|
+
ignore_if_exists=True,
|
560
|
+
)
|
561
|
+
return
|
562
|
+
|
563
|
+
async def _create_aci_credentials_block(
|
564
|
+
self,
|
565
|
+
work_pool_name: str,
|
566
|
+
client_id: str,
|
567
|
+
tenant_id: str,
|
568
|
+
client_secret: str,
|
569
|
+
client: PrefectClient,
|
570
|
+
) -> UUID:
|
571
|
+
"""
|
572
|
+
Creates a credentials block for Azure Container Instance.
|
573
|
+
|
574
|
+
Args:
|
575
|
+
work_pool_name (str): The name of the work pool.
|
576
|
+
client_id (str): The client ID obtained from app registration.
|
577
|
+
tenant_id (str): The tenant ID obtained from the secret generation.
|
578
|
+
client_secret (str): The client secret obtained from the secret generation.
|
579
|
+
client (PrefectClient): An instance of PrefectClient.
|
580
|
+
|
581
|
+
Returns:
|
582
|
+
UUID: The ID of the created credentials block.
|
583
|
+
|
584
|
+
Raises:
|
585
|
+
ObjectAlreadyExists: If a credentials block with the same name already exists.
|
586
|
+
"""
|
587
|
+
credentials_block_name = f"{work_pool_name}-push-pool-credentials"
|
588
|
+
credentials_block_type = await client.read_block_type_by_slug(
|
589
|
+
"azure-container-instance-credentials"
|
590
|
+
)
|
591
|
+
|
592
|
+
credentials_block_schema = (
|
593
|
+
await client.get_most_recent_block_schema_for_block_type(
|
594
|
+
block_type_id=credentials_block_type.id
|
595
|
+
)
|
596
|
+
)
|
597
|
+
|
598
|
+
try:
|
599
|
+
block_doc = await client.create_block_document(
|
600
|
+
block_document=BlockDocumentCreate(
|
601
|
+
name=credentials_block_name,
|
602
|
+
data={
|
603
|
+
"client_id": client_id,
|
604
|
+
"tenant_id": tenant_id,
|
605
|
+
"client_secret": client_secret,
|
606
|
+
},
|
607
|
+
block_type_id=credentials_block_type.id,
|
608
|
+
block_schema_id=credentials_block_schema.id,
|
609
|
+
)
|
610
|
+
)
|
611
|
+
|
612
|
+
self._console.print(
|
613
|
+
(
|
614
|
+
f"ACI credentials block '{credentials_block_name}' created in"
|
615
|
+
" Prefect Cloud"
|
616
|
+
),
|
617
|
+
style="green",
|
618
|
+
)
|
619
|
+
return block_doc.id
|
620
|
+
|
621
|
+
except ObjectAlreadyExists:
|
622
|
+
self._console.print(
|
623
|
+
f"ACI credentials block '{credentials_block_name}' already exists",
|
624
|
+
style="yellow",
|
625
|
+
)
|
626
|
+
block_doc = await client.read_block_document_by_name(
|
627
|
+
name=credentials_block_name,
|
628
|
+
block_type_slug="azure-container-instance-credentials",
|
629
|
+
)
|
630
|
+
return block_doc.id
|
631
|
+
|
632
|
+
except Exception as e:
|
633
|
+
self._console.print(
|
634
|
+
f"Failed to create ACI credentials block: {e}",
|
635
|
+
style="red",
|
636
|
+
)
|
637
|
+
raise e
|
638
|
+
|
639
|
+
async def _aci_credentials_block_exists(
|
640
|
+
self, block_name: str, client: PrefectClient
|
641
|
+
) -> bool:
|
642
|
+
"""
|
643
|
+
Checks if an ACI credentials block with the given name already exists.
|
644
|
+
|
645
|
+
Args:
|
646
|
+
block_name (str): The name of the ACI credentials block.
|
647
|
+
client (PrefectClient): An instance of PrefectClient.
|
648
|
+
|
649
|
+
Returns:
|
650
|
+
bool: True if the credentials block exists, False otherwise.
|
651
|
+
"""
|
652
|
+
try:
|
653
|
+
await client.read_block_document_by_name(
|
654
|
+
name=block_name,
|
655
|
+
block_type_slug="azure-container-instance-credentials",
|
656
|
+
)
|
657
|
+
return True
|
658
|
+
except ObjectNotFound:
|
659
|
+
return False
|
660
|
+
|
661
|
+
@inject_client
|
662
|
+
async def provision(
|
663
|
+
self,
|
664
|
+
work_pool_name: str,
|
665
|
+
base_job_template: Dict[str, Any],
|
666
|
+
client: Optional[PrefectClient] = None,
|
667
|
+
) -> Dict[str, Any]:
|
668
|
+
"""
|
669
|
+
Orchestrates the provisioning of Azure resources and setup for the push work pool.
|
670
|
+
|
671
|
+
Args:
|
672
|
+
work_pool_name (str): The name of the work pool.
|
673
|
+
base_job_template (Dict[str, Any]): The base template for job creation.
|
674
|
+
client (Optional[PrefectClient]): An instance of PrefectClient. If None, it will be injected.
|
675
|
+
|
676
|
+
Returns:
|
677
|
+
Dict[str, Any]: The updated job template with necessary references and configurations.
|
678
|
+
|
679
|
+
Raises:
|
680
|
+
RuntimeError: If client injection fails or the Azure CLI command execution fails.
|
681
|
+
"""
|
682
|
+
if not client:
|
683
|
+
self._console.print(
|
684
|
+
"Client injection failed, cannot proceed with provisioning.",
|
685
|
+
style="red",
|
686
|
+
)
|
687
|
+
return base_job_template
|
688
|
+
|
689
|
+
await self._verify_az_ready()
|
690
|
+
await self._select_subscription()
|
691
|
+
await self.set_location()
|
692
|
+
|
693
|
+
table = Panel(
|
694
|
+
dedent(
|
695
|
+
f"""\
|
696
|
+
Provisioning infrastructure for your work pool [blue]{work_pool_name}[/] will require:
|
697
|
+
|
698
|
+
Updates in subscription [blue]{self._subscription_name}[/]
|
699
|
+
|
700
|
+
- Create a resource group in location [blue]{self._location}[/]
|
701
|
+
- Create an app registration in Azure AD [blue]{self.APP_REGISTRATION_NAME}[/]
|
702
|
+
- Create/use a service principal for app registration
|
703
|
+
- Generate a secret for app registration
|
704
|
+
- Assign Contributor role to service account
|
705
|
+
- Create Azure Container Instance 'aci-push-pool-container' in resource group [blue]{self.RESOURCE_GROUP_NAME}[/]
|
706
|
+
|
707
|
+
Updates in Prefect workspace
|
708
|
+
|
709
|
+
- Create Azure Container Instance credentials block [blue]aci-push-pool-credentials[/]
|
710
|
+
"""
|
711
|
+
),
|
712
|
+
expand=False,
|
713
|
+
)
|
714
|
+
self._console.print(table)
|
715
|
+
if self._console.is_interactive:
|
716
|
+
if not Confirm.ask(
|
717
|
+
"Proceed with infrastructure provisioning?", console=self._console
|
718
|
+
):
|
719
|
+
return base_job_template
|
720
|
+
|
721
|
+
credentials_block_exists = await self._aci_credentials_block_exists(
|
722
|
+
block_name=f"{work_pool_name}-push-pool-credentials", client=client
|
723
|
+
)
|
724
|
+
|
725
|
+
if not credentials_block_exists:
|
726
|
+
total_tasks = 6
|
727
|
+
else:
|
728
|
+
total_tasks = 5
|
729
|
+
|
730
|
+
with Progress(console=self._console) as progress:
|
731
|
+
task = progress.add_task(
|
732
|
+
"Provisioning infrastructure...", total=total_tasks
|
733
|
+
)
|
734
|
+
progress.console.print("Creating resource group..")
|
735
|
+
await self._create_resource_group()
|
736
|
+
progress.advance(task)
|
737
|
+
|
738
|
+
progress.console.print("Creating app registration..")
|
739
|
+
client_id = await self._create_app_registration()
|
740
|
+
progress.advance(task)
|
741
|
+
|
742
|
+
credentials_block_exists = await self._aci_credentials_block_exists(
|
743
|
+
block_name=f"{work_pool_name}-push-pool-credentials", client=client
|
744
|
+
)
|
745
|
+
|
746
|
+
if not credentials_block_exists:
|
747
|
+
progress.console.print("Generating secret for app registration")
|
748
|
+
tenant_id, client_secret = await self._generate_secret_for_app(
|
749
|
+
app_id=client_id,
|
750
|
+
)
|
751
|
+
progress.advance(task)
|
752
|
+
|
753
|
+
progress.console.print("Creating ACI credentials block..")
|
754
|
+
block_doc_id = await self._create_aci_credentials_block(
|
755
|
+
work_pool_name, client_id, tenant_id, client_secret, client
|
756
|
+
)
|
757
|
+
progress.advance(task)
|
758
|
+
else:
|
759
|
+
progress.console.print(
|
760
|
+
"ACI credentials block already exists.", style="yellow"
|
761
|
+
)
|
762
|
+
block_doc = await client.read_block_document_by_name(
|
763
|
+
name=f"{work_pool_name}-push-pool-credentials",
|
764
|
+
block_type_slug="azure-container-instance-credentials",
|
765
|
+
)
|
766
|
+
block_doc_id = block_doc.id
|
767
|
+
progress.advance(task)
|
768
|
+
|
769
|
+
progress.console.print("Assigning Contributor role to service account...")
|
770
|
+
await self._assign_contributor_role(app_id=client_id)
|
771
|
+
progress.advance(task)
|
772
|
+
|
773
|
+
progress.console.print("Creating Azure Container Instance..")
|
774
|
+
await self._create_container_instance()
|
775
|
+
progress.advance(task)
|
776
|
+
|
777
|
+
base_job_template_copy = deepcopy(base_job_template)
|
778
|
+
base_job_template_copy["variables"]["properties"]["aci_credentials"][
|
779
|
+
"default"
|
780
|
+
] = {"$ref": {"block_document_id": str(block_doc_id)}}
|
781
|
+
|
782
|
+
base_job_template_copy["variables"]["properties"]["resource_group_name"][
|
783
|
+
"default"
|
784
|
+
] = self.RESOURCE_GROUP_NAME
|
785
|
+
|
786
|
+
base_job_template_copy["variables"]["properties"]["subscription_id"][
|
787
|
+
"default"
|
788
|
+
] = self._subscription_id
|
789
|
+
|
790
|
+
self._console.print(
|
791
|
+
(
|
792
|
+
f"Infrastructure successfully provisioned for '{work_pool_name}' work"
|
793
|
+
" pool!"
|
794
|
+
),
|
795
|
+
style="green",
|
796
|
+
)
|
797
|
+
return base_job_template_copy
|