-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
deploy.py
1705 lines (1502 loc) · 59.1 KB
/
deploy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Module containing implementation for deploying flows."""
import json
import os
import re
from copy import deepcopy
from datetime import timedelta
from getpass import GetPassWarning
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from uuid import UUID
import typer
import yaml
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from yaml.error import YAMLError
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
else:
import pydantic
import prefect
from prefect._internal.compatibility.deprecated import (
generate_deprecation_message,
)
from prefect.blocks.system import Secret
from prefect.cli._prompts import (
confirm,
prompt,
prompt_build_custom_docker_image,
prompt_entrypoint,
prompt_push_custom_docker_image,
prompt_schedules,
prompt_select_blob_storage_credentials,
prompt_select_from_table,
prompt_select_remote_flow_storage,
prompt_select_work_pool,
)
from prefect.cli._types import SettingsOption
from prefect.cli._utilities import (
exit_with_error,
)
from prefect.cli.root import app, is_interactive
from prefect.client.orchestration import PrefectClient, ServerType
from prefect.client.schemas.objects import MinimalDeploymentSchedule
from prefect.client.schemas.schedules import (
CronSchedule,
IntervalSchedule,
RRuleSchedule,
)
from prefect.client.utilities import inject_client
from prefect.deployments import initialize_project
from prefect.deployments.base import (
_format_deployment_for_saving_to_prefect_file,
_get_git_branch,
_get_git_remote_origin_url,
_save_deployment_to_prefect_file,
)
from prefect.deployments.steps.core import run_steps
from prefect.events import DeploymentTriggerTypes, TriggerTypes
from prefect.exceptions import ObjectNotFound, PrefectHTTPStatusError
from prefect.flows import load_flow_from_entrypoint
from prefect.settings import (
PREFECT_DEFAULT_WORK_POOL_NAME,
PREFECT_UI_URL,
)
from prefect.utilities.annotations import NotSet
from prefect.utilities.asyncutils import run_sync_in_worker_thread
from prefect.utilities.callables import parameter_schema
from prefect.utilities.collections import get_from_dict
from prefect.utilities.slugify import slugify
from prefect.utilities.templating import (
apply_values,
resolve_block_document_references,
resolve_variables,
)
@app.command()
async def init(
name: str = None,
recipe: str = None,
fields: List[str] = typer.Option(
None,
"-f",
"--field",
help=(
"One or more fields to pass to the recipe (e.g., image_name) in the format"
" of key=value."
),
),
):
"""
Initialize a new deployment configuration recipe.
"""
inputs = {}
fields = fields or []
recipe_paths = prefect.__module_path__ / "deployments" / "recipes"
for field in fields:
key, value = field.split("=")
inputs[key] = value
if not recipe and is_interactive():
recipe_paths = prefect.__module_path__ / "deployments" / "recipes"
recipes = []
for r in recipe_paths.iterdir():
if r.is_dir() and (r / "prefect.yaml").exists():
with open(r / "prefect.yaml") as f:
recipe_data = yaml.safe_load(f)
recipe_name = r.name
recipe_description = recipe_data.get(
"description", "(no description available)"
)
recipe_dict = {
"name": recipe_name,
"description": recipe_description,
}
recipes.append(recipe_dict)
selected_recipe = prompt_select_from_table(
app.console,
"Would you like to initialize your deployment configuration with a recipe?",
columns=[
{"header": "Name", "key": "name"},
{"header": "Description", "key": "description"},
],
data=recipes,
opt_out_message="No, I'll use the default deployment configuration.",
opt_out_response={},
)
if selected_recipe != {}:
recipe = selected_recipe["name"]
if recipe and (recipe_paths / recipe / "prefect.yaml").exists():
with open(recipe_paths / recipe / "prefect.yaml") as f:
recipe_inputs = yaml.safe_load(f).get("required_inputs") or {}
if recipe_inputs:
if set(recipe_inputs.keys()) < set(inputs.keys()):
# message to user about extra fields
app.console.print(
(
f"Warning: extra fields provided for {recipe!r} recipe:"
f" '{', '.join(set(inputs.keys()) - set(recipe_inputs.keys()))}'"
),
style="red",
)
elif set(recipe_inputs.keys()) > set(inputs.keys()):
table = Table(
title=f"[red]Required inputs for {recipe!r} recipe[/red]",
)
table.add_column("Field Name", style="green", no_wrap=True)
table.add_column(
"Description", justify="left", style="white", no_wrap=False
)
for field, description in recipe_inputs.items():
if field not in inputs:
table.add_row(field, description)
app.console.print(table)
for key, description in recipe_inputs.items():
if key not in inputs:
inputs[key] = typer.prompt(key)
app.console.print("-" * 15)
try:
files = [
f"[green]{fname}[/green]"
for fname in initialize_project(name=name, recipe=recipe, inputs=inputs)
]
except ValueError as exc:
if "Unknown recipe" in str(exc):
exit_with_error(
f"Unknown recipe {recipe!r} provided - run [yellow]`prefect init"
"`[/yellow] to see all available recipes."
)
else:
raise
files = "\n".join(files)
empty_msg = (
f"Created project in [green]{Path('.').resolve()}[/green]; no new files"
" created."
)
file_msg = (
f"Created project in [green]{Path('.').resolve()}[/green] with the following"
f" new files:\n{files}"
)
app.console.print(file_msg if files else empty_msg)
@app.command()
async def deploy(
entrypoint: str = typer.Argument(
None,
help=(
"The path to a flow entrypoint within a project, in the form of"
" `./path/to/file.py:flow_func_name`"
),
),
names: List[str] = typer.Option(
None,
"--name",
"-n",
help=(
"The name to give the deployment. Can be a pattern. Examples:"
" 'my-deployment', 'my-flow/my-deployment', 'my-deployment-*',"
" '*-flow-name/deployment*'"
),
),
description: str = typer.Option(
None,
"--description",
"-d",
help=(
"The description to give the deployment. If not provided, the description"
" will be populated from the flow's description."
),
),
version: str = typer.Option(
None, "--version", help="A version to give the deployment."
),
tags: List[str] = typer.Option(
None,
"-t",
"--tag",
help=(
"One or more optional tags to apply to the deployment. Note: tags are used"
" only for organizational purposes. For delegating work to agents, use the"
" --work-queue flag."
),
),
work_pool_name: str = SettingsOption(
PREFECT_DEFAULT_WORK_POOL_NAME,
"-p",
"--pool",
help="The work pool that will handle this deployment's runs.",
),
work_queue_name: str = typer.Option(
None,
"-q",
"--work-queue",
help=(
"The work queue that will handle this deployment's runs. "
"It will be created if it doesn't already exist. Defaults to `None`."
),
),
variables: List[str] = typer.Option(
None,
"-v",
"--variable",
help=("DEPRECATED: Please use --jv/--job-variable for similar functionality "),
),
job_variables: List[str] = typer.Option(
None,
"-jv",
"--job-variable",
help=(
"One or more job variable overrides for the work pool provided in the"
" format of key=value string or a JSON object"
),
),
cron: List[str] = typer.Option(
None,
"--cron",
help="A cron string that will be used to set a CronSchedule on the deployment.",
),
interval: List[int] = typer.Option(
None,
"--interval",
help=(
"An integer specifying an interval (in seconds) that will be used to set an"
" IntervalSchedule on the deployment."
),
),
interval_anchor: Optional[str] = typer.Option(
None, "--anchor-date", help="The anchor date for all interval schedules"
),
rrule: List[str] = typer.Option(
None,
"--rrule",
help="An RRule that will be used to set an RRuleSchedule on the deployment.",
),
timezone: str = typer.Option(
None,
"--timezone",
help="Deployment schedule timezone string e.g. 'America/New_York'",
),
trigger: List[str] = typer.Option(
None,
"--trigger",
help=(
"Specifies a trigger for the deployment. The value can be a"
" json string or path to `.yaml`/`.json` file. This flag can be used"
" multiple times."
),
),
param: List[str] = typer.Option(
None,
"--param",
help=(
"An optional parameter override, values are parsed as JSON strings e.g."
" --param question=ultimate --param answer=42"
),
),
params: str = typer.Option(
None,
"--params",
help=(
"An optional parameter override in a JSON string format e.g."
' --params=\'{"question": "ultimate", "answer": 42}\''
),
),
enforce_parameter_schema: bool = typer.Option(
False,
"--enforce-parameter-schema",
help=(
"Whether to enforce the parameter schema on this deployment. If set to"
" True, any parameters passed to this deployment must match the signature"
" of the flow."
),
),
deploy_all: bool = typer.Option(
False,
"--all",
help=(
"Deploy all flows in the project. If a flow name or entrypoint is also"
" provided, this flag will be ignored."
),
),
prefect_file: Path = typer.Option(
Path("prefect.yaml"),
"--prefect-file",
help="Specify a custom path to a prefect.yaml file",
),
):
"""
Deploy a flow from this project by creating a deployment.
Should be run from a project root directory.
"""
if variables is not None:
app.console.print(
generate_deprecation_message(
name="The `--variable` flag",
start_date="Mar 2024",
help=(
"Please use the `--job-variable foo=bar` argument instead: `prefect"
" deploy --job-variable`."
),
),
style="yellow",
)
if variables is None:
variables = list()
if job_variables is None:
job_variables = list()
job_variables.extend(variables)
options = {
"entrypoint": entrypoint,
"description": description,
"version": version,
"tags": tags,
"work_pool_name": work_pool_name,
"work_queue_name": work_queue_name,
"variables": job_variables,
"cron": cron,
"interval": interval,
"anchor_date": interval_anchor,
"rrule": rrule,
"timezone": timezone,
"triggers": trigger,
"param": param,
"params": params,
"enforce_parameter_schema": enforce_parameter_schema,
}
try:
deploy_configs, actions = _load_deploy_configs_and_actions(
prefect_file=prefect_file,
)
parsed_names = []
for name in names or []:
if "*" in name:
parsed_names.extend(_parse_name_from_pattern(deploy_configs, name))
else:
parsed_names.append(name)
deploy_configs = _pick_deploy_configs(
deploy_configs,
parsed_names,
deploy_all,
)
if len(deploy_configs) > 1:
if any(options.values()):
app.console.print(
(
"You have passed options to the deploy command, but you are"
" creating or updating multiple deployments. These options"
" will be ignored."
),
style="yellow",
)
await _run_multi_deploy(
deploy_configs=deploy_configs,
actions=actions,
deploy_all=deploy_all,
prefect_file=prefect_file,
)
else:
# Accommodate passing in -n flow-name/deployment-name as well as -n deployment-name
options["names"] = [
name.split("/", 1)[-1] if "/" in name else name for name in parsed_names
]
await _run_single_deploy(
deploy_config=deploy_configs[0] if deploy_configs else {},
actions=actions,
options=options,
prefect_file=prefect_file,
)
except ValueError as exc:
exit_with_error(str(exc))
@inject_client
async def _run_single_deploy(
deploy_config: Dict,
actions: Dict,
options: Optional[Dict] = None,
client: PrefectClient = None,
prefect_file: Path = Path("prefect.yaml"),
):
deploy_config = deepcopy(deploy_config) if deploy_config else {}
actions = deepcopy(actions) if actions else {}
options = deepcopy(options) if options else {}
should_prompt_for_save = is_interactive()
deploy_config = _merge_with_default_deploy_config(deploy_config)
deploy_config = _handle_deprecated_schedule_fields(deploy_config)
(
deploy_config,
variable_overrides,
) = _apply_cli_options_to_deploy_config(deploy_config, options)
build_steps = deploy_config.get("build", actions.get("build")) or []
push_steps = deploy_config.get("push", actions.get("push")) or []
pull_steps = deploy_config.get("pull", actions.get("pull")) or []
deploy_config = await resolve_block_document_references(deploy_config)
deploy_config = await resolve_variables(deploy_config)
# check for env var placeholders early so users can pass work pool names, etc.
deploy_config = apply_values(deploy_config, os.environ, remove_notset=False)
if not deploy_config.get("entrypoint"):
if not is_interactive():
raise ValueError(
"An entrypoint must be provided:\n\n"
" \t[yellow]prefect deploy path/to/file.py:flow_function\n\n"
"You can also provide an entrypoint in a prefect.yaml file."
)
deploy_config["entrypoint"] = await prompt_entrypoint(app.console)
if deploy_config.get("flow_name") and deploy_config.get("entrypoint"):
raise ValueError(
"Received an entrypoint and a flow name for this deployment. Please provide"
" either an entrypoint or a flow name."
)
# entrypoint logic
if deploy_config.get("entrypoint"):
flow = await run_sync_in_worker_thread(
load_flow_from_entrypoint, deploy_config["entrypoint"]
)
deploy_config["flow_name"] = flow.name
deployment_name = deploy_config.get("name")
if not deployment_name:
if not is_interactive():
raise ValueError("A deployment name must be provided.")
deploy_config["name"] = prompt("Deployment name", default="default")
deploy_config["parameter_openapi_schema"] = parameter_schema(flow)
deploy_config["schedules"] = _construct_schedules(
deploy_config,
)
# determine work pool
work_pool_name = get_from_dict(deploy_config, "work_pool.name")
if work_pool_name:
try:
work_pool = await client.read_work_pool(deploy_config["work_pool"]["name"])
# dont allow submitting to prefect-agent typed work pools
if work_pool.type == "prefect-agent":
if not is_interactive():
raise ValueError(
"Cannot create a project-style deployment with work pool of"
" type 'prefect-agent'. If you wish to use an agent with"
" your deployment, please use the `prefect deployment"
" build` command."
)
app.console.print(
"You've chosen a work pool with type 'prefect-agent' which"
" cannot be used for project-style deployments. Let's pick"
" another work pool to deploy to."
)
deploy_config["work_pool"]["name"] = await prompt_select_work_pool(
app.console,
client=client,
)
except ObjectNotFound:
raise ValueError(
"This deployment configuration references work pool"
f" {deploy_config['work_pool']['name']!r} which does not exist. This"
" means no worker will be able to pick up its runs. You can create a"
" work pool in the Prefect UI."
)
else:
if not is_interactive():
raise ValueError(
"A work pool is required to deploy this flow. Please specify a work"
" pool name via the '--pool' flag or in your prefect.yaml file."
)
if not isinstance(deploy_config.get("work_pool"), dict):
deploy_config["work_pool"] = {}
deploy_config["work_pool"]["name"] = await prompt_select_work_pool(
console=app.console, client=client
)
docker_build_steps = [
"prefect_docker.deployments.steps.build_docker_image",
]
docker_push_steps = [
"prefect_docker.deployments.steps.push_docker_image",
]
docker_build_step_exists = any(
any(step in action for step in docker_build_steps)
for action in deploy_config.get("build", actions.get("build")) or []
)
update_work_pool_image = False
build_step_set_to_null = "build" in deploy_config and deploy_config["build"] is None
work_pool = await client.read_work_pool(deploy_config["work_pool"]["name"])
if is_interactive() and not docker_build_step_exists and not build_step_set_to_null:
docker_based_infrastructure = "image" in work_pool.base_job_template.get(
"variables", {}
).get("properties", {})
if docker_based_infrastructure:
build_docker_image_step = await prompt_build_custom_docker_image(
app.console, deploy_config
)
if build_docker_image_step is not None:
work_pool_job_variables_image_not_found = not get_from_dict(
deploy_config, "work_pool.job_variables.image"
)
if work_pool_job_variables_image_not_found:
update_work_pool_image = True
(
push_docker_image_step,
updated_build_docker_image_step,
) = await prompt_push_custom_docker_image(
app.console, deploy_config, build_docker_image_step
)
if actions.get("build"):
actions["build"].append(updated_build_docker_image_step)
else:
actions["build"] = [updated_build_docker_image_step]
if push_docker_image_step is not None:
if actions.get("push"):
actions["push"].append(push_docker_image_step)
else:
actions["push"] = [push_docker_image_step]
build_steps = deploy_config.get("build", actions.get("build")) or []
push_steps = deploy_config.get("push", actions.get("push")) or []
docker_push_step_exists = any(
any(step in action for step in docker_push_steps)
for action in deploy_config.get("push", actions.get("push")) or []
)
## CONFIGURE PUSH and/or PULL STEPS FOR REMOTE FLOW STORAGE
if (
is_interactive()
and not (deploy_config.get("pull") or actions.get("pull"))
and not docker_push_step_exists
and confirm(
(
"Your Prefect workers will need access to this flow's code in order to"
" run it. Would you like your workers to pull your flow code from a"
" remote storage location when running this flow?"
),
default=True,
console=app.console,
)
):
actions = await _generate_actions_for_remote_flow_storage(
console=app.console, deploy_config=deploy_config, actions=actions
)
if trigger_specs := _gather_deployment_trigger_definitions(
options.get("triggers"), deploy_config.get("triggers")
):
triggers = _initialize_deployment_triggers(deployment_name, trigger_specs)
if client.server_type != ServerType.CLOUD:
app.console.print(
Panel(
(
"Deployment triggers are only supported on "
"Prefect Cloud. Any triggers defined for the deployment will "
"not be created."
),
),
style="yellow",
)
else:
triggers = []
pull_steps = (
pull_steps
or actions.get("pull")
or await _generate_default_pull_action(
app.console,
deploy_config=deploy_config,
actions=actions,
)
)
## RUN BUILD AND PUSH STEPS
step_outputs = {}
if build_steps:
app.console.print("Running deployment build steps...")
step_outputs.update(
await run_steps(build_steps, step_outputs, print_function=app.console.print)
)
if push_steps := push_steps or actions.get("push"):
app.console.print("Running deployment push steps...")
step_outputs.update(
await run_steps(push_steps, step_outputs, print_function=app.console.print)
)
step_outputs.update(variable_overrides)
if update_work_pool_image:
if "build-image" not in step_outputs:
app.console.print(
"Warning: no build-image step found in the deployment build steps."
" The work pool image will not be updated."
)
deploy_config["work_pool"]["job_variables"]["image"] = "{{ build-image.image }}"
if not deploy_config.get("description"):
deploy_config["description"] = flow.description
# save deploy_config before templating
deploy_config_before_templating = deepcopy(deploy_config)
## apply templating from build and push steps to the final deployment spec
_parameter_schema = deploy_config.pop("parameter_openapi_schema")
_schedules = deploy_config.pop("schedules")
deploy_config = apply_values(deploy_config, step_outputs)
deploy_config["parameter_openapi_schema"] = _parameter_schema
deploy_config["schedules"] = _schedules
pull_steps = apply_values(pull_steps, step_outputs, remove_notset=False)
flow_id = await client.create_flow_from_name(deploy_config["flow_name"])
deployment_id = await client.create_deployment(
flow_id=flow_id,
name=deploy_config.get("name"),
work_queue_name=get_from_dict(deploy_config, "work_pool.work_queue_name"),
work_pool_name=get_from_dict(deploy_config, "work_pool.name"),
version=deploy_config.get("version"),
schedules=deploy_config.get("schedules"),
paused=deploy_config.get("paused"),
enforce_parameter_schema=deploy_config.get("enforce_parameter_schema", False),
parameter_openapi_schema=deploy_config.get("parameter_openapi_schema").dict(),
parameters=deploy_config.get("parameters"),
description=deploy_config.get("description"),
tags=deploy_config.get("tags", []),
entrypoint=deploy_config.get("entrypoint"),
pull_steps=pull_steps,
job_variables=get_from_dict(deploy_config, "work_pool.job_variables"),
)
await _create_deployment_triggers(client, deployment_id, triggers)
app.console.print(
Panel(
f"Deployment '{deploy_config['flow_name']}/{deploy_config['name']}'"
f" successfully created with id '{deployment_id}'."
),
style="green",
)
if PREFECT_UI_URL:
app.console.print(
"\nView Deployment in UI:"
f" {PREFECT_UI_URL.value()}/deployments/deployment/{deployment_id}\n"
)
identical_deployment_exists_in_prefect_file = (
_check_if_identical_deployment_in_prefect_file(
deploy_config_before_templating, prefect_file
)
)
if should_prompt_for_save and not identical_deployment_exists_in_prefect_file:
if confirm(
(
"Would you like to save configuration for this deployment for faster"
" deployments in the future?"
),
console=app.console,
):
matching_deployment_exists = (
_check_for_matching_deployment_name_and_entrypoint_in_prefect_file(
deploy_config=deploy_config_before_templating,
prefect_file=prefect_file,
)
)
if matching_deployment_exists and not confirm(
(
"Found existing deployment configuration with name:"
f" [yellow]{deploy_config_before_templating.get('name')}[/yellow]"
" and entrypoint:"
f" [yellow]{deploy_config_before_templating.get('entrypoint')}[/yellow]"
f" in the [yellow]prefect.yaml[/yellow] file at {prefect_file}."
" Would you like to overwrite that entry?"
),
):
app.console.print(
"[red]Cancelled saving deployment configuration"
f" '{deploy_config_before_templating.get('name')}' to the"
f" deployment configuration file[/red] at {prefect_file}"
)
else:
_save_deployment_to_prefect_file(
deploy_config_before_templating,
build_steps=build_steps or None,
push_steps=push_steps or None,
pull_steps=pull_steps or None,
triggers=trigger_specs or None,
prefect_file=prefect_file,
)
app.console.print(
(
f"\n[green]Deployment configuration saved to {prefect_file}![/]"
" You can now deploy using this deployment configuration"
" with:\n\n\t[blue]$ prefect deploy -n"
f" {deploy_config['name']}[/]\n\nYou can also make changes to"
" this deployment configuration by making changes to the"
" YAML file."
),
)
if not work_pool.is_push_pool and not work_pool.is_managed_pool:
app.console.print(
"\nTo execute flow runs from this deployment, start a worker in a"
" separate terminal that pulls work from the"
f" {deploy_config['work_pool']['name']!r} work pool:"
)
app.console.print(
f"\n\t$ prefect worker start --pool {deploy_config['work_pool']['name']!r}",
style="blue",
)
app.console.print(
"\nTo schedule a run for this deployment, use the following command:"
)
app.console.print(
(
"\n\t$ prefect deployment run"
f" '{deploy_config['flow_name']}/{deploy_config['name']}'\n"
),
style="blue",
)
async def _run_multi_deploy(
deploy_configs: List[Dict],
actions: Dict,
names: Optional[List[str]] = None,
deploy_all: bool = False,
prefect_file: Path = Path("prefect.yaml"),
):
deploy_configs = deepcopy(deploy_configs) if deploy_configs else []
actions = deepcopy(actions) if actions else {}
names = names or []
if deploy_all:
app.console.print(
"Deploying all flows with an existing deployment configuration..."
)
else:
app.console.print("Deploying flows with selected deployment configurations...")
for deploy_config in deploy_configs:
if deploy_config.get("name") is None:
if not is_interactive():
app.console.print(
"Discovered unnamed deployment. Skipping...", style="yellow"
)
continue
app.console.print("Discovered unnamed deployment.", style="yellow")
app.console.print_json(data=deploy_config)
if confirm(
"Would you like to give this deployment a name and deploy it?",
default=True,
console=app.console,
):
deploy_config["name"] = prompt("Deployment name", default="default")
else:
app.console.print("Skipping unnamed deployment.", style="yellow")
continue
app.console.print(Panel(f"Deploying {deploy_config['name']}", style="blue"))
await _run_single_deploy(deploy_config, actions, prefect_file=prefect_file)
def _construct_schedules(
deploy_config: Dict,
) -> List[MinimalDeploymentSchedule]:
"""
Constructs a schedule from a deployment configuration.
Args:
deploy_config: A deployment configuration
Returns:
A list of schedule objects
"""
schedule_configs = deploy_config.get("schedules", NotSet)
if schedule_configs is not NotSet:
schedules = [
_schedule_config_to_deployment_schedule(schedule_config)
for schedule_config in schedule_configs
]
elif schedule_configs is NotSet:
if is_interactive():
schedules = prompt_schedules(app.console)
else:
schedules = []
return schedules
def _schedule_config_to_deployment_schedule(
schedule_config: Dict,
) -> MinimalDeploymentSchedule:
cron = schedule_config.get("cron")
interval = schedule_config.get("interval")
anchor_date = schedule_config.get("anchor_date")
rrule = schedule_config.get("rrule")
timezone = schedule_config.get("timezone")
schedule_active = schedule_config.get("active", True)
if cron:
cron_kwargs = {"cron": cron, "timezone": timezone}
schedule = CronSchedule(
**{k: v for k, v in cron_kwargs.items() if v is not None}
)
elif interval:
interval_kwargs = {
"interval": timedelta(seconds=interval),
"anchor_date": anchor_date,
"timezone": timezone,
}
schedule = IntervalSchedule(
**{k: v for k, v in interval_kwargs.items() if v is not None}
)
elif rrule:
try:
schedule = RRuleSchedule(**json.loads(rrule))
if timezone:
# override timezone if specified via CLI argument
schedule.timezone = timezone
except json.JSONDecodeError:
schedule = RRuleSchedule(rrule=rrule, timezone=timezone)
else:
raise ValueError(
f"Unknown schedule type. Please provide a valid schedule. schedule={schedule_config}"
)
return MinimalDeploymentSchedule(schedule=schedule, active=schedule_active)
def _merge_with_default_deploy_config(deploy_config: Dict):
"""
Merge a base deploy config with the default deploy config.
If a key is missing in the base deploy config, it will be filled with the
corresponding value from the default deploy config.
Parameters:
deploy_config: The base deploy config to be merged with
the default deploy config.
Returns:
The merged deploy config.
"""
deploy_config = deepcopy(deploy_config)
DEFAULT_DEPLOY_CONFIG = {
"name": None,
"version": None,
"tags": [],
"description": None,
"flow_name": None,
"entrypoint": None,
"parameters": {},
"work_pool": {
"name": None,
"work_queue_name": None,
"job_variables": {},
},
}
# merge default and base deploy configs
# this allows for missing keys in a user's deploy config
for key, value in DEFAULT_DEPLOY_CONFIG.items():
if key not in deploy_config:
deploy_config[key] = value
if isinstance(value, dict):
for k, v in value.items():
if k not in deploy_config[key]:
deploy_config[key][k] = v
return deploy_config
async def _generate_git_clone_pull_step(
console: Console,
deploy_config: Dict,
remote_url: str,
):
branch = _get_git_branch() or "main"
if not remote_url:
remote_url = prompt(
"Please enter the URL to pull your flow code from", console=console
)
elif not confirm(
f"Is [green]{remote_url}[/] the correct URL to pull your flow code from?",
default=True,
console=console,
):
remote_url = prompt(
"Please enter the URL to pull your flow code from", console=console
)
if not confirm(
f"Is [green]{branch}[/] the correct branch to pull your flow code from?",
default=True,
console=console,
):
branch = prompt(
"Please enter the branch to pull your flow code from",
default="main",
console=console,
)
token_secret_block_name = None
if confirm("Is this a private repository?", console=console):
token_secret_block_name = f"deployment-{slugify(deploy_config['name'])}-{slugify(deploy_config['flow_name'])}-repo-token"
create_new_block = False
prompt_message = (
"Please enter a token that can be used to access your private"
" repository. This token will be saved as a secret via the Prefect API"
)
try:
await Secret.load(token_secret_block_name)
if not confirm(
(
"We found an existing token saved for this deployment. Would"
" you like use the existing token?"
),
default=True,
console=console,
):