forked from Azure/azure-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom.py
More file actions
5249 lines (4313 loc) · 249 KB
/
custom.py
File metadata and controls
5249 lines (4313 loc) · 249 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long, consider-using-f-string, logging-format-interpolation, inconsistent-return-statements, broad-except, bare-except, too-many-statements, too-many-locals, too-many-boolean-expressions, too-many-branches, too-many-nested-blocks, pointless-statement, expression-not-assigned, unbalanced-tuple-unpacking, unsupported-assignment-operation
# pylint: disable=unused-argument, no-else-raise
from copy import deepcopy
import json
import threading
import sys
import time
from urllib.parse import urlparse
import requests
from azure.cli.core.azclierror import (
RequiredArgumentMissingError,
ValidationError,
ResourceNotFoundError,
CLIError,
CLIInternalError,
InvalidArgumentValueError,
ArgumentUsageError,
MutuallyExclusiveArgumentError)
from azure.cli.core.commands.client_factory import get_subscription_id
from azure.cli.core.util import open_page_in_browser
from azure.mgmt.core.tools import parse_resource_id, is_valid_resource_id
from knack.log import get_logger
from knack.prompting import prompt_y_n, prompt as prompt_str
from msrest.exceptions import DeserializationError
from .containerapp_job_decorator import ContainerAppJobDecorator, ContainerAppJobCreateDecorator
from .containerapp_env_decorator import ContainerAppEnvDecorator, ContainerAppEnvCreateDecorator, ContainerAppEnvUpdateDecorator
from .containerapp_auth_decorator import ContainerAppAuthDecorator
from .containerapp_decorator import ContainerAppCreateDecorator, BaseContainerAppDecorator
from ._client_factory import handle_raw_exception, handle_non_resource_not_found_exception, \
handle_non_404_status_code_exception
from ._clients import (
ManagedEnvironmentClient,
ContainerAppClient,
GitHubActionClient,
DaprComponentClient,
StorageClient,
AuthClient,
WorkloadProfileClient,
ContainerAppsJobClient,
HttpRouteConfigClient,
SubscriptionClient
)
from ._github_oauth import get_github_access_token
from ._models import (
JobExecutionTemplate as JobExecutionTemplateModel,
RegistryCredentials as RegistryCredentialsModel,
ContainerResources as ContainerResourcesModel,
Scale as ScaleModel,
Container as ContainerModel,
GitHubActionConfiguration,
RegistryInfo as RegistryInfoModel,
AzureCredentials as AzureCredentialsModel,
SourceControl as SourceControlModel,
ContainerAppCertificateEnvelope as ContainerAppCertificateEnvelopeModel,
ContainerAppCustomDomain as ContainerAppCustomDomainModel,
AzureFileProperties as AzureFilePropertiesModel,
ScaleRule as ScaleRuleModel,
Volume as VolumeModel,
VolumeMount as VolumeMountModel)
from ._utils import (_validate_subscription_registered,
parse_secret_flags, store_as_secret_and_return_secret_ref, parse_env_var_flags,
_get_existing_secrets, _convert_object_from_snake_to_camel_case,
_object_to_dict, _add_or_update_secrets, _remove_additional_attributes, _remove_readonly_attributes,
_add_or_update_env_vars, _add_or_update_tags, _update_revision_weights, _append_label_weights,
_get_app_from_revision, raise_missing_token_suggestion, _remove_registry_secret, _remove_secret,
_ensure_identity_resource_id, _remove_dapr_readonly_attributes, _remove_env_vars, _validate_traffic_sum,
_update_revision_env_secretrefs, _get_acr_cred, safe_get, await_github_action, repo_url_to_name,
validate_container_app_name, _update_weights, register_provider_if_needed,
generate_randomized_cert_name, _get_name, load_cert_file, check_cert_name_availability,
validate_hostname, patch_new_custom_domain, get_custom_domains, _validate_revision_name, set_managed_identity,
is_registry_msi_system, clean_null_values, _populate_secret_values,
safe_set, parse_metadata_flags, parse_auth_flags, set_ip_restrictions, certificate_matches,
ensure_workload_profile_supported, _generate_secret_volume_name,
trigger_workflow, AppType,
format_location, certificate_location_matches, generate_randomized_managed_cert_name,
check_managed_cert_name_availability, prepare_managed_certificate_envelop)
from ._validators import validate_revision_suffix
from ._ssh_utils import (SSH_DEFAULT_ENCODING, WebSocketConnection, read_ssh, get_stdin_writer, SSH_CTRL_C_MSG,
SSH_BACKUP_ENCODING)
from ._constants import (MICROSOFT_SECRET_SETTING_NAME, FACEBOOK_SECRET_SETTING_NAME, GITHUB_SECRET_SETTING_NAME,
GOOGLE_SECRET_SETTING_NAME, TWITTER_SECRET_SETTING_NAME, APPLE_SECRET_SETTING_NAME, CONTAINER_APPS_RP,
NAME_INVALID, NAME_ALREADY_EXISTS, ACR_IMAGE_SUFFIX, HELLO_WORLD_IMAGE, LOG_TYPE_SYSTEM, LOG_TYPE_CONSOLE,
MANAGED_CERTIFICATE_RT, PRIVATE_CERTIFICATE_RT, PENDING_STATUS, SUCCEEDED_STATUS, CONTAINER_APPS_SDK_MODELS,
BLOB_STORAGE_TOKEN_STORE_SECRET_SETTING_NAME, DEFAULT_PORT)
from .containerapp_job_registry_decorator import ContainerAppJobRegistryDecorator, ContainerAppJobRegistrySetDecorator, \
ContainerAppJobRegistryRemoveDecorator
logger = get_logger(__name__)
# These properties should be under the "properties" attribute. Move the properties under "properties" attribute
def process_loaded_yaml(yaml_containerapp):
if not isinstance(yaml_containerapp, dict): # pylint: disable=unidiomatic-typecheck
raise ValidationError('Invalid YAML provided. Please see https://aka.ms/azure-container-apps-yaml for a valid containerapps YAML spec.')
if not yaml_containerapp.get('properties'):
yaml_containerapp['properties'] = {}
if yaml_containerapp.get('identity') and yaml_containerapp['identity'].get('userAssignedIdentities'):
for identity in yaml_containerapp['identity']['userAssignedIdentities']:
# properties (principalId and clientId) are readonly and create (PUT) will throw error if they are provided
# Update (PATCH) ignores them so it's okay to remove them as well
yaml_containerapp['identity']['userAssignedIdentities'][identity] = {}
nested_properties = ["provisioningState",
"managedEnvironmentId",
"environmentId",
"latestRevisionName",
"latestRevisionFqdn",
"customDomainVerificationId",
"configuration",
"template",
"outboundIPAddresses",
"workloadProfileName",
"latestReadyRevisionName",
"eventStreamEndpoint"]
for nested_property in nested_properties:
tmp = yaml_containerapp.get(nested_property)
if nested_property in yaml_containerapp:
yaml_containerapp['properties'][nested_property] = tmp
del yaml_containerapp[nested_property]
if "managedEnvironmentId" in yaml_containerapp['properties']:
tmp = yaml_containerapp['properties']['managedEnvironmentId']
if tmp:
yaml_containerapp['properties']["environmentId"] = tmp
del yaml_containerapp['properties']['managedEnvironmentId']
return yaml_containerapp
def load_yaml_file(file_name):
import yaml
import errno
try:
with open(file_name) as stream: # pylint: disable=unspecified-encoding
return yaml.safe_load(stream.read().replace('\x00', ''))
except OSError as ex:
if getattr(ex, 'errno', 0) == errno.ENOENT:
raise ValidationError('{} does not exist'.format(file_name)) from ex
raise
except (yaml.parser.ParserError, UnicodeDecodeError) as ex:
raise ValidationError('Error parsing {} ({})'.format(file_name, str(ex))) from ex
def create_deserializer():
from ._sdk_models import ContainerApp # pylint: disable=unused-import
from msrest import Deserializer
import inspect
sdkClasses = inspect.getmembers(sys.modules[CONTAINER_APPS_SDK_MODELS])
deserializer = {}
for sdkClass in sdkClasses:
deserializer[sdkClass[0]] = sdkClass[1]
return Deserializer(deserializer)
def update_containerapp_yaml(cmd, name, resource_group_name, file_name, from_revision=None, no_wait=False):
yaml_containerapp = process_loaded_yaml(load_yaml_file(file_name))
if not yaml_containerapp.get('name'):
yaml_containerapp['name'] = name
elif yaml_containerapp.get('name').lower() != name.lower():
logger.warning('The app name provided in the --yaml file "{}" does not match the one provided in the --name flag "{}". The one provided in the --yaml file will be used.'.format(yaml_containerapp.get('name'), name))
name = yaml_containerapp.get('name')
if not yaml_containerapp.get('type'):
yaml_containerapp['type'] = 'Microsoft.App/containerApps'
elif yaml_containerapp.get('type').lower() != "microsoft.app/containerapps":
raise ValidationError('Containerapp type must be \"Microsoft.App/ContainerApps\"')
containerapp_def = None
# Check if containerapp exists
try:
containerapp_def = ContainerAppClient.show(cmd=cmd, resource_group_name=resource_group_name, name=name)
except Exception:
pass
if not containerapp_def:
raise ValidationError("The containerapp '{}' does not exist".format(name))
existed_environment_id = containerapp_def['properties']['environmentId']
containerapp_def = None
# Deserialize the yaml into a ContainerApp object. Need this since we're not using SDK
try:
deserializer = create_deserializer()
containerapp_def = deserializer('ContainerApp', yaml_containerapp)
except DeserializationError as ex:
raise ValidationError('Invalid YAML provided. Please see https://aka.ms/azure-container-apps-yaml for a valid containerapps YAML spec.') from ex
# Remove tags before converting from snake case to camel case, then re-add tags. We don't want to change the case of the tags. Need this since we're not using SDK
tags = None
if yaml_containerapp.get('tags'):
tags = yaml_containerapp.get('tags')
del yaml_containerapp['tags']
containerapp_def = _convert_object_from_snake_to_camel_case(_object_to_dict(containerapp_def))
containerapp_def['tags'] = tags
# After deserializing, some properties may need to be moved under the "properties" attribute. Need this since we're not using SDK
containerapp_def = process_loaded_yaml(containerapp_def)
# Change which revision we update from
if from_revision:
r = ContainerAppClient.show_revision(cmd=cmd, resource_group_name=resource_group_name, container_app_name=name, name=from_revision)
_update_revision_env_secretrefs(r["properties"]["template"]["containers"], name)
containerapp_def["properties"]["template"] = r["properties"]["template"]
# Remove "additionalProperties" and read-only attributes that are introduced in the deserialization. Need this since we're not using SDK
_remove_additional_attributes(containerapp_def)
_remove_readonly_attributes(containerapp_def)
secret_values = list_secrets(cmd=cmd, name=name, resource_group_name=resource_group_name, show_values=True)
_populate_secret_values(containerapp_def, secret_values)
# Clean null values since this is an update
containerapp_def = clean_null_values(containerapp_def)
# Fix bug with revisionSuffix when containers are added
if not safe_get(containerapp_def, "properties", "template", "revisionSuffix"):
if "properties" not in containerapp_def:
containerapp_def["properties"] = {}
if "template" not in containerapp_def["properties"]:
containerapp_def["properties"]["template"] = {}
containerapp_def["properties"]["template"]["revisionSuffix"] = None
# Remove the environmentId in the PATCH payload if it has not been changed
if safe_get(containerapp_def, "properties", "environmentId") and safe_get(containerapp_def, "properties", "environmentId").lower() == existed_environment_id.lower():
del containerapp_def["properties"]['environmentId']
try:
r = ContainerAppClient.update(
cmd=cmd, resource_group_name=resource_group_name, name=name, container_app_envelope=containerapp_def, no_wait=no_wait)
if not no_wait and "properties" in r and "provisioningState" in r["properties"] and r["properties"]["provisioningState"].lower() == "waiting":
logger.warning('Containerapp creation in progress. Please monitor the creation using `az containerapp show -n {} -g {}`'.format(
name, resource_group_name
))
return r
except Exception as e:
handle_raw_exception(e)
def create_containerapp(cmd,
name,
resource_group_name,
yaml=None,
image=None,
container_name=None,
managed_env=None,
min_replicas=None,
max_replicas=None,
scale_rule_name=None,
scale_rule_type=None,
scale_rule_http_concurrency=None,
scale_rule_metadata=None,
scale_rule_auth=None,
target_port=None,
exposed_port=None,
transport="auto",
ingress=None,
allow_insecure=False,
revisions_mode="single",
secrets=None,
env_vars=None,
cpu=None,
memory=None,
registry_server=None,
registry_user=None,
registry_pass=None,
dapr_enabled=False,
dapr_app_port=None,
dapr_app_id=None,
dapr_app_protocol=None,
dapr_http_read_buffer_size=None,
dapr_http_max_request_size=None,
dapr_log_level=None,
dapr_enable_api_logging=False,
revision_suffix=None,
startup_command=None,
args=None,
tags=None,
no_wait=False,
system_assigned=False,
disable_warnings=False,
user_assigned=None,
registry_identity=None,
workload_profile_name=None,
termination_grace_period=None,
secret_volume_mount=None):
raw_parameters = locals()
containerapp_create_decorator = ContainerAppCreateDecorator(
cmd=cmd,
client=ContainerAppClient,
raw_parameters=raw_parameters,
models=CONTAINER_APPS_SDK_MODELS
)
containerapp_create_decorator.register_provider(CONTAINER_APPS_RP)
containerapp_create_decorator.validate_arguments()
containerapp_create_decorator.construct_payload()
r = containerapp_create_decorator.create()
containerapp_create_decorator.construct_for_post_process(r)
r = containerapp_create_decorator.post_process(r)
return r
def update_containerapp_logic(cmd,
name,
resource_group_name,
yaml=None,
image=None,
container_name=None,
min_replicas=None,
max_replicas=None,
scale_rule_name=None,
scale_rule_type="http",
scale_rule_http_concurrency=None,
scale_rule_metadata=None,
scale_rule_auth=None,
set_env_vars=None,
remove_env_vars=None,
replace_env_vars=None,
remove_all_env_vars=False,
cpu=None,
memory=None,
revision_suffix=None,
startup_command=None,
args=None,
tags=None,
no_wait=False,
from_revision=None,
ingress=None,
target_port=None,
workload_profile_name=None,
termination_grace_period=None,
registry_server=None,
registry_user=None,
registry_pass=None,
secret_volume_mount=None):
_validate_subscription_registered(cmd, CONTAINER_APPS_RP)
validate_revision_suffix(revision_suffix)
# Validate that max_replicas is set to 0-1000
if max_replicas is not None:
if max_replicas < 1 or max_replicas > 1000:
raise ArgumentUsageError('--max-replicas must be in the range [1,1000]')
if yaml:
if image or min_replicas or max_replicas or\
set_env_vars or remove_env_vars or replace_env_vars or remove_all_env_vars or cpu or memory or\
startup_command or args or tags:
logger.warning('Additional flags were passed along with --yaml. These flags will be ignored, and the configuration defined in the yaml will be used instead')
return update_containerapp_yaml(cmd=cmd, name=name, resource_group_name=resource_group_name, file_name=yaml, no_wait=no_wait, from_revision=from_revision)
containerapp_def = None
try:
containerapp_def = ContainerAppClient.show(cmd=cmd, resource_group_name=resource_group_name, name=name)
except Exception as e:
handle_non_404_status_code_exception(e)
if not containerapp_def:
raise ResourceNotFoundError("The containerapp '{}' does not exist".format(name))
new_containerapp = {}
new_containerapp["properties"] = {}
if from_revision:
try:
r = ContainerAppClient.show_revision(cmd=cmd, resource_group_name=resource_group_name, container_app_name=name, name=from_revision)
except CLIError as e:
# Error handle the case where revision not found?
handle_raw_exception(e)
_update_revision_env_secretrefs(r["properties"]["template"]["containers"], name)
new_containerapp["properties"]["template"] = r["properties"]["template"]
# Doing this while API has bug. If env var is an empty string, API doesn't return "value" even though the "value" should be an empty string
for container in safe_get(containerapp_def, "properties", "template", "containers", default=[]):
if "env" in container:
for e in container["env"]:
if "value" not in e:
e["value"] = ""
update_map = {}
update_map['scale'] = min_replicas is not None or max_replicas is not None or scale_rule_name
update_map['container'] = image or container_name or set_env_vars is not None or remove_env_vars is not None or replace_env_vars is not None or remove_all_env_vars or cpu or memory or startup_command is not None or args is not None or secret_volume_mount is not None
update_map['ingress'] = ingress or target_port
update_map['registry'] = registry_server or registry_user or registry_pass
if tags:
_add_or_update_tags(new_containerapp, tags)
if revision_suffix is not None:
new_containerapp["properties"]["template"] = {} if "template" not in new_containerapp["properties"] else new_containerapp["properties"]["template"]
new_containerapp["properties"]["template"]["revisionSuffix"] = revision_suffix
if termination_grace_period is not None:
safe_set(new_containerapp, "properties", "template", "terminationGracePeriodSeconds", value=termination_grace_period)
if workload_profile_name:
new_containerapp["properties"]["workloadProfileName"] = workload_profile_name
parsed_managed_env = parse_resource_id(containerapp_def["properties"]["managedEnvironmentId"])
managed_env_name = parsed_managed_env['name']
managed_env_rg = parsed_managed_env['resource_group']
managed_env_info = None
try:
managed_env_info = ManagedEnvironmentClient.show(cmd=cmd, resource_group_name=managed_env_rg, name=managed_env_name)
except:
pass
if not managed_env_info:
raise ValidationError("Error parsing the managed environment '{}' from the specified containerapp".format(managed_env_name))
ensure_workload_profile_supported(cmd, managed_env_name, managed_env_rg, workload_profile_name, managed_env_info)
# Containers
if update_map["container"]:
new_containerapp["properties"]["template"] = {} if "template" not in new_containerapp["properties"] else new_containerapp["properties"]["template"]
new_containerapp["properties"]["template"]["containers"] = containerapp_def["properties"]["template"]["containers"]
if not container_name:
if len(new_containerapp["properties"]["template"]["containers"]) == 1:
container_name = new_containerapp["properties"]["template"]["containers"][0]["name"]
else:
raise ValidationError("Usage error: --container-name is required when adding or updating a container")
# Check if updating existing container
updating_existing_container = False
for c in new_containerapp["properties"]["template"]["containers"]:
if c["name"].lower() == container_name.lower():
updating_existing_container = True
if image is not None:
c["image"] = image
if set_env_vars is not None:
if "env" not in c or not c["env"]:
c["env"] = []
# env vars
_add_or_update_env_vars(c["env"], parse_env_var_flags(set_env_vars))
if replace_env_vars is not None:
# Remove other existing env_vars, then add them
c["env"] = []
_add_or_update_env_vars(c["env"], parse_env_var_flags(replace_env_vars))
if remove_env_vars is not None:
if "env" not in c or not c["env"]:
c["env"] = []
# env vars
_remove_env_vars(c["env"], remove_env_vars)
if remove_all_env_vars:
c["env"] = []
if startup_command is not None:
if isinstance(startup_command, list) and not startup_command:
c["command"] = None
else:
c["command"] = startup_command
if args is not None:
if isinstance(args, list) and not args:
c["args"] = None
else:
c["args"] = args
if cpu is not None or memory is not None:
if "resources" in c and c["resources"]:
if cpu is not None:
c["resources"]["cpu"] = cpu
if memory is not None:
c["resources"]["memory"] = memory
else:
c["resources"] = {
"cpu": cpu,
"memory": memory
}
if secret_volume_mount is not None:
new_containerapp["properties"]["template"]["volumes"] = containerapp_def["properties"]["template"]["volumes"]
if "volumeMounts" not in c or not c["volumeMounts"]:
# if no volume mount exists, create a new volume and then mount
volume_def = VolumeModel
volume_mount_def = VolumeMountModel
volume_def["name"] = _generate_secret_volume_name()
volume_def["storageType"] = "Secret"
volume_mount_def["volumeName"] = volume_def["name"]
volume_mount_def["mountPath"] = secret_volume_mount
if "volumes" not in new_containerapp["properties"]["template"] or new_containerapp["properties"]["template"]["volumes"] is None:
new_containerapp["properties"]["template"]["volumes"] = [volume_def]
else:
new_containerapp["properties"]["template"]["volumes"].append(volume_def)
c["volumeMounts"] = [volume_mount_def]
else:
if len(c["volumeMounts"]) > 1:
raise ValidationError("Usage error: --secret-volume-mount can only be used with a container that has a single volume mount, to define multiple volumes and mounts please use --yaml")
else:
# check that the only volume is of type secret
volume_name = c["volumeMounts"][0]["volumeName"]
for v in new_containerapp["properties"]["template"]["volumes"]:
if v["name"].lower() == volume_name.lower():
if v["storageType"] != "Secret":
raise ValidationError("Usage error: --secret-volume-mount can only be used to update volume mounts with volumes of type secret. To update other types of volumes please use --yaml")
break
c["volumeMounts"][0]["mountPath"] = secret_volume_mount
# If not updating existing container, add as new container
if not updating_existing_container:
if image is None:
raise ValidationError("Usage error: --image is required when adding a new container")
resources_def = None
if cpu is not None or memory is not None:
resources_def = ContainerResourcesModel
resources_def["cpu"] = cpu
resources_def["memory"] = memory
container_def = ContainerModel
container_def["name"] = container_name
container_def["image"] = image
container_def["env"] = []
if set_env_vars is not None:
# env vars
_add_or_update_env_vars(container_def["env"], parse_env_var_flags(set_env_vars))
if replace_env_vars is not None:
# env vars
_add_or_update_env_vars(container_def["env"], parse_env_var_flags(replace_env_vars))
if remove_env_vars is not None:
# env vars
_remove_env_vars(container_def["env"], remove_env_vars)
if remove_all_env_vars:
container_def["env"] = []
if startup_command is not None:
if isinstance(startup_command, list) and not startup_command:
container_def["command"] = None
else:
container_def["command"] = startup_command
if args is not None:
if isinstance(args, list) and not args:
container_def["args"] = None
else:
container_def["args"] = args
if resources_def is not None:
container_def["resources"] = resources_def
if secret_volume_mount is not None:
new_containerapp["properties"]["template"]["volumes"] = containerapp_def["properties"]["template"]["volumes"]
# generate a new volume name
volume_def = VolumeModel
volume_mount_def = VolumeMountModel
volume_def["name"] = _generate_secret_volume_name()
volume_def["storageType"] = "Secret"
# mount the volume to the container
volume_mount_def["volumeName"] = volume_def["name"]
volume_mount_def["mountPath"] = secret_volume_mount
container_def["volumeMounts"] = [volume_mount_def]
if "volumes" not in new_containerapp["properties"]["template"]:
new_containerapp["properties"]["template"]["volumes"] = [volume_def]
else:
new_containerapp["properties"]["template"]["volumes"].append(volume_def)
new_containerapp["properties"]["template"]["containers"].append(container_def)
# Scale
if update_map["scale"]:
new_containerapp["properties"]["template"] = {} if "template" not in new_containerapp["properties"] else new_containerapp["properties"]["template"]
if "scale" not in new_containerapp["properties"]["template"]:
new_containerapp["properties"]["template"]["scale"] = {}
if min_replicas is not None:
new_containerapp["properties"]["template"]["scale"]["minReplicas"] = min_replicas
if max_replicas is not None:
new_containerapp["properties"]["template"]["scale"]["maxReplicas"] = max_replicas
scale_def = None
if min_replicas is not None or max_replicas is not None:
scale_def = ScaleModel
scale_def["minReplicas"] = min_replicas
scale_def["maxReplicas"] = max_replicas
# so we don't overwrite rules
if safe_get(new_containerapp, "properties", "template", "scale", "rules"):
new_containerapp["properties"]["template"]["scale"].pop("rules")
if scale_rule_name:
if not scale_rule_type:
scale_rule_type = "http"
scale_rule_type = scale_rule_type.lower()
scale_rule_def = ScaleRuleModel
curr_metadata = {}
if scale_rule_http_concurrency:
if scale_rule_type == 'http':
curr_metadata["concurrentRequests"] = str(scale_rule_http_concurrency)
elif scale_rule_type == 'tcp':
curr_metadata["concurrentConnections"] = str(scale_rule_http_concurrency)
metadata_def = parse_metadata_flags(scale_rule_metadata, curr_metadata)
auth_def = parse_auth_flags(scale_rule_auth)
if scale_rule_type == "http":
scale_rule_def["name"] = scale_rule_name
scale_rule_def["custom"] = None
scale_rule_def["tcp"] = None
scale_rule_def["http"] = {}
scale_rule_def["http"]["metadata"] = metadata_def
scale_rule_def["http"]["auth"] = auth_def
elif scale_rule_type == "tcp":
scale_rule_def["name"] = scale_rule_name
scale_rule_def["custom"] = None
scale_rule_def["http"] = None
scale_rule_def["tcp"] = {}
scale_rule_def["tcp"]["metadata"] = metadata_def
scale_rule_def["tcp"]["auth"] = auth_def
else:
scale_rule_def["name"] = scale_rule_name
scale_rule_def["http"] = None
scale_rule_def["tcp"] = None
scale_rule_def["custom"] = {}
scale_rule_def["custom"]["type"] = scale_rule_type
scale_rule_def["custom"]["metadata"] = metadata_def
scale_rule_def["custom"]["auth"] = auth_def
if not scale_def:
scale_def = ScaleModel
scale_def["rules"] = [scale_rule_def]
new_containerapp["properties"]["template"]["scale"]["rules"] = scale_def["rules"]
# Ingress
if update_map["ingress"]:
new_containerapp["properties"]["configuration"] = {} if "configuration" not in new_containerapp["properties"] else new_containerapp["properties"]["configuration"]
if target_port is not None or ingress is not None:
new_containerapp["properties"]["configuration"]["ingress"] = {}
if ingress:
new_containerapp["properties"]["configuration"]["ingress"]["external"] = ingress.lower() == "external"
if target_port:
new_containerapp["properties"]["configuration"]["ingress"]["targetPort"] = target_port
# Registry
if update_map["registry"]:
new_containerapp["properties"]["configuration"] = {} if "configuration" not in new_containerapp["properties"] else new_containerapp["properties"]["configuration"]
if "registries" in containerapp_def["properties"]["configuration"]:
new_containerapp["properties"]["configuration"]["registries"] = containerapp_def["properties"]["configuration"]["registries"]
if "registries" not in containerapp_def["properties"]["configuration"] or containerapp_def["properties"]["configuration"]["registries"] is None:
new_containerapp["properties"]["configuration"]["registries"] = []
registries_def = new_containerapp["properties"]["configuration"]["registries"]
_get_existing_secrets(cmd, resource_group_name, name, containerapp_def)
if "secrets" in containerapp_def["properties"]["configuration"] and containerapp_def["properties"]["configuration"]["secrets"]:
new_containerapp["properties"]["configuration"]["secrets"] = containerapp_def["properties"]["configuration"]["secrets"]
else:
new_containerapp["properties"]["configuration"]["secrets"] = []
if registry_server:
if not registry_pass or not registry_user:
if ACR_IMAGE_SUFFIX not in registry_server:
raise RequiredArgumentMissingError('Registry url is required if using Azure Container Registry, otherwise Registry username and password are required if using Dockerhub')
logger.warning('No credential was provided to access Azure Container Registry. Trying to look up...')
parsed = urlparse(registry_server)
registry_name = (parsed.netloc if parsed.scheme else parsed.path).split('.')[0]
registry_user, registry_pass, _ = _get_acr_cred(cmd.cli_ctx, registry_name)
# Check if updating existing registry
updating_existing_registry = False
for r in registries_def:
if r['server'].lower() == registry_server.lower():
updating_existing_registry = True
if registry_user:
r["username"] = registry_user
if registry_pass:
r["passwordSecretRef"] = store_as_secret_and_return_secret_ref(
new_containerapp["properties"]["configuration"]["secrets"],
r["username"],
r["server"],
registry_pass,
update_existing_secret=True,
disable_warnings=True)
# If not updating existing registry, add as new registry
if not updating_existing_registry:
registry = RegistryCredentialsModel
registry["server"] = registry_server
registry["username"] = registry_user
registry["passwordSecretRef"] = store_as_secret_and_return_secret_ref(
new_containerapp["properties"]["configuration"]["secrets"],
registry_user,
registry_server,
registry_pass,
update_existing_secret=True,
disable_warnings=True)
registries_def.append(registry)
if not revision_suffix:
new_containerapp["properties"]["template"] = {} if "template" not in new_containerapp["properties"] else new_containerapp["properties"]["template"]
new_containerapp["properties"]["template"]["revisionSuffix"] = None
try:
r = ContainerAppClient.update(
cmd=cmd, resource_group_name=resource_group_name, name=name, container_app_envelope=new_containerapp, no_wait=no_wait)
if not no_wait and "properties" in r and "provisioningState" in r["properties"] and r["properties"]["provisioningState"].lower() == "waiting":
logger.warning('Containerapp update in progress. Please monitor the update using `az containerapp show -n {} -g {}`'.format(name, resource_group_name))
return r
except Exception as e:
handle_raw_exception(e)
def update_containerapp(cmd,
name,
resource_group_name,
yaml=None,
image=None,
container_name=None,
min_replicas=None,
max_replicas=None,
scale_rule_name=None,
scale_rule_type=None,
scale_rule_http_concurrency=None,
scale_rule_metadata=None,
scale_rule_auth=None,
set_env_vars=None,
remove_env_vars=None,
replace_env_vars=None,
remove_all_env_vars=False,
cpu=None,
memory=None,
revision_suffix=None,
startup_command=None,
args=None,
tags=None,
workload_profile_name=None,
termination_grace_period=None,
no_wait=False,
secret_volume_mount=None):
_validate_subscription_registered(cmd, CONTAINER_APPS_RP)
return update_containerapp_logic(cmd=cmd,
name=name,
resource_group_name=resource_group_name,
yaml=yaml,
image=image,
container_name=container_name,
min_replicas=min_replicas,
max_replicas=max_replicas,
scale_rule_name=scale_rule_name,
scale_rule_type=scale_rule_type,
scale_rule_http_concurrency=scale_rule_http_concurrency,
scale_rule_metadata=scale_rule_metadata,
scale_rule_auth=scale_rule_auth,
set_env_vars=set_env_vars,
remove_env_vars=remove_env_vars,
replace_env_vars=replace_env_vars,
remove_all_env_vars=remove_all_env_vars,
cpu=cpu,
memory=memory,
revision_suffix=revision_suffix,
startup_command=startup_command,
args=args,
tags=tags,
workload_profile_name=workload_profile_name,
termination_grace_period=termination_grace_period,
no_wait=no_wait,
secret_volume_mount=secret_volume_mount)
def show_containerapp(cmd, name, resource_group_name, show_secrets=False):
raw_parameters = locals()
containerapp_base_decorator = BaseContainerAppDecorator(
cmd=cmd,
client=ContainerAppClient,
raw_parameters=raw_parameters,
models=CONTAINER_APPS_SDK_MODELS
)
containerapp_base_decorator.validate_subscription_registered(CONTAINER_APPS_RP)
return containerapp_base_decorator.show()
def list_containerapp(cmd, resource_group_name=None, managed_env=None):
raw_parameters = locals()
containerapp_list_decorator = BaseContainerAppDecorator(
cmd=cmd,
client=ContainerAppClient,
raw_parameters=raw_parameters,
models=CONTAINER_APPS_SDK_MODELS
)
containerapp_list_decorator.validate_subscription_registered(CONTAINER_APPS_RP)
return containerapp_list_decorator.list()
def show_custom_domain_verification_id(cmd):
_validate_subscription_registered(cmd, CONTAINER_APPS_RP)
try:
r = SubscriptionClient.show_custom_domain_verification_id(cmd)
return r
except CLIError as e:
handle_raw_exception(e)
def list_usages(cmd, location):
_validate_subscription_registered(cmd, CONTAINER_APPS_RP)
try:
r = SubscriptionClient.list_usages(cmd, location)
return r
except CLIError as e:
handle_raw_exception(e)
def list_environment_usages(cmd, resource_group_name, name):
_validate_subscription_registered(cmd, CONTAINER_APPS_RP)
try:
r = ManagedEnvironmentClient.list_usages(cmd, resource_group_name, name)
return r
except CLIError as e:
handle_raw_exception(e)
def delete_containerapp(cmd, name, resource_group_name, no_wait=False):
raw_parameters = locals()
containerapp_base_decorator = BaseContainerAppDecorator(
cmd=cmd,
client=ContainerAppClient,
raw_parameters=raw_parameters,
models=CONTAINER_APPS_SDK_MODELS
)
containerapp_base_decorator.validate_subscription_registered(CONTAINER_APPS_RP)
return containerapp_base_decorator.delete()
def create_managed_environment(cmd,
name,
resource_group_name,
logs_destination="log-analytics",
storage_account=None,
logs_customer_id=None,
logs_key=None,
location=None,
instrumentation_key=None,
dapr_connection_string=None,
infrastructure_subnet_resource_id=None,
docker_bridge_cidr=None,
platform_reserved_cidr=None,
platform_reserved_dns_ip=None,
internal_only=False,
tags=None,
disable_warnings=False,
zone_redundant=False,
hostname=None,
certificate_file=None,
certificate_password=None,
enable_workload_profiles=True,
mtls_enabled=None,
p2p_encryption_enabled=None,
no_wait=False):
raw_parameters = locals()
containerapp_env_create_decorator = ContainerAppEnvCreateDecorator(
cmd=cmd,
client=ManagedEnvironmentClient,
raw_parameters=raw_parameters,
models=CONTAINER_APPS_SDK_MODELS
)
containerapp_env_create_decorator.validate_arguments()
containerapp_env_create_decorator.register_provider(CONTAINER_APPS_RP)
containerapp_env_create_decorator.construct_payload()
r = containerapp_env_create_decorator.create()
r = containerapp_env_create_decorator.post_process(r)
return r
def update_managed_environment(cmd,
name,
resource_group_name,
logs_destination=None,
storage_account=None,
logs_customer_id=None,
logs_key=None,
hostname=None,
certificate_file=None,
certificate_password=None,
tags=None,
workload_profile_type=None,
workload_profile_name=None,
min_nodes=None,
max_nodes=None,
mtls_enabled=None,
p2p_encryption_enabled=None,
dapr_connection_string=None,
no_wait=False):
raw_parameters = locals()
containerapp_env_update_decorator = ContainerAppEnvUpdateDecorator(
cmd=cmd,
client=ManagedEnvironmentClient,
raw_parameters=raw_parameters,
models=CONTAINER_APPS_SDK_MODELS
)
containerapp_env_update_decorator.validate_arguments()
containerapp_env_update_decorator.construct_payload()
r = containerapp_env_update_decorator.update()
r = containerapp_env_update_decorator.post_process(r)
return r
def show_managed_environment(cmd, name, resource_group_name):
raw_parameters = locals()
containerapp_env_decorator = ContainerAppEnvDecorator(
cmd=cmd,
client=ManagedEnvironmentClient,
raw_parameters=raw_parameters,
models=CONTAINER_APPS_SDK_MODELS
)
containerapp_env_decorator.validate_subscription_registered(CONTAINER_APPS_RP)
return containerapp_env_decorator.show()
def list_managed_environments(cmd, resource_group_name=None):
raw_parameters = locals()
containerapp_env_decorator = ContainerAppEnvDecorator(
cmd=cmd,
client=ManagedEnvironmentClient,
raw_parameters=raw_parameters,
models=CONTAINER_APPS_SDK_MODELS
)
containerapp_env_decorator.validate_subscription_registered(CONTAINER_APPS_RP)
return containerapp_env_decorator.list()
def delete_managed_environment(cmd, name, resource_group_name, no_wait=False):
raw_parameters = locals()
containerapp_env_decorator = ContainerAppEnvDecorator(
cmd=cmd,
client=ManagedEnvironmentClient,
raw_parameters=raw_parameters,
models=CONTAINER_APPS_SDK_MODELS
)
containerapp_env_decorator.validate_subscription_registered(CONTAINER_APPS_RP)
return containerapp_env_decorator.delete()
def create_containerappsjob(cmd,
name,
resource_group_name,
yaml=None,
image=None,
container_name=None,
managed_env=None,
trigger_type=None,
replica_timeout=None,
replica_retry_limit=None,
replica_completion_count=None,
parallelism=None,
cron_expression=None,
secrets=None,
env_vars=None,
cpu=None,
memory=None,
registry_server=None,
registry_user=None,
registry_pass=None,
startup_command=None,
args=None,
scale_rule_metadata=None,
scale_rule_name=None,
scale_rule_type=None,
scale_rule_auth=None,
polling_interval=None,
min_executions=None,
max_executions=None,
tags=None,
no_wait=False,
system_assigned=False,
disable_warnings=False,
user_assigned=None,
registry_identity=None,
workload_profile_name=None):
raw_parameters = locals()
containerapp_job_create_decorator = ContainerAppJobCreateDecorator(
cmd=cmd,
client=ContainerAppsJobClient,
raw_parameters=raw_parameters,