prefect-client 2.14.9__py3-none-any.whl → 2.14.11__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.
Files changed (38) hide show
  1. prefect/__init__.py +4 -1
  2. prefect/_internal/pydantic/v2_schema.py +9 -2
  3. prefect/client/orchestration.py +51 -4
  4. prefect/client/schemas/objects.py +16 -1
  5. prefect/deployments/runner.py +34 -3
  6. prefect/engine.py +302 -25
  7. prefect/events/clients.py +216 -5
  8. prefect/events/filters.py +214 -0
  9. prefect/exceptions.py +4 -0
  10. prefect/flows.py +16 -0
  11. prefect/infrastructure/base.py +106 -1
  12. prefect/infrastructure/container.py +52 -0
  13. prefect/infrastructure/kubernetes.py +64 -0
  14. prefect/infrastructure/process.py +38 -0
  15. prefect/infrastructure/provisioners/__init__.py +2 -0
  16. prefect/infrastructure/provisioners/cloud_run.py +206 -34
  17. prefect/infrastructure/provisioners/container_instance.py +1080 -0
  18. prefect/infrastructure/provisioners/ecs.py +483 -48
  19. prefect/input/__init__.py +11 -0
  20. prefect/input/actions.py +88 -0
  21. prefect/input/run_input.py +107 -0
  22. prefect/runner/runner.py +5 -0
  23. prefect/runner/server.py +92 -8
  24. prefect/runner/utils.py +92 -0
  25. prefect/settings.py +34 -9
  26. prefect/states.py +26 -3
  27. prefect/utilities/dockerutils.py +31 -0
  28. prefect/utilities/processutils.py +5 -2
  29. prefect/utilities/services.py +10 -0
  30. prefect/utilities/validation.py +63 -0
  31. prefect/workers/__init__.py +1 -0
  32. prefect/workers/block.py +226 -0
  33. prefect/workers/utilities.py +2 -2
  34. {prefect_client-2.14.9.dist-info → prefect_client-2.14.11.dist-info}/METADATA +2 -1
  35. {prefect_client-2.14.9.dist-info → prefect_client-2.14.11.dist-info}/RECORD +38 -30
  36. {prefect_client-2.14.9.dist-info → prefect_client-2.14.11.dist-info}/LICENSE +0 -0
  37. {prefect_client-2.14.9.dist-info → prefect_client-2.14.11.dist-info}/WHEEL +0 -0
  38. {prefect_client-2.14.9.dist-info → prefect_client-2.14.11.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1080 @@
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 random
15
+ import shlex
16
+ import string
17
+ import subprocess
18
+ import time
19
+ from copy import deepcopy
20
+ from textwrap import dedent
21
+ from typing import Any, Dict, Optional
22
+ from uuid import UUID
23
+
24
+ from anyio import run_process
25
+ from rich.console import Console
26
+ from rich.panel import Panel
27
+ from rich.progress import Progress, SpinnerColumn, TextColumn
28
+ from rich.prompt import Confirm
29
+ from rich.syntax import Syntax
30
+
31
+ from prefect.cli._prompts import prompt, prompt_select_from_table
32
+ from prefect.client.orchestration import PrefectClient
33
+ from prefect.client.schemas.actions import BlockDocumentCreate
34
+ from prefect.client.utilities import inject_client
35
+ from prefect.exceptions import ObjectAlreadyExists, ObjectNotFound
36
+ from prefect.settings import (
37
+ PREFECT_DEFAULT_DOCKER_BUILD_NAMESPACE,
38
+ update_current_profile,
39
+ )
40
+
41
+
42
+ class AzureCLI:
43
+ """
44
+ A class for executing Azure CLI commands and handling their output.
45
+
46
+ Args:
47
+ console (Console): A Rich console object for displaying messages.
48
+
49
+ Methods:
50
+ run_command(command, success_message=None, failure_message=None, ignore_if_exists=False, return_json=False)
51
+ Execute an Azure CLI command.
52
+ """
53
+
54
+ def __init__(self, console: Console):
55
+ self._console = console
56
+
57
+ async def run_command(
58
+ self,
59
+ command: str,
60
+ success_message: Optional[str] = None,
61
+ failure_message: Optional[str] = None,
62
+ ignore_if_exists: bool = False,
63
+ return_json: bool = False,
64
+ ):
65
+ """
66
+ Runs an Azure CLI command and processes the output.
67
+
68
+ Args:
69
+ command (str): The Azure CLI command to execute.
70
+ success_message (str, optional): Message to print on success.
71
+ failure_message (str, optional): Message to print on failure.
72
+ ignore_if_exists (bool): Whether to ignore errors if a resource already exists.
73
+ return_json (bool): Whether to return the output as JSON.
74
+
75
+ Returns:
76
+ tuple: A tuple with two elements:
77
+ - str: Status, either 'created', 'exists', or 'error'.
78
+ - str or dict or None: The command output or None if an error occurs (depends on return_json).
79
+
80
+ Raises:
81
+ subprocess.CalledProcessError: If the command execution fails.
82
+ json.JSONDecodeError: If output cannot be decoded as JSON when return_json is True.
83
+ """
84
+ try:
85
+ result = await run_process(shlex.split(command), check=False)
86
+ output = result.stdout.decode("utf-8").strip()
87
+
88
+ if result.returncode != 0:
89
+ error_message = result.stderr.decode("utf-8")
90
+ if ignore_if_exists and "already exists" in error_message:
91
+ if success_message:
92
+ self._console.print(
93
+ f"{success_message} (already exists)", style="yellow"
94
+ )
95
+ return ("exists", None)
96
+ else:
97
+ if failure_message:
98
+ self._console.print(
99
+ f"{failure_message}: {result.stderr.decode('utf-8')}",
100
+ style="red",
101
+ )
102
+ raise subprocess.CalledProcessError(
103
+ result.returncode,
104
+ command,
105
+ output=result.stdout,
106
+ stderr=result.stderr,
107
+ )
108
+ if success_message:
109
+ self._console.print(success_message, style="green")
110
+
111
+ if return_json:
112
+ try:
113
+ return json.loads(output)
114
+ except json.JSONDecodeError as e:
115
+ self._console.print(f"Failed to decode JSON: {e}", style="red")
116
+ raise e
117
+
118
+ return output
119
+
120
+ except subprocess.CalledProcessError as e:
121
+ self._console.print(f"Command execution failed: {e}", style="red")
122
+ return
123
+
124
+
125
+ class ContainerInstancePushProvisioner:
126
+ """
127
+ A class responsible for provisioning Azure resources and setting up a push work pool.
128
+
129
+ Attributes:
130
+ _console (Console): A Rich console object for displaying messages and progress.
131
+ _subscription_id (str): Azure subscription ID.
132
+ _subscription_name (str): Azure subscription name.
133
+ _resource_group (str): Azure resource group name.
134
+ _location (str): Azure resource location.
135
+ azure_cli (AzureCLI): An instance of AzureCLI for running Azure commands.
136
+
137
+ Methods:
138
+ set_location: Sets the location for Azure resource deployment.
139
+ _verify_az_ready: Verifies if Azure CLI is ready and available.
140
+ _select_subscription: Selects an Azure subscription interactively or automatically.
141
+ _create_resource_group: Creates a resource group in Azure.
142
+ _create_app_registration: Creates an app registration in Azure AD.
143
+ _generate_secret_for_app: Generates a secret for the app registration.
144
+ _get_service_principal_object_id: Retrieves the object ID of the service principal associated with the app registration.
145
+ _assign_contributor_role: Assigns the Contributor role to the service account.
146
+ _create_aci_credentials_block: Creates an Azure Container Instance credentials block.
147
+ provision: Orchestrates the provisioning of Azure resources and setup for the push work pool.
148
+ """
149
+
150
+ def __init__(self):
151
+ self._console = Console()
152
+ self._subscription_id = None
153
+ self._subscription_name = None
154
+ self._location = "eastus"
155
+ self._identity_name = "prefect-acr-identity"
156
+ self.azure_cli = AzureCLI(self.console)
157
+ self._credentials_block_name = None
158
+ self._resource_group_name = "prefect-aci-push-pool-rg"
159
+ self._app_registration_name = "prefect-aci-push-pool-app"
160
+ self._registry_name_prefix = "prefect"
161
+
162
+ @property
163
+ def console(self) -> Console:
164
+ return self._console
165
+
166
+ @console.setter
167
+ def console(self, value: Console) -> None:
168
+ self._console = value
169
+
170
+ async def set_location(self):
171
+ """
172
+ Set the Azure resource deployment location to the default or 'eastus' on failure.
173
+
174
+ Raises:
175
+ RuntimeError: If unable to execute the Azure CLI command.
176
+ """
177
+ try:
178
+ command = (
179
+ 'az account list-locations --query "[?isDefault].name" --output tsv'
180
+ )
181
+ output = await self.azure_cli.run_command(command)
182
+ if output:
183
+ self._location = output
184
+ except subprocess.CalledProcessError as e:
185
+ raise RuntimeError("Failed to get default location.") from e
186
+
187
+ async def _verify_az_ready(self) -> None:
188
+ """
189
+ Verifies if Azure CLI is installed and ready to use.
190
+
191
+ Raises:
192
+ RuntimeError: If Azure CLI is not installed.
193
+ subprocess.CalledProcessError: If the Azure CLI command execution fails.
194
+ """
195
+ try:
196
+ await self.azure_cli.run_command("az --version", ignore_if_exists=True)
197
+
198
+ except subprocess.CalledProcessError as e:
199
+ raise RuntimeError(
200
+ "Azure CLI is not installed. Please see"
201
+ " https://docs.microsoft.com/en-us/cli/azure/install-azure-cli"
202
+ ) from e
203
+
204
+ accounts = await self.azure_cli.run_command(
205
+ "az account list --output json",
206
+ return_json=True,
207
+ )
208
+ if not accounts:
209
+ raise RuntimeError(
210
+ "No Azure accounts found. Please run `az login` to log in to Azure."
211
+ )
212
+
213
+ async def _select_subscription(self) -> str:
214
+ """
215
+ Selects an Azure subscription for use. If running in interactive mode,
216
+ the user will be prompted to select a subscription. Otherwise, the current subscription is used.
217
+
218
+ Returns:
219
+ str: The ID of the selected Azure subscription.
220
+
221
+ Raises:
222
+ RuntimeError: If no Azure subscriptions are found or the Azure CLI command execution fails.
223
+ """
224
+ if self._console.is_interactive:
225
+ with Progress(
226
+ SpinnerColumn(),
227
+ TextColumn("Fetching Azure subscriptions..."),
228
+ transient=True,
229
+ console=self._console,
230
+ ) as progress:
231
+ list_projects_task = progress.add_task(
232
+ "Fetching subscriptions...", total=1
233
+ )
234
+ subscriptions_list = await self.azure_cli.run_command(
235
+ "az account list --output json",
236
+ failure_message=(
237
+ "No Azure subscriptions found. Please create an Azure subscription"
238
+ " and try again."
239
+ ),
240
+ ignore_if_exists=True,
241
+ return_json=True,
242
+ )
243
+ progress.update(list_projects_task, completed=1)
244
+ if subscriptions_list:
245
+ selected_subscription = prompt_select_from_table(
246
+ self._console,
247
+ "Please select which Azure subscription to use:",
248
+ [
249
+ {"header": "Name", "key": "name"},
250
+ {"header": "Subscription ID", "key": "id"},
251
+ ],
252
+ subscriptions_list,
253
+ )
254
+ self._subscription_id = selected_subscription["id"]
255
+ self._subscription_name = selected_subscription["name"]
256
+
257
+ else:
258
+ subscriptions_list = await self.azure_cli.run_command(
259
+ "az account list --output json",
260
+ failure_message=(
261
+ "No Azure subscriptions found. Please create an Azure subscription"
262
+ " and try again."
263
+ ),
264
+ ignore_if_exists=True,
265
+ return_json=True,
266
+ )
267
+ if subscriptions_list:
268
+ self._subscription_id = subscriptions_list[0]["id"]
269
+ self._subscription_name = subscriptions_list[0]["name"]
270
+ else:
271
+ raise RuntimeError(
272
+ "No Azure subscriptions found. Please create an Azure subscription"
273
+ " and try again."
274
+ )
275
+
276
+ async def _create_resource_group(self):
277
+ """
278
+ Creates a resource group in Azure using predefined names and locations.
279
+
280
+ Raises:
281
+ subprocess.CalledProcessError: If the Azure CLI command execution fails.
282
+ """
283
+ check_exists_command = (
284
+ f"az group exists --name {self._resource_group_name} --subscription"
285
+ f" {self._subscription_id}"
286
+ )
287
+ exists_result = await self.azure_cli.run_command(
288
+ check_exists_command, return_json=True
289
+ )
290
+ if exists_result is True:
291
+ self._console.print(
292
+ (
293
+ f"Resource group '{self._resource_group_name}' already exists in"
294
+ f" subscription {self._subscription_name}."
295
+ ),
296
+ style="yellow",
297
+ )
298
+ return
299
+
300
+ resource_group_command = (
301
+ f"az group create --name '{self._resource_group_name}' --location"
302
+ f" '{self._location}' --subscription '{self._subscription_id}'"
303
+ )
304
+ await self.azure_cli.run_command(
305
+ resource_group_command,
306
+ success_message=(
307
+ f"Resource group '{self._resource_group_name}' created successfully"
308
+ ),
309
+ failure_message=(
310
+ f"Failed to create resource group '{self._resource_group_name}' in"
311
+ f" subscription '{self._subscription_name}'"
312
+ ),
313
+ ignore_if_exists=True,
314
+ )
315
+
316
+ async def _create_app_registration(self) -> str:
317
+ """
318
+ Creates an app registration in Azure Active Directory.
319
+
320
+ Returns:
321
+ str: The client ID of the newly created app registration.
322
+
323
+ Raises:
324
+ subprocess.CalledProcessError: If the Azure CLI command execution fails.
325
+ """
326
+ # Check if the app registration already exists
327
+ check_exists_command = (
328
+ f"az ad app list --display-name {self._app_registration_name} --output json"
329
+ )
330
+ app_registrations = await self.azure_cli.run_command(
331
+ check_exists_command,
332
+ )
333
+ if app_registrations:
334
+ if isinstance(app_registrations, str):
335
+ app_registrations = json.loads(app_registrations)
336
+
337
+ existing_app_registration = next(
338
+ (
339
+ app
340
+ for app in app_registrations
341
+ if app["displayName"] == self._app_registration_name
342
+ ),
343
+ None,
344
+ )
345
+ if existing_app_registration:
346
+ self._console.print(
347
+ f"App registration '{self._app_registration_name}' already exists.",
348
+ style="yellow",
349
+ )
350
+ return existing_app_registration["appId"]
351
+
352
+ app_registration_command = (
353
+ f"az ad app create --display-name {self._app_registration_name} "
354
+ "--output json"
355
+ )
356
+ app_registration = await self.azure_cli.run_command(
357
+ app_registration_command,
358
+ success_message=(
359
+ f"App registration '{self._app_registration_name}' created successfully"
360
+ ),
361
+ failure_message=(
362
+ "Failed to create app registration with name"
363
+ f" '{self._app_registration_name}'"
364
+ ),
365
+ ignore_if_exists=True,
366
+ )
367
+ if app_registration:
368
+ if isinstance(app_registration, str):
369
+ app_registration = json.loads(app_registration)
370
+ return app_registration["appId"]
371
+
372
+ else:
373
+ raise RuntimeError("Failed to create app registration.")
374
+
375
+ async def _generate_secret_for_app(self, app_id: str) -> tuple:
376
+ """
377
+ Generates a secret for the app registration.
378
+
379
+ Args:
380
+ app_id (str): The client ID of the app registration for which to generate the secret.
381
+
382
+ Returns:
383
+ tuple: A tuple containing the tenant ID and the generated secret.
384
+
385
+ Raises:
386
+ subprocess.CalledProcessError: If the Azure CLI command execution fails.
387
+ """
388
+ secret_command = (
389
+ f"az ad app credential reset --id {app_id} --append --output json"
390
+ )
391
+ app_secret = await self.azure_cli.run_command(
392
+ secret_command,
393
+ success_message=(
394
+ f"Secret generated for app registration with client ID '{app_id}'"
395
+ ),
396
+ failure_message=(
397
+ "Failed to generate secret for app registration with client ID"
398
+ f" '{app_id}'. If you have already generated 2 secrets for this app"
399
+ " registration, please delete one from the"
400
+ f" `{self._app_registration_name}` resource and try again."
401
+ ),
402
+ ignore_if_exists=True,
403
+ return_json=True,
404
+ )
405
+
406
+ try:
407
+ return app_secret["tenant"], app_secret["password"]
408
+ except Exception as e:
409
+ raise RuntimeError(
410
+ "Failed to generate a new secret for the app registration."
411
+ ) from e
412
+
413
+ async def _get_or_create_service_principal_object_id(self, app_id: str):
414
+ """
415
+ Retrieves or creates a service principal for the given app registration client ID.
416
+
417
+ Args:
418
+ app_id (str): The client ID of the app registration.
419
+
420
+ Returns:
421
+ str: The object ID of the service principal.
422
+ """
423
+ # Try to retrieve the existing service principal
424
+ command_get_sp = (
425
+ f"az ad sp list --all --query \"[?appId=='{app_id}']\" --output json"
426
+ )
427
+ service_principal = await self.azure_cli.run_command(
428
+ command_get_sp,
429
+ return_json=True,
430
+ )
431
+
432
+ if service_principal:
433
+ return service_principal[0]
434
+
435
+ # Service principal does not exist, create it
436
+ command_create_sp = f"az ad sp create --id {app_id}"
437
+ await self.azure_cli.run_command(
438
+ command_create_sp,
439
+ success_message=f"Service principal created for app ID '{app_id}'",
440
+ failure_message=f"Failed to create service principal for app ID '{app_id}'",
441
+ )
442
+
443
+ # Retrieve the object ID of the newly created service principal
444
+ new_service_principal = await self.azure_cli.run_command(
445
+ command_get_sp,
446
+ failure_message=(
447
+ f"Failed to retrieve new service principal for app ID {app_id}"
448
+ ),
449
+ return_json=True,
450
+ )
451
+
452
+ if new_service_principal:
453
+ return new_service_principal[0]
454
+ else:
455
+ raise Exception(
456
+ f"Failed to retrieve new service principal for app ID {app_id}"
457
+ )
458
+
459
+ async def _get_or_create_identity(
460
+ self, identity_name: str, resource_group_name: str, subscription_id: str
461
+ ):
462
+ """
463
+ Retrieves or creates a managed identity for the given resource group.
464
+
465
+ Returns:
466
+ dict: Object representing the identity.
467
+ """
468
+ # Try to retrieve the existing identity
469
+ command_get_identity = (
470
+ f"az identity list --query \"[?name=='{identity_name}']\" --resource-group"
471
+ f" {resource_group_name} --subscription {subscription_id} --output json"
472
+ )
473
+ identity = await self.azure_cli.run_command(
474
+ command_get_identity,
475
+ return_json=True,
476
+ )
477
+
478
+ if identity:
479
+ self._console.print(
480
+ (
481
+ f"Identity '{self._identity_name}' already exists in"
482
+ f" subscription '{self._subscription_name}'."
483
+ ),
484
+ style="yellow",
485
+ )
486
+ return identity[0]
487
+
488
+ # Identity does not exist, create it
489
+ command_create_identity = (
490
+ f"az identity create --name {identity_name} --resource-group"
491
+ f" {resource_group_name} --subscription {subscription_id} --output json"
492
+ )
493
+ response = await self.azure_cli.run_command(
494
+ command_create_identity,
495
+ success_message=f"Identity {identity_name!r} created",
496
+ failure_message=f"Failed to create identity {identity_name!r}",
497
+ return_json=True,
498
+ )
499
+
500
+ if response:
501
+ return response
502
+ else:
503
+ raise Exception(
504
+ f"Failed to retrieve new identity for identity {self._identity_name}"
505
+ )
506
+
507
+ @staticmethod
508
+ def _generate_acr_name(base_name: str):
509
+ # Ensure the base name adheres to ACR naming conventions
510
+ if not base_name.isalnum() or len(base_name) > 50:
511
+ raise ValueError(
512
+ "ACR registry name prefix should be alphanumeric and up to 50"
513
+ " characters"
514
+ )
515
+
516
+ # Generate a unique string
517
+ timestamp = int(time.time())
518
+ random_str = "".join(
519
+ random.choices(string.ascii_lowercase + string.digits, k=4)
520
+ )
521
+
522
+ # Combine to form the ACR name
523
+ acr_name = f"{base_name}{timestamp}{random_str}"
524
+ return acr_name
525
+
526
+ async def _get_or_create_registry(
527
+ self,
528
+ registry_name: str,
529
+ resource_group_name: str,
530
+ location: str,
531
+ subscription_id: str,
532
+ ):
533
+ """
534
+ Retrieves or creates an Azure Container Registry.
535
+
536
+ Args:
537
+ registry_name: The name of the registry.
538
+ resource_group_name: The name of the resource group to use for the registry.
539
+ location: Where to create the registry.
540
+ subscription_id: The ID of the subscription to use for the registry.
541
+
542
+ Returns:
543
+ dict: Object representing the registry.
544
+ """
545
+ # check to see if there are any registries starting with 'prefect'
546
+ command_get_registries = (
547
+ 'az acr list --query "[?starts_with(name,'
548
+ f" '{self._registry_name_prefix}')]\" --subscription"
549
+ f" {subscription_id} --output json"
550
+ )
551
+ response = await self.azure_cli.run_command(
552
+ command_get_registries,
553
+ return_json=True,
554
+ )
555
+
556
+ # acr names must be globally unique, so if there are any matches, use the first one
557
+ if response:
558
+ self._console.print(
559
+ (
560
+ f"Registry with prefix {self._registry_name_prefix!r} already"
561
+ f" exists in subscription '{subscription_id}'."
562
+ ),
563
+ style="yellow",
564
+ )
565
+ return response[0]
566
+
567
+ command_create_repository = (
568
+ f"az acr create --name {registry_name} --resource-group"
569
+ f" {resource_group_name} --subscription {subscription_id} --location"
570
+ f" {location} --sku Basic"
571
+ )
572
+ response = await self.azure_cli.run_command(
573
+ command_create_repository,
574
+ success_message="Registry created",
575
+ failure_message="Failed to create registry",
576
+ return_json=True,
577
+ )
578
+
579
+ if response:
580
+ return response
581
+ else:
582
+ raise Exception(f"Failed to create registry {registry_name}")
583
+
584
+ async def _log_into_registry(self, login_server: str, subscription_id: str):
585
+ """
586
+ Logs into the given Azure Container Registry.
587
+
588
+ Args:
589
+ registry_name: The name of the registry to log into.
590
+
591
+ Raises:
592
+ subprocess.CalledProcessError: If the Azure CLI command execution fails.
593
+ """
594
+ command_login = (
595
+ f"az acr login --name {login_server} --subscription {subscription_id}"
596
+ )
597
+ await self.azure_cli.run_command(
598
+ command_login,
599
+ success_message=f"Logged into registry {login_server}",
600
+ failure_message=f"Failed to log into registry {login_server}",
601
+ )
602
+
603
+ async def _assign_contributor_role(self, app_id: str, subscription_id: str) -> None:
604
+ """
605
+ Assigns the 'Contributor' role to the service principal associated with a given app ID.
606
+
607
+ Args:
608
+ app_id (str): The client ID of the app registration.
609
+ """
610
+ service_principal = await self._get_or_create_service_principal_object_id(
611
+ app_id
612
+ )
613
+
614
+ service_principal_id = service_principal["id"]
615
+
616
+ if service_principal_id:
617
+ role = "Contributor"
618
+ scope = f"/subscriptions/{self._subscription_id}/resourceGroups/{self._resource_group_name}"
619
+
620
+ # Check if the role is already assigned
621
+ check_role_command = (
622
+ f"az role assignment list --assignee {service_principal_id} --role"
623
+ f" {role} --scope {scope} --subscription {subscription_id} --output"
624
+ " json"
625
+ )
626
+ role_assignments = await self.azure_cli.run_command(
627
+ check_role_command, return_json=True
628
+ )
629
+ if role_assignments and any(
630
+ ra
631
+ for ra in role_assignments
632
+ if ra["roleDefinitionName"] == role and ra["scope"] == scope
633
+ ):
634
+ self._console.print(
635
+ (
636
+ f"Service principal with object ID '{service_principal_id}'"
637
+ f" already has the '{role}' role assigned in '{scope}'."
638
+ ),
639
+ style="yellow",
640
+ )
641
+ return
642
+
643
+ assign_command = (
644
+ f"az role assignment create --role {role} --assignee-object-id"
645
+ f" {service_principal_id} --scope {scope} --subscription"
646
+ f" {subscription_id}"
647
+ )
648
+ await self.azure_cli.run_command(
649
+ assign_command,
650
+ success_message=(
651
+ "Contributor role assigned to service principal with object ID"
652
+ f" '{service_principal_id}'"
653
+ ),
654
+ failure_message=(
655
+ "Failed to assign Contributor role to service principal with"
656
+ f" object ID '{service_principal_id}'"
657
+ ),
658
+ ignore_if_exists=True,
659
+ )
660
+
661
+ async def _assign_acr_pull_role(
662
+ self, identity: Dict[str, Any], registry: Dict[str, Any], subscription_id: str
663
+ ) -> None:
664
+ """
665
+ Assigns the AcrPull role to the specified identity for the given registry.
666
+
667
+ Args:
668
+ identity: The identity to assign the role to.
669
+ registry: The registry to grant access to.
670
+ """
671
+ command = (
672
+ f"az role assignment create --assignee {identity['principalId']} --scope"
673
+ f" {registry['id']} --role AcrPull --subscription {subscription_id}"
674
+ )
675
+ await self.azure_cli.run_command(
676
+ command,
677
+ ignore_if_exists=True,
678
+ )
679
+
680
+ async def _create_aci_credentials_block(
681
+ self,
682
+ work_pool_name: str,
683
+ client_id: str,
684
+ tenant_id: str,
685
+ client_secret: str,
686
+ client: PrefectClient,
687
+ ) -> UUID:
688
+ """
689
+ Creates a credentials block for Azure Container Instance.
690
+
691
+ Args:
692
+ work_pool_name (str): The name of the work pool.
693
+ client_id (str): The client ID obtained from app registration.
694
+ tenant_id (str): The tenant ID obtained from the secret generation.
695
+ client_secret (str): The client secret obtained from the secret generation.
696
+ client (PrefectClient): An instance of PrefectClient.
697
+
698
+ Returns:
699
+ UUID: The ID of the created credentials block.
700
+
701
+ Raises:
702
+ ObjectAlreadyExists: If a credentials block with the same name already exists.
703
+ """
704
+ credentials_block_name = self._credentials_block_name
705
+ credentials_block_type = await client.read_block_type_by_slug(
706
+ "azure-container-instance-credentials"
707
+ )
708
+
709
+ credentials_block_schema = (
710
+ await client.get_most_recent_block_schema_for_block_type(
711
+ block_type_id=credentials_block_type.id
712
+ )
713
+ )
714
+
715
+ try:
716
+ block_doc = await client.create_block_document(
717
+ block_document=BlockDocumentCreate(
718
+ name=credentials_block_name,
719
+ data={
720
+ "client_id": client_id,
721
+ "tenant_id": tenant_id,
722
+ "client_secret": client_secret,
723
+ },
724
+ block_type_id=credentials_block_type.id,
725
+ block_schema_id=credentials_block_schema.id,
726
+ )
727
+ )
728
+
729
+ self._console.print(
730
+ (
731
+ f"ACI credentials block '{credentials_block_name}' created in"
732
+ " Prefect Cloud"
733
+ ),
734
+ style="green",
735
+ )
736
+ return block_doc.id
737
+
738
+ except ObjectAlreadyExists:
739
+ self._console.print(
740
+ f"ACI credentials block '{credentials_block_name}' already exists",
741
+ style="yellow",
742
+ )
743
+ block_doc = await client.read_block_document_by_name(
744
+ name=credentials_block_name,
745
+ block_type_slug="azure-container-instance-credentials",
746
+ )
747
+ return block_doc.id
748
+
749
+ except Exception as e:
750
+ self._console.print(
751
+ f"Failed to create ACI credentials block: {e}",
752
+ style="red",
753
+ )
754
+ raise e
755
+
756
+ async def _aci_credentials_block_exists(
757
+ self, block_name: str, client: PrefectClient
758
+ ) -> bool:
759
+ """
760
+ Checks if an ACI credentials block with the given name already exists.
761
+
762
+ Args:
763
+ block_name (str): The name of the ACI credentials block.
764
+ client (PrefectClient): An instance of PrefectClient.
765
+
766
+ Returns:
767
+ bool: True if the credentials block exists, False otherwise.
768
+ """
769
+ try:
770
+ await client.read_block_document_by_name(
771
+ name=block_name,
772
+ block_type_slug="azure-container-instance-credentials",
773
+ )
774
+ return True
775
+ except ObjectNotFound:
776
+ return False
777
+
778
+ def _validate_user_input(self, name):
779
+ if 2 < len(name) < 40 and name.isalnum():
780
+ return True
781
+ else:
782
+ return False
783
+
784
+ async def _create_provision_table(self, work_pool_name: str, client: PrefectClient):
785
+ return Panel(
786
+ dedent(
787
+ f"""\
788
+ Provisioning infrastructure for your work pool [blue]{work_pool_name}[/] will require:
789
+
790
+ Updates in subscription: [blue]{self._subscription_name}[/]
791
+
792
+ - Create a resource group in location: [blue]{self._location}[/]
793
+ - Create an app registration in Azure AD: [blue]{self._app_registration_name}[/]
794
+ - Create/use a service principal for app registration
795
+ - Generate a secret for app registration
796
+ - Create an Azure Container Registry with prefix [blue]{self._registry_name_prefix}[/]
797
+ - Create an identity [blue]{self._identity_name}[/] to allow access to the created registry
798
+ - Assign Contributor role to service account
799
+ - Create an ACR registry for image hosting
800
+ - Create an identity for Azure Container Instance to allow access to the registry
801
+
802
+ Updates in Prefect workspace
803
+
804
+ - Create Azure Container Instance credentials block: [blue]{self._credentials_block_name}[/]
805
+ """
806
+ ),
807
+ expand=False,
808
+ )
809
+
810
+ async def _customize_resource_names(
811
+ self, work_pool_name: str, client: PrefectClient
812
+ ) -> bool:
813
+ self._resource_group_name = prompt(
814
+ "Please enter a name for the resource group",
815
+ default=self._resource_group_name,
816
+ )
817
+ self._app_registration_name = prompt(
818
+ "Please enter a name for the app registration",
819
+ default=self._app_registration_name,
820
+ )
821
+ while True:
822
+ self._registry_name_prefix = prompt(
823
+ "Please enter a prefix for the Azure Container Registry",
824
+ default=self._registry_name_prefix,
825
+ )
826
+ if self._validate_user_input(self._registry_name_prefix):
827
+ break
828
+ else:
829
+ self._console.print(
830
+ "The prefix must be alphanumeric and between 3-50 characters.",
831
+ style="red",
832
+ )
833
+ while True:
834
+ self._identity_name = prompt(
835
+ "Please enter a name for the identity (used for ACR access)",
836
+ default=self._identity_name,
837
+ )
838
+ if self._validate_user_input(self._identity_name):
839
+ break
840
+ else:
841
+ self._console.print(
842
+ "The identity name must be alphanumeric and at least 3 characters.",
843
+ style="red",
844
+ )
845
+ self._credentials_block_name = prompt(
846
+ "Please enter a name for the ACI credentials block",
847
+ default=self._credentials_block_name,
848
+ )
849
+ table = await self._create_provision_table(work_pool_name, client)
850
+ self._console.print(table)
851
+
852
+ return Confirm.ask(
853
+ "Proceed with infrastructure provisioning?", console=self._console
854
+ )
855
+
856
+ @inject_client
857
+ async def provision(
858
+ self,
859
+ work_pool_name: str,
860
+ base_job_template: Dict[str, Any],
861
+ client: Optional[PrefectClient] = None,
862
+ ) -> Dict[str, Any]:
863
+ """
864
+ Orchestrates the provisioning of Azure resources and setup for the push work pool.
865
+
866
+ Args:
867
+ work_pool_name (str): The name of the work pool.
868
+ base_job_template (Dict[str, Any]): The base template for job creation.
869
+ client (Optional[PrefectClient]): An instance of PrefectClient. If None, it will be injected.
870
+
871
+ Returns:
872
+ Dict[str, Any]: The updated job template with necessary references and configurations.
873
+
874
+ Raises:
875
+ RuntimeError: If client injection fails or the Azure CLI command execution fails.
876
+ """
877
+ if not client:
878
+ self._console.print(
879
+ "Client injection failed, cannot proceed with provisioning.",
880
+ style="red",
881
+ )
882
+ return base_job_template
883
+
884
+ await self._verify_az_ready()
885
+ await self._select_subscription()
886
+ await self.set_location()
887
+ self._credentials_block_name = f"{work_pool_name}-push-pool-credentials"
888
+
889
+ table = await self._create_provision_table(work_pool_name, client)
890
+ self._console.print(table)
891
+ if self._console.is_interactive:
892
+ chosen_option = prompt_select_from_table(
893
+ self._console,
894
+ "Proceed with infrastructure provisioning with default resource names?",
895
+ [
896
+ {"header": "Options:", "key": "option"},
897
+ ],
898
+ [
899
+ {
900
+ "option": (
901
+ "Yes, proceed with infrastructure provisioning with default"
902
+ " resource names"
903
+ )
904
+ },
905
+ {"option": "Customize resource names"},
906
+ {"option": "Do not proceed with infrastructure provisioning"},
907
+ ],
908
+ )
909
+ if chosen_option["option"] == "Customize resource names":
910
+ if not await self._customize_resource_names(work_pool_name, client):
911
+ return base_job_template
912
+
913
+ elif (
914
+ chosen_option["option"]
915
+ == "Do not proceed with infrastructure provisioning"
916
+ ):
917
+ return base_job_template
918
+ elif (
919
+ chosen_option["option"]
920
+ != "Yes, proceed with infrastructure provisioning with default"
921
+ " resource names"
922
+ ):
923
+ # basically, we should never hit this. i'm concerned that we might change
924
+ # the options in the future and forget to update this check
925
+ raise ValueError(f"Invalid option selected: {chosen_option['option']}")
926
+
927
+ credentials_block_exists = await self._aci_credentials_block_exists(
928
+ block_name=self._credentials_block_name, client=client
929
+ )
930
+
931
+ if not credentials_block_exists:
932
+ total_tasks = 7
933
+ else:
934
+ total_tasks = 6
935
+
936
+ with Progress(console=self._console) as progress:
937
+ self.azure_cli._console = progress.console
938
+ task = progress.add_task("Provisioning infrastructure.", total=total_tasks)
939
+ progress.console.print("Creating resource group")
940
+ await self._create_resource_group()
941
+ progress.advance(task)
942
+
943
+ progress.console.print("Creating app registration")
944
+ client_id = await self._create_app_registration()
945
+ progress.advance(task)
946
+
947
+ credentials_block_exists = await self._aci_credentials_block_exists(
948
+ block_name=self._credentials_block_name, client=client
949
+ )
950
+
951
+ if not credentials_block_exists:
952
+ progress.console.print("Generating secret for app registration")
953
+ tenant_id, client_secret = await self._generate_secret_for_app(
954
+ app_id=client_id,
955
+ )
956
+ progress.advance(task)
957
+
958
+ progress.console.print("Creating ACI credentials block")
959
+ block_doc_id = await self._create_aci_credentials_block(
960
+ work_pool_name, client_id, tenant_id, client_secret, client
961
+ )
962
+ progress.advance(task)
963
+ else:
964
+ progress.console.print(
965
+ "ACI credentials block already exists.", style="yellow"
966
+ )
967
+ block_doc = await client.read_block_document_by_name(
968
+ name=self._credentials_block_name,
969
+ block_type_slug="azure-container-instance-credentials",
970
+ )
971
+ block_doc_id = block_doc.id
972
+ progress.advance(task)
973
+
974
+ progress.console.print("Assigning Contributor role to service account")
975
+ await self._assign_contributor_role(
976
+ app_id=client_id, subscription_id=self._subscription_id
977
+ )
978
+ progress.advance(task)
979
+
980
+ progress.console.print(
981
+ "Creating Azure Container Registry (this make take a few minutes)"
982
+ )
983
+
984
+ registry_name = self._generate_acr_name(self._registry_name_prefix)
985
+ registry = await self._get_or_create_registry(
986
+ registry_name=registry_name,
987
+ resource_group_name=self._resource_group_name,
988
+ location=self._location,
989
+ subscription_id=self._subscription_id,
990
+ )
991
+ await self._log_into_registry(
992
+ login_server=registry["loginServer"],
993
+ subscription_id=self._subscription_id,
994
+ )
995
+ update_current_profile(
996
+ {PREFECT_DEFAULT_DOCKER_BUILD_NAMESPACE: registry["loginServer"]}
997
+ )
998
+ progress.advance(task)
999
+
1000
+ progress.console.print("Creating identity")
1001
+ identity = await self._get_or_create_identity(
1002
+ identity_name=self._identity_name,
1003
+ resource_group_name=self._resource_group_name,
1004
+ subscription_id=self._subscription_id,
1005
+ )
1006
+ await self._assign_acr_pull_role(
1007
+ identity=identity,
1008
+ registry=registry,
1009
+ subscription_id=self._subscription_id,
1010
+ )
1011
+ progress.advance(task)
1012
+
1013
+ base_job_template_copy = deepcopy(base_job_template)
1014
+ base_job_template_copy["variables"]["properties"]["aci_credentials"][
1015
+ "default"
1016
+ ] = {"$ref": {"block_document_id": str(block_doc_id)}}
1017
+
1018
+ base_job_template_copy["variables"]["properties"]["resource_group_name"][
1019
+ "default"
1020
+ ] = self._resource_group_name
1021
+
1022
+ base_job_template_copy["variables"]["properties"]["subscription_id"][
1023
+ "default"
1024
+ ] = self._subscription_id
1025
+ base_job_template_copy["variables"]["properties"]["image_registry"][
1026
+ "default"
1027
+ ] = {
1028
+ "registry_url": registry["loginServer"],
1029
+ "identity": identity["id"],
1030
+ }
1031
+ base_job_template_copy["variables"]["properties"]["identities"]["default"] = [
1032
+ identity["id"]
1033
+ ]
1034
+
1035
+ self._console.print(
1036
+ dedent(
1037
+ f"""\
1038
+ Your default Docker build namespace has been set to [blue]{registry["loginServer"]!r}[/].
1039
+ Use any image name to build and push to this registry by default:
1040
+ """
1041
+ ),
1042
+ Panel(
1043
+ Syntax(
1044
+ dedent(
1045
+ f"""\
1046
+ from prefect import flow
1047
+ from prefect.deployments import DeploymentImage
1048
+
1049
+
1050
+ @flow(log_prints=True)
1051
+ def my_flow(name: str = "world"):
1052
+ print(f"Hello {{name}}! I'm a flow running on an Azure Container Instance!")
1053
+
1054
+
1055
+ if __name__ == "__main__":
1056
+ my_flow.deploy(
1057
+ name="my-deployment",
1058
+ work_pool_name="{work_pool_name}",
1059
+ image=DeploymentImage(
1060
+ name="my-image:latest",
1061
+ platform="linux/amd64",
1062
+ )
1063
+ )"""
1064
+ ),
1065
+ "python",
1066
+ background_color="default",
1067
+ ),
1068
+ title="example_deploy_script.py",
1069
+ expand=False,
1070
+ ),
1071
+ )
1072
+
1073
+ self._console.print(
1074
+ (
1075
+ f"Infrastructure successfully provisioned for '{work_pool_name}' work"
1076
+ " pool!"
1077
+ ),
1078
+ style="green",
1079
+ )
1080
+ return base_job_template_copy