diff --git a/src/azure-cli/azure/cli/command_modules/containerapp/_help.py b/src/azure-cli/azure/cli/command_modules/containerapp/_help.py index 6bb700c875c..ca43c3cb704 100644 --- a/src/azure-cli/azure/cli/command_modules/containerapp/_help.py +++ b/src/azure-cli/azure/cli/command_modules/containerapp/_help.py @@ -415,12 +415,28 @@ text: | az containerapp env create -n MyContainerappEnvironment -g MyResourceGroup \\ --location eastus2 --enable-workload-profiles false + - name: Create a workload profiles environment using environment mode. + text: | + az containerapp env create -n MyContainerappEnvironment -g MyResourceGroup \\ + --location eastus2 --environment-mode WorkloadProfiles + - name: Create a consumption-only environment using environment mode. + text: | + az containerapp env create -n MyContainerappEnvironment -g MyResourceGroup \\ + --location eastus2 --environment-mode ConsumptionOnly + - name: Create an Express environment using environment mode. + text: | + az containerapp env create -n MyContainerappEnvironment -g MyResourceGroup \\ + --location eastus2 --environment-mode Express """ helps['containerapp env update'] = """ type: command short-summary: Update a Container Apps environment. + parameters: + - name: --environment-mode + short-summary: Mode of the environment, such as Express, WorkloadProfiles, or ConsumptionOnly. + long-summary: Only the environment mode is changed; existing apps are preserved. The service validates supported mode changes. examples: - name: Update an environment's custom domain configuration. text: | diff --git a/src/azure-cli/azure/cli/command_modules/containerapp/_params.py b/src/azure-cli/azure/cli/command_modules/containerapp/_params.py index b6c5c68ebce..ff3cc81b8c5 100644 --- a/src/azure-cli/azure/cli/command_modules/containerapp/_params.py +++ b/src/azure-cli/azure/cli/command_modules/containerapp/_params.py @@ -186,6 +186,10 @@ def load_arguments(self, _): c.argument('zone_redundant', options_list=["--zone-redundant", "-z"], help="Enable zone redundancy on the environment. Cannot be used without --infrastructure-subnet-resource-id. If used with --location, the subnet's location must match") c.argument('enable_workload_profiles', arg_type=get_three_state_flag(), options_list=["--enable-workload-profiles", "-w"], help="Boolean indicating if the environment is enabled to have workload profiles") + for command in ['containerapp env create', 'containerapp env update']: + with self.argument_context(command) as c: + c.argument('environment_mode', options_list=['--environment-mode'], help="Mode of the environment, such as Express, WorkloadProfiles, or ConsumptionOnly.") + with self.argument_context('containerapp env update') as c: c.argument('name', name_type, help='Name of the Container Apps environment.') c.argument('tags', arg_type=tags_type) diff --git a/src/azure-cli/azure/cli/command_modules/containerapp/_utils.py b/src/azure-cli/azure/cli/command_modules/containerapp/_utils.py index 5cbee92ebeb..61a16baf4c5 100644 --- a/src/azure-cli/azure/cli/command_modules/containerapp/_utils.py +++ b/src/azure-cli/azure/cli/command_modules/containerapp/_utils.py @@ -1749,6 +1749,14 @@ def get_default_workload_profile_name_from_env(cmd, env_def, resource_group): return env_profiles[0]["name"] +def validate_environment_mode_and_workload_profiles_compatible(environment_mode, workload_profiles_enabled): + if environment_mode is not None and workload_profiles_enabled is not None: + if environment_mode.lower() == 'consumptiononly' and workload_profiles_enabled: + raise ValidationError("Cannot use '--enable-workload-profiles' with '--environment-mode ConsumptionOnly'. Please use '--environment-mode' alone.") + if environment_mode.lower() != 'consumptiononly' and not workload_profiles_enabled: + raise ValidationError("Cannot use '--enable-workload-profiles false' with '--environment-mode {}'. Please use '--environment-mode' alone.".format(environment_mode)) + + def get_default_workload_profiles(cmd, location): profiles = [ { diff --git a/src/azure-cli/azure/cli/command_modules/containerapp/containerapp_env_decorator.py b/src/azure-cli/azure/cli/command_modules/containerapp/containerapp_env_decorator.py index bb15639178c..8364899a0d3 100644 --- a/src/azure-cli/azure/cli/command_modules/containerapp/containerapp_env_decorator.py +++ b/src/azure-cli/azure/cli/command_modules/containerapp/containerapp_env_decorator.py @@ -21,6 +21,7 @@ load_cert_file, safe_set, get_default_workload_profiles, + validate_environment_mode_and_workload_profiles_compatible, _azure_monitor_quickstart, safe_get) from ._client_factory import handle_raw_exception, handle_non_404_status_code_exception from .base_resource import BaseResource @@ -114,6 +115,14 @@ def get_argument_min_nodes(self): def get_argument_max_nodes(self): return self.get_param("max_nodes") + def get_argument_environment_mode(self): + return self.get_param("environment_mode") + + def set_up_environment_mode(self): + environment_mode = self.get_argument_environment_mode() + if environment_mode: + safe_set(self.managed_env_def, "properties", "environmentMode", value=environment_mode) + def set_up_peer_to_peer_encryption(self): is_p2p_encryption_enabled = self.get_argument_p2p_encryption_enabled() is_mtls_enabled = self.get_argument_mtls_enabled() @@ -133,10 +142,22 @@ def __init__(self, cmd: AzCliCommand, client: Any, raw_parameters: Dict, models: def get_argument_enable_workload_profiles(self): return self.get_param("enable_workload_profiles") + def get_effective_workload_profiles(self): + environment_mode = self.get_argument_environment_mode() + if environment_mode: + return environment_mode.lower() != "consumptiononly" + return self.get_argument_enable_workload_profiles() + def get_argument_infrastructure_resource_group(self): return self.get_param("infrastructure_resource_group") def validate_arguments(self): + safe_params = self.cmd.cli_ctx.data.get('safe_params', []) + workload_profiles = self.get_argument_enable_workload_profiles() if ( + '-w' in safe_params or '--enable-workload-profiles' in safe_params) else None + validate_environment_mode_and_workload_profiles_compatible( + self.get_argument_environment_mode(), workload_profiles) + location = self.get_argument_location() if self.get_argument_zone_redundant(): if not self.get_argument_infrastructure_subnet_resource_id(): @@ -166,7 +187,10 @@ def validate_arguments(self): if not self.get_argument_infrastructure_subnet_resource_id(): raise RequiredArgumentMissingError("Cannot use --infrastructure-resource-group/-i without " "--infrastructure-subnet-resource-id/-s") - if not self.get_argument_enable_workload_profiles(): + if not self.get_effective_workload_profiles(): + if self.get_argument_environment_mode(): + raise RequiredArgumentMissingError("Cannot use --infrastructure-resource-group/-i with " + "--environment-mode ConsumptionOnly") raise RequiredArgumentMissingError("Cannot use --infrastructure-resource-group/-i without " "--enable-workload-profiles/-w") @@ -197,6 +221,7 @@ def construct_payload(self): self.managed_env_def["properties"]["zoneRedundant"] = self.get_argument_zone_redundant() self.set_up_workload_profiles() + self.set_up_environment_mode() # Custom domains if self.get_argument_hostname(): @@ -221,7 +246,7 @@ def construct_payload(self): self.set_up_infrastructure_resource_group() def set_up_infrastructure_resource_group(self): - if self.get_argument_enable_workload_profiles() and self.get_argument_infrastructure_subnet_resource_id() is not None: + if self.get_effective_workload_profiles() and self.get_argument_infrastructure_subnet_resource_id() is not None: self.managed_env_def["properties"]["InfrastructureResourceGroup"] = self.get_argument_infrastructure_resource_group() def set_up_workload_profiles(self): @@ -233,15 +258,19 @@ def set_up_workload_profiles(self): name=self.get_argument_name()) except Exception as e: handle_non_404_status_code_exception(e) - if self.get_argument_enable_workload_profiles(): + if self.get_effective_workload_profiles(): if existing_environment and safe_get(existing_environment, "properties", "workloadProfiles") is None: # check if input params include -w/--enable-workload-profiles - if self.cmd.cli_ctx.data.get('safe_params') and ('-w' in self.cmd.cli_ctx.data.get( - 'safe_params') or '--enable-workload-profiles' in self.cmd.cli_ctx.data.get('safe_params')): + safe_params = self.cmd.cli_ctx.data.get('safe_params', []) + if self.get_argument_environment_mode() or '-w' in safe_params or '--enable-workload-profiles' in safe_params: raise ValidationError( f"Existing environment {self.get_argument_name()} cannot enable workload profiles. If you want to use Consumption and Dedicated environment, please create a new one.") return + if existing_environment and self.get_argument_environment_mode(): + self.managed_env_def["properties"]["workloadProfiles"] = existing_environment["properties"]["workloadProfiles"] + return + self.managed_env_def["properties"]["workloadProfiles"] = get_default_workload_profiles(self.cmd, self.get_argument_location()) else: if existing_environment and safe_get(existing_environment, "properties", "workloadProfiles") is not None: @@ -332,6 +361,7 @@ def construct_payload(self): # dapr self.set_up_dapr() + self.set_up_environment_mode() def set_up_app_log_configuration(self): logs_destination = self.get_argument_logs_destination() diff --git a/src/azure-cli/azure/cli/command_modules/containerapp/custom.py b/src/azure-cli/azure/cli/command_modules/containerapp/custom.py index 973d6986839..da85df88685 100644 --- a/src/azure-cli/azure/cli/command_modules/containerapp/custom.py +++ b/src/azure-cli/azure/cli/command_modules/containerapp/custom.py @@ -869,7 +869,8 @@ def create_managed_environment(cmd, enable_workload_profiles=True, mtls_enabled=None, p2p_encryption_enabled=None, - no_wait=False): + no_wait=False, + environment_mode=None): raw_parameters = locals() containerapp_env_create_decorator = ContainerAppEnvCreateDecorator( cmd=cmd, @@ -905,7 +906,8 @@ def update_managed_environment(cmd, mtls_enabled=None, p2p_encryption_enabled=None, dapr_connection_string=None, - no_wait=False): + no_wait=False, + environment_mode=None): raw_parameters = locals() containerapp_env_update_decorator = ContainerAppEnvUpdateDecorator( cmd=cmd, diff --git a/src/azure-cli/azure/cli/command_modules/containerapp/tests/latest/test_containerapp_env_commands.py b/src/azure-cli/azure/cli/command_modules/containerapp/tests/latest/test_containerapp_env_commands.py index 5c83fd9a89e..5e1b0feecbe 100644 --- a/src/azure-cli/azure/cli/command_modules/containerapp/tests/latest/test_containerapp_env_commands.py +++ b/src/azure-cli/azure/cli/command_modules/containerapp/tests/latest/test_containerapp_env_commands.py @@ -25,6 +25,24 @@ class ContainerappEnvScenarioTest(ScenarioTest): def __init__(self, *arg, **kwargs): super().__init__(*arg, random_config_dir=True, **kwargs) + @live_only() + @AllowLargeResponse(8192) + @ResourceGroupPreparer(location="eastus2") + def test_containerapp_env_environment_mode(self, resource_group): + for mode in ['WorkloadProfiles', 'Express']: + env_name = self.create_random_name(prefix='env-mode-', length=24) + self.cmd( + 'containerapp env create -g {} -n {} --location eastus2 ' + '--environment-mode {} --logs-destination none'.format(resource_group, env_name, mode), + checks=[JMESPathCheck('properties.environmentMode', mode)]) + self.cmd('containerapp env show -g {} -n {}'.format(resource_group, env_name), + checks=[JMESPathCheck('properties.environmentMode', mode)]) + self.cmd( + 'containerapp env update -g {} -n {} --environment-mode Archived'.format( + resource_group, env_name), + checks=[JMESPathCheck('properties.environmentMode', 'Archived')]) + self.cmd('containerapp env delete -g {} -n {} --yes --no-wait'.format(resource_group, env_name)) + @AllowLargeResponse(8192) @ResourceGroupPreparer(location="northeurope") @LogAnalyticsWorkspacePreparer(location="eastus", get_shared_key=True) diff --git a/src/azure-cli/azure/cli/command_modules/containerapp/tests/latest/test_containerapp_env_mode_unit.py b/src/azure-cli/azure/cli/command_modules/containerapp/tests/latest/test_containerapp_env_mode_unit.py new file mode 100644 index 00000000000..1754ead880f --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/containerapp/tests/latest/test_containerapp_env_mode_unit.py @@ -0,0 +1,207 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import json +import unittest +from copy import deepcopy +from unittest.mock import Mock, patch + +from azure.cli.core.azclierror import RequiredArgumentMissingError, ValidationError +from azure.cli.command_modules.containerapp._clients import ManagedEnvironmentClient +from azure.cli.command_modules.containerapp._utils import ( + validate_environment_mode_and_workload_profiles_compatible, +) +from azure.cli.command_modules.containerapp.containerapp_env_decorator import ( + ContainerAppEnvCreateDecorator, + ContainerAppEnvUpdateDecorator, +) + + +class ContainerappEnvEnvironmentModeTest(unittest.TestCase): + def setUp(self): + self.cmd = Mock() + self.cmd.cli_ctx.data = {'safe_params': []} + self.client = Mock() + self.client.show.return_value = None + self.parameters = { + 'name': 'test-env', + 'resource_group_name': 'test-rg', + 'location': 'eastus2', + 'logs_destination': 'none', + 'enable_workload_profiles': True, + } + self.profiles = [{'name': 'Consumption', 'workloadProfileType': 'Consumption'}] + module = 'azure.cli.command_modules.containerapp.containerapp_env_decorator' + for name, value in [ + ('validate_environment_location', 'eastus2'), + ('_ensure_location_allowed', None), + ('get_default_workload_profiles', self.profiles)]: + patcher = patch(f'{module}.{name}', return_value=value) + patcher.start() + self.addCleanup(patcher.stop) + + def create_decorator(self, **parameters): + return ContainerAppEnvCreateDecorator( + self.cmd, self.client, dict(self.parameters, **parameters), None) + + def test_containerapp_env_mode_compatibility(self): + for mode in [None, 'WorkloadProfiles', 'ConsumptionOnly', 'Express', + 'workloadprofiles', 'CONSUMPTIONONLY', 'express', 'EXPRESS']: + for enabled in [None, True, False]: + with self.subTest(mode=mode, enabled=enabled): + conflict = mode is not None and enabled is not None and ( + (mode.lower() != 'consumptiononly') != enabled) + if conflict: + with self.assertRaisesRegex(ValidationError, "Please use '--environment-mode' alone"): + validate_environment_mode_and_workload_profiles_compatible(mode, enabled) + else: + validate_environment_mode_and_workload_profiles_compatible(mode, enabled) + + def test_containerapp_env_mode_create_payload(self): + for mode in ['WorkloadProfiles', 'ConsumptionOnly', 'Express', + 'workloadprofiles', 'CONSUMPTIONONLY', 'express', 'EXPRESS']: + with self.subTest(mode=mode): + decorator = self.create_decorator(environment_mode=mode) + decorator.validate_arguments() + decorator.construct_payload() + properties = decorator.managed_env_def['properties'] + self.assertEqual(properties['environmentMode'], mode) + if mode.lower() == 'consumptiononly': + self.assertIsNone(properties.get('workloadProfiles')) + else: + self.assertEqual(properties['workloadProfiles'], self.profiles) + decorator.create() + self.assertEqual( + self.client.create.call_args.kwargs['managed_environment_envelope'], + decorator.managed_env_def) + + def test_containerapp_env_mode_legacy_defaults(self): + for enabled in [True, False]: + with self.subTest(enabled=enabled): + decorator = self.create_decorator(enable_workload_profiles=enabled) + decorator.validate_arguments() + decorator.construct_payload() + properties = decorator.managed_env_def['properties'] + self.assertNotIn('environmentMode', properties) + self.assertEqual(properties.get('workloadProfiles'), self.profiles if enabled else None) + + def test_containerapp_env_mode_explicit_legacy_flags(self): + for flag in ['-w', '--enable-workload-profiles']: + self.cmd.cli_ctx.data['safe_params'] = [flag] + for mode, enabled in [('ConsumptionOnly', True), ('WorkloadProfiles', False), ('Express', False)]: + with self.subTest(flag=flag, mode=mode): + with self.assertRaises(ValidationError): + self.create_decorator( + environment_mode=mode, enable_workload_profiles=enabled).validate_arguments() + for mode, enabled in [('ConsumptionOnly', False), ('WorkloadProfiles', True), ('Express', True)]: + with self.subTest(flag=flag, mode=mode): + self.create_decorator( + environment_mode=mode, enable_workload_profiles=enabled).validate_arguments() + + def test_containerapp_env_mode_infrastructure_resource_group(self): + subnet = '/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/subnet' + decorator = self.create_decorator( + environment_mode='ConsumptionOnly', infrastructure_resource_group='infra-rg', + infrastructure_subnet_resource_id=subnet) + with self.assertRaisesRegex(RequiredArgumentMissingError, 'ConsumptionOnly'): + decorator.validate_arguments() + + for mode in ['WorkloadProfiles', 'Express']: + with self.subTest(mode=mode): + decorator = self.create_decorator( + environment_mode=mode, infrastructure_resource_group='infra-rg', + infrastructure_subnet_resource_id=subnet) + decorator.validate_arguments() + decorator.construct_payload() + self.assertEqual(decorator.managed_env_def['properties']['InfrastructureResourceGroup'], 'infra-rg') + + def test_containerapp_env_mode_existing_environment(self): + dedicated_profiles = self.profiles + [ + {'name': 'dedicated', 'workloadProfileType': 'D4', 'minimumCount': 1, 'maximumCount': 2}] + for mode, profiles in [('ConsumptionOnly', None), ('WorkloadProfiles', dedicated_profiles), + ('Express', dedicated_profiles)]: + self.client.show.return_value = { + 'location': 'eastus2', 'properties': {'workloadProfiles': profiles}} + with self.subTest(mode=mode): + decorator = self.create_decorator(environment_mode=mode) + decorator.construct_payload() + properties = decorator.managed_env_def['properties'] + self.assertEqual(properties['environmentMode'], mode) + self.assertEqual(properties.get('workloadProfiles'), profiles) + + other_mode = 'WorkloadProfiles' if mode == 'ConsumptionOnly' else 'ConsumptionOnly' + with self.assertRaises(ValidationError): + self.create_decorator(environment_mode=other_mode).construct_payload() + + def test_containerapp_env_mode_existing_consumption_default(self): + self.client.show.return_value = { + 'location': 'eastus2', 'properties': {'workloadProfiles': None}} + decorator = self.create_decorator() + decorator.construct_payload() + self.assertIsNone(decorator.managed_env_def['properties'].get('workloadProfiles')) + self.assertNotIn('environmentMode', decorator.managed_env_def['properties']) + + def test_containerapp_env_mode_update_payload(self): + existing = { + 'location': 'eastus2', + 'properties': {'environmentMode': 'WorkloadProfiles', 'workloadProfiles': self.profiles}, + } + self.client.show.return_value = existing + for mode in [None, 'WorkloadProfiles', 'ConsumptionOnly', 'Express']: + with self.subTest(mode=mode): + decorator = ContainerAppEnvUpdateDecorator( + self.cmd, self.client, { + 'name': 'test-env', 'resource_group_name': 'test-rg', 'environment_mode': mode, + }, None) + decorator.validate_arguments() + decorator.construct_payload() + expected = {'location': 'eastus2'} + if mode is not None: + expected['properties'] = {'environmentMode': mode} + self.assertEqual(decorator.managed_env_def, expected) + decorator.update() + self.assertEqual( + self.client.update.call_args.kwargs['managed_environment_envelope'], expected) + self.assertEqual(existing, { + 'location': 'eastus2', + 'properties': {'environmentMode': 'WorkloadProfiles', 'workloadProfiles': self.profiles}, + }) + + def test_containerapp_env_mode_update_with_workload_profile(self): + self.client.show.return_value = { + 'location': 'eastus2', 'properties': {'workloadProfiles': deepcopy(self.profiles)}} + decorator = ContainerAppEnvUpdateDecorator( + self.cmd, self.client, { + 'environment_mode': 'WorkloadProfiles', 'workload_profile_name': 'dedicated', + 'workload_profile_type': 'D4', 'min_nodes': 1, 'max_nodes': 2, + }, None) + decorator.construct_payload() + self.assertEqual(decorator.managed_env_def['properties'], { + 'environmentMode': 'WorkloadProfiles', + 'workloadProfiles': self.profiles + [{ + 'name': 'dedicated', 'workloadProfileType': 'D4', + 'minimumCount': 1, 'maximumCount': 2, + }], + }) + + def test_containerapp_env_mode_rest_requests(self): + self.cmd.cli_ctx.cloud.endpoints.resource_manager = 'https://management.azure.com' + module = 'azure.cli.command_modules.containerapp._clients' + payload = {'location': 'eastus2', 'properties': {'environmentMode': 'WorkloadProfiles'}} + expected_url = ( + 'https://management.azure.com/subscriptions/sub/resourceGroups/test-rg/' + 'providers/Microsoft.App/managedEnvironments/test-env?api-version=2026-07-01') + with patch(f'{module}.get_subscription_id', return_value='sub'), \ + patch(f'{module}.send_raw_request') as send: + send.return_value.status_code = 200 + send.return_value.json.return_value = payload + for operation, method in [(ManagedEnvironmentClient.create, 'PUT'), + (ManagedEnvironmentClient.update, 'PATCH')]: + with self.subTest(method=method): + self.assertEqual(operation(self.cmd, 'test-rg', 'test-env', payload), payload) + send.assert_called_with( + self.cmd.cli_ctx, method, expected_url, body=json.dumps(payload)) + self.assertEqual(ManagedEnvironmentClient.show(self.cmd, 'test-rg', 'test-env'), payload) + send.assert_called_with(self.cmd.cli_ctx, 'GET', expected_url)