diff --git a/src/azure-cli/azure/cli/command_modules/acs/_help.py b/src/azure-cli/azure/cli/command_modules/acs/_help.py index 38b5ae6e3ef..d5bac6a7731 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/_help.py +++ b/src/azure-cli/azure/cli/command_modules/acs/_help.py @@ -2456,6 +2456,11 @@ - name: --disable-artifact-streaming type: bool short-summary: Disable artifact streaming for VirtualMachineScaleSets managed by a Linux node pool. + - name: --node-vm-size -s + type: string + short-summary: Resize the VMs of a VirtualMachineScaleSets node pool. + long-summary: | + AKS replaces every node in the node pool with a node of the new size. It adds surge nodes of the new size, then cordons, drains and deletes the old nodes, following the node pool's upgrade settings (--max-surge, --max-unavailable, --drain-timeout, --node-soak-duration). The target size must be compatible with the current node pool configuration. Can be combined with --update-cluster-autoscaler, or with --enable-cluster-autoscaler/--disable-cluster-autoscaler when they change the autoscaler state. Not supported for VirtualMachines node pools; use "az aks nodepool manual-scale update" or "az aks nodepool auto-scale update" to change their VM sizes. examples: - name: Reconcile the nodepool back to its current state. text: az aks nodepool update -g MyResourceGroup -n nodepool1 --cluster-name MyManagedCluster @@ -2470,6 +2475,8 @@ az aks nodepool update --resource-group MyResourceGroup \\ --cluster-name MyManagedCluster --name npwin \\ --os-sku Windows2025 --enable-fips-image + - name: Resize the VMs of a VirtualMachineScaleSets node pool to Standard_D4s_v5. + text: az aks nodepool update -g MyResourceGroup -n nodepool1 --cluster-name MyManagedCluster --node-vm-size Standard_D4s_v5 """ helps["aks nodepool upgrade"] = """ diff --git a/src/azure-cli/azure/cli/command_modules/acs/_params.py b/src/azure-cli/azure/cli/command_modules/acs/_params.py index d0915ac6fe1..f172bdc3ac6 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/_params.py +++ b/src/azure-cli/azure/cli/command_modules/acs/_params.py @@ -1374,6 +1374,7 @@ def load_arguments(self, _): c.argument('gpu_driver', arg_type=get_enum_type(gpu_driver_install_modes)) c.argument('enable_artifact_streaming', action='store_true', validator=validate_artifact_streaming) c.argument('disable_artifact_streaming', action='store_true', validator=validate_artifact_streaming) + c.argument('node_vm_size', options_list=['--node-vm-size', '-s']) with self.argument_context('aks nodepool upgrade') as c: c.argument('max_surge', validator=validate_max_surge) diff --git a/src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py b/src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py index 64f23dfa07e..d27385c67e4 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py +++ b/src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py @@ -2022,6 +2022,52 @@ def get_yes(self) -> bool: """ return self.raw_param.get("yes") + def get_node_vm_size_for_update(self) -> Union[str, None]: + """Obtain and validate the value of node_vm_size for `az aks nodepool update`. + + An explicit empty value is rejected instead of being treated as omitted. + + :return: string or None + """ + node_vm_size = self.raw_param.get("node_vm_size") + if node_vm_size is None: + return None + if not node_vm_size.strip(): + raise InvalidArgumentValueError("--node-vm-size cannot be empty.") + return node_vm_size + + def validate_node_vm_size_with_autoscaler_for_update(self) -> None: + """Reject a resize combined with an autoscaler request that would exit early without updating. + + Must be called with the fetched agentpool attached and before the autoscaler properties are updated, since + it compares the request with the node pool's current autoscaler state. + + On a VirtualMachineScaleSets pool, --enable-cluster-autoscaler when the autoscaler is already enabled, or + --disable-cluster-autoscaler when it is already disabled, is a no-op that exits early, which would silently + drop --node-vm-size. Other combinations (e.g. resize with --update-cluster-autoscaler, or with an + enable/disable that changes the autoscaler state) are left untouched so existing callers, such as + aks-preview, keep working. VirtualMachines pools are handled by update_auto_scaler_properties_vms and + update_vm_size, which aks-preview overrides with its own VirtualMachines handling. + """ + if self.get_node_vm_size_for_update() is None: + return + if self.agentpool is None or self.get_vm_set_type() != CONST_VIRTUAL_MACHINE_SCALE_SETS: + return + autoscaler_enabled = bool(self.agentpool.enable_auto_scaling) + if self.raw_param.get("enable_cluster_autoscaler") and autoscaler_enabled: + raise MutuallyExclusiveArgumentError( + "Cluster autoscaler is already enabled for this node pool, so --enable-cluster-autoscaler " + "would skip the update and --node-vm-size would not be applied. " + "Remove --enable-cluster-autoscaler, or use --update-cluster-autoscaler to change " + "min-count or max-count." + ) + if self.raw_param.get("disable_cluster_autoscaler") and not autoscaler_enabled: + raise MutuallyExclusiveArgumentError( + "Cluster autoscaler is already disabled for this node pool, so --disable-cluster-autoscaler " + "would skip the update and --node-vm-size would not be applied. " + "Remove --disable-cluster-autoscaler." + ) + class AKSAgentPoolAddDecorator: def __init__( @@ -3030,6 +3076,44 @@ def update_ssh_access(self, agentpool: AgentPool) -> AgentPool: agentpool.security_profile.ssh_access = ssh_access return agentpool + def update_vm_size(self, agentpool: AgentPool) -> AgentPool: + """Update the VM size of a VirtualMachineScaleSets based AgentPool object. + + Changing the VM size triggers a rolling replacement: AKS surges nodes with the new size, then cordons, + drains and deletes the old nodes according to the node pool's upgrade settings. + + VirtualMachines node pools manage VM sizes through their scale profiles, so --node-vm-size is rejected + for them instead of being silently ignored. Combinations with no-op autoscaler requests are rejected + earlier by AKSAgentPoolContext.validate_node_vm_size_with_autoscaler_for_update. + + :return: the AgentPool object + """ + self._ensure_agentpool(agentpool) + + node_vm_size = self.context.get_node_vm_size_for_update() + if node_vm_size is None: + return agentpool + + if self.context.get_vm_set_type() == CONST_VIRTUAL_MACHINES: + raise InvalidArgumentValueError( + "--node-vm-size is not supported for VirtualMachines node pools. " + 'Please use "az aks nodepool manual-scale update" or "az aks nodepool auto-scale update" ' + "to change the VM size of a VirtualMachines node pool." + ) + + # already set to the same value, directly return + if agentpool.vm_size and agentpool.vm_size.lower() == node_vm_size.lower(): + return agentpool + + msg = ( + f"You're going to resize agentpool {agentpool.name} from '{agentpool.vm_size}' to '{node_vm_size}'. " + "All nodes in the node pool will be replaced with nodes of the new size. Proceed?" + ) + if not self.context.get_yes() and not prompt_y_n(msg, default="n"): + raise DecoratorEarlyExitException() + agentpool.vm_size = node_vm_size + return agentpool + def update_gpu_profile(self, agentpool: AgentPool) -> AgentPool: self._ensure_agentpool(agentpool) @@ -3069,6 +3153,9 @@ def update_agentpool_profile_default(self, agentpools: List[AgentPool] = None) - """ # fetch the Agentpool object agentpool = self.fetch_agentpool(agentpools) + # reject a resize combined with a no-op autoscaler request, before update_auto_scaler_properties changes the + # autoscaler state or exits early (e.g. autoscaler already enabled) and drops the resize + self.context.validate_node_vm_size_with_autoscaler_for_update() # update auto scaler properties agentpool = self.update_auto_scaler_properties(agentpool) # update auto scaler properties for vms pool @@ -3091,6 +3178,8 @@ def update_agentpool_profile_default(self, agentpools: List[AgentPool] = None) - agentpool = self.update_secure_boot(agentpool) # update ssh access agentpool = self.update_ssh_access(agentpool) + # update vm size + agentpool = self.update_vm_size(agentpool) # update local DNS profile agentpool = self.update_localdns_profile(agentpool) # update gpu profile diff --git a/src/azure-cli/azure/cli/command_modules/acs/custom.py b/src/azure-cli/azure/cli/command_modules/acs/custom.py index 4a412d06616..7622cccc1a6 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/custom.py @@ -3672,6 +3672,7 @@ def aks_agentpool_update( # ssh access ssh_access=None, yes=False, + node_vm_size=None, ): # DO NOT MOVE: get all the original parameters and save them as a dictionary raw_parameters = locals() diff --git a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_agentpool_decorator.py b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_agentpool_decorator.py index 7d068a3eff4..c8fde5b464e 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_agentpool_decorator.py +++ b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_agentpool_decorator.py @@ -4021,6 +4021,168 @@ def common_update_ssh_access(self): ), self.assertRaises(DecoratorEarlyExitException): dec_4.update_ssh_access(agentpool_4) + def _set_vms_pool_type(self, agentpool): + if self.agentpool_decorator_mode == AgentPoolDecoratorMode.MANAGED_CLUSTER: + agentpool.type = CONST_VIRTUAL_MACHINES + else: + if agentpool.properties is None: + agentpool.properties = self.models.AgentPoolManagedClusterAgentPoolProfileProperties() + agentpool.properties.type_properties_type = CONST_VIRTUAL_MACHINES + return agentpool + + def common_update_vm_size(self): + # set a new value with --yes, no prompt + dec_1 = AKSAgentPoolUpdateDecorator( + self.cmd, + self.client, + {"node_vm_size": "Standard_D4s_v5", "yes": True}, + self.resource_type, + self.agentpool_decorator_mode, + ) + # fail on passing the wrong agentpool object + with self.assertRaises(CLIInternalError): + dec_1.update_vm_size(None) + agentpool_1 = self.create_initialized_agentpool_instance(vm_size="Standard_D2s_v5") + dec_1.context.attach_agentpool(agentpool_1) + with patch("azure.cli.command_modules.acs.agentpool_decorator.prompt_y_n") as mock_prompt: + dec_agentpool_1 = dec_1.update_vm_size(agentpool_1) + mock_prompt.assert_not_called() + ground_truth_agentpool_1 = self.create_initialized_agentpool_instance(vm_size="Standard_D4s_v5") + self.assertEqual(dec_agentpool_1, ground_truth_agentpool_1) + + # None, no change + dec_2 = AKSAgentPoolUpdateDecorator( + self.cmd, + self.client, + {"node_vm_size": None}, + self.resource_type, + self.agentpool_decorator_mode, + ) + agentpool_2 = self.create_initialized_agentpool_instance(vm_size="Standard_D2s_v5") + dec_2.context.attach_agentpool(agentpool_2) + dec_agentpool_2 = dec_2.update_vm_size(agentpool_2) + ground_truth_agentpool_2 = self.create_initialized_agentpool_instance(vm_size="Standard_D2s_v5") + self.assertEqual(dec_agentpool_2, ground_truth_agentpool_2) + + # already set to the same value (case-insensitive), no prompt needed, directly return + dec_3 = AKSAgentPoolUpdateDecorator( + self.cmd, + self.client, + {"node_vm_size": "standard_d2s_v5"}, + self.resource_type, + self.agentpool_decorator_mode, + ) + agentpool_3 = self.create_initialized_agentpool_instance(vm_size="Standard_D2s_v5") + dec_3.context.attach_agentpool(agentpool_3) + with patch("azure.cli.command_modules.acs.agentpool_decorator.prompt_y_n") as mock_prompt: + dec_agentpool_3 = dec_3.update_vm_size(agentpool_3) + mock_prompt.assert_not_called() + ground_truth_agentpool_3 = self.create_initialized_agentpool_instance(vm_size="Standard_D2s_v5") + self.assertEqual(dec_agentpool_3, ground_truth_agentpool_3) + + # prompt accepted + dec_4 = AKSAgentPoolUpdateDecorator( + self.cmd, + self.client, + {"node_vm_size": "Standard_D4s_v5", "yes": False}, + self.resource_type, + self.agentpool_decorator_mode, + ) + agentpool_4 = self.create_initialized_agentpool_instance(vm_size="Standard_D2s_v5") + dec_4.context.attach_agentpool(agentpool_4) + with patch( + "azure.cli.command_modules.acs.agentpool_decorator.prompt_y_n", + return_value=True, + ) as mock_prompt: + dec_agentpool_4 = dec_4.update_vm_size(agentpool_4) + mock_prompt.assert_called_once() + self.assertEqual(dec_agentpool_4.vm_size, "Standard_D4s_v5") + + # prompt rejected, early exit + dec_5 = AKSAgentPoolUpdateDecorator( + self.cmd, + self.client, + {"node_vm_size": "Standard_D4s_v5", "yes": False}, + self.resource_type, + self.agentpool_decorator_mode, + ) + agentpool_5 = self.create_initialized_agentpool_instance(vm_size="Standard_D2s_v5") + dec_5.context.attach_agentpool(agentpool_5) + with patch( + "azure.cli.command_modules.acs.agentpool_decorator.prompt_y_n", + return_value=False, + ), self.assertRaises(DecoratorEarlyExitException): + dec_5.update_vm_size(agentpool_5) + + # VirtualMachines pool, raise error rather than silently ignoring the size + dec_6 = AKSAgentPoolUpdateDecorator( + self.cmd, + self.client, + {"node_vm_size": "Standard_D4s_v5", "yes": True}, + self.resource_type, + self.agentpool_decorator_mode, + ) + agentpool_6 = self._set_vms_pool_type(self.create_initialized_agentpool_instance()) + dec_6.context.attach_agentpool(agentpool_6) + with self.assertRaises(InvalidArgumentValueError): + dec_6.update_vm_size(agentpool_6) + + # empty value, raise error on both VMSS and VirtualMachines pools + for set_vms_type in (False, True): + dec_7 = AKSAgentPoolUpdateDecorator( + self.cmd, + self.client, + {"node_vm_size": "", "yes": True}, + self.resource_type, + self.agentpool_decorator_mode, + ) + agentpool_7 = self.create_initialized_agentpool_instance(vm_size="Standard_D2s_v5") + if set_vms_type: + agentpool_7 = self._set_vms_pool_type(agentpool_7) + dec_7.context.attach_agentpool(agentpool_7) + with self.subTest(vms=set_vms_type), self.assertRaises(InvalidArgumentValueError): + dec_7.update_vm_size(agentpool_7) + + # VMSS pool: an autoscaler request that is a no-op (already in the requested state) exits early and would + # drop the resize, so it is rejected; every other autoscaler combination is allowed and the size applied + for autoscaler_param, enable_auto_scaling, expect_error in ( + ("enable_cluster_autoscaler", True, True), + ("disable_cluster_autoscaler", False, True), + ("enable_cluster_autoscaler", False, False), + ("disable_cluster_autoscaler", True, False), + ("update_cluster_autoscaler", True, False), + ): + dec_8 = AKSAgentPoolUpdateDecorator( + self.cmd, + self.client, + {"node_vm_size": "Standard_D4s_v5", "yes": True, autoscaler_param: True}, + self.resource_type, + self.agentpool_decorator_mode, + ) + agentpool_8 = self.create_initialized_agentpool_instance( + vm_size="Standard_D2s_v5", enable_auto_scaling=enable_auto_scaling + ) + dec_8.context.attach_agentpool(agentpool_8) + with self.subTest(param=autoscaler_param, enabled=enable_auto_scaling): + if expect_error: + with self.assertRaises(MutuallyExclusiveArgumentError): + dec_8.context.validate_node_vm_size_with_autoscaler_for_update() + else: + dec_8.context.validate_node_vm_size_with_autoscaler_for_update() + self.assertEqual(dec_8.update_vm_size(agentpool_8).vm_size, "Standard_D4s_v5") + + # VirtualMachines pool: the autoscaler check does not apply (handled by update_vm_size and the VMs path) + dec_9 = AKSAgentPoolUpdateDecorator( + self.cmd, + self.client, + {"node_vm_size": "Standard_D4s_v5", "enable_cluster_autoscaler": True}, + self.resource_type, + self.agentpool_decorator_mode, + ) + agentpool_9 = self._set_vms_pool_type(self.create_initialized_agentpool_instance()) + dec_9.context.attach_agentpool(agentpool_9) + dec_9.context.validate_node_vm_size_with_autoscaler_for_update() + def common_update_managed_dranet(self): dec_1 = AKSAgentPoolUpdateDecorator( self.cmd, @@ -4322,6 +4484,77 @@ def test_update_managed_dranet(self): def test_update_ssh_access(self): self.common_update_ssh_access() + def test_update_vm_size(self): + self.common_update_vm_size() + + def _run_aks_agentpool_update(self, existing_agentpool, **kwargs): + from azure.cli.command_modules.acs.custom import aks_agentpool_update + + self.client.get = Mock(return_value=existing_agentpool) + with patch("azure.cli.command_modules.acs.agentpool_decorator.sdk_no_wait") as put_agentpool: + result = aks_agentpool_update( + self.cmd, + self.client, + "test_rg_name", + "test_cluster_name", + "test_nodepool_name", + **kwargs, + ) + return result, put_agentpool + + def test_aks_agentpool_update_vm_size(self): + def vmss_pool(enable_auto_scaling=False): + return self.create_initialized_agentpool_instance( + nodepool_name="test_nodepool_name", + vm_size="Standard_D2s_v5", + count=3, + enable_auto_scaling=enable_auto_scaling, + min_count=1 if enable_auto_scaling else None, + max_count=3 if enable_auto_scaling else None, + ) + + # resize alone sends a PUT with the new size + _, put_agentpool = self._run_aks_agentpool_update(vmss_pool(), node_vm_size="Standard_D4s_v5", yes=True) + put_agentpool.assert_called_once() + self.assertEqual(put_agentpool.call_args.args[5].vm_size, "Standard_D4s_v5") + + # resize combined with an autoscaler change that does something: one PUT carries both changes + for name, enabled, params, expected in ( + ("update", True, {"update_cluster_autoscaler": True, "min_count": 2, "max_count": 5}, (True, 2, 5)), + ("enable", False, {"enable_cluster_autoscaler": True, "min_count": 2, "max_count": 5}, (True, 2, 5)), + ("disable", True, {"disable_cluster_autoscaler": True}, (False, None, None)), + ): + with self.subTest(combined=name): + _, put_agentpool = self._run_aks_agentpool_update( + vmss_pool(enabled), node_vm_size="Standard_D4s_v5", yes=True, **params + ) + put_agentpool.assert_called_once() + sent = put_agentpool.call_args.args[5] + self.assertEqual(sent.vm_size, "Standard_D4s_v5") + self.assertEqual((sent.enable_auto_scaling, sent.min_count, sent.max_count), expected) + + # an autoscaler request that is a no-op exits early; it must not swallow the resize: reject before any PUT + for name, enabled, params in ( + ("enable", True, {"enable_cluster_autoscaler": True, "min_count": 1, "max_count": 3}), + ("disable", False, {"disable_cluster_autoscaler": True}), + ): + with self.subTest(noop=name): + with patch("azure.cli.command_modules.acs.agentpool_decorator.sdk_no_wait") as put_agentpool, \ + self.assertRaises(MutuallyExclusiveArgumentError): + self._run_aks_agentpool_update( + vmss_pool(enabled), node_vm_size="Standard_D4s_v5", yes=True, **params + ) + put_agentpool.assert_not_called() + + # empty value is rejected before any PUT + with self.assertRaises(InvalidArgumentValueError): + self._run_aks_agentpool_update(vmss_pool(), node_vm_size="", yes=True) + + # omitting --node-vm-size keeps the existing size + _, put_agentpool = self._run_aks_agentpool_update(vmss_pool()) + put_agentpool.assert_called_once() + self.assertEqual(put_agentpool.call_args.args[5].vm_size, "Standard_D2s_v5") + def test_update_agentpool_profile_default(self): import inspect @@ -4509,6 +4742,9 @@ def test_update_managed_dranet(self): def test_update_ssh_access(self): self.common_update_ssh_access() + def test_update_vm_size(self): + self.common_update_vm_size() + def test_update_agentpool_profile_default(self): import inspect diff --git a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_aks_commands.py b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_aks_commands.py index 6d845b1b14b..b9d9d138846 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_aks_commands.py +++ b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_aks_commands.py @@ -17430,3 +17430,57 @@ def test_aks_update_with_disable_upstream_kubescheduler_user_configuration( self.is_empty(), ], ) + + @live_only() + @AllowLargeResponse() + @AKSCustomResourceGroupPreparer(random_name_length=17, name_prefix='clitest', location='westus2') + def test_aks_nodepool_update_vm_size(self, resource_group, resource_group_location): + # reset the count so in replay mode the random names will start with 0 + self.test_resources_count = 0 + aks_name = self.create_random_name('cliakstest', 16) + self.kwargs.update({ + 'resource_group': resource_group, + 'name': aks_name, + 'location': resource_group_location, + 'nodepool_name': 'nodepool2', + 'ssh_key_value': self.generate_ssh_keys(), + }) + + # create + create_cmd = 'aks create --resource-group={resource_group} --name={name} --location={location} ' \ + '--node-count=1 --node-vm-size=Standard_D2s_v5 --ssh-key-value={ssh_key_value}' + self.cmd(create_cmd, checks=[ + self.check('provisioningState', 'Succeeded'), + ]) + + # add a VMSS user node pool; the service may report it as Updating while it settles, so wait for it + self.cmd('aks nodepool add --resource-group={resource_group} --cluster-name={name} ' + '--name={nodepool_name} --node-count=1 --node-vm-size=Standard_D2s_v5', checks=[ + self.check('vmSize', 'Standard_D2s_v5'), + ]) + wait_cmd = 'aks nodepool wait --resource-group={resource_group} --cluster-name={name} ' \ + '--name={nodepool_name} --custom "provisioningState==\'Succeeded\'" --interval 30 --timeout 3600' + self.cmd(wait_cmd, checks=[self.is_empty()]) + + # resize the node pool; right after a node pool is added, AKS may still run cluster-level operations + # (e.g. addon reconciliation) that reject a new PUT, so retry on those conflicts + resize_cmd = 'aks nodepool update --resource-group={resource_group} --cluster-name={name} ' \ + '--name={nodepool_name} --node-vm-size=Standard_D4s_v5 --yes' + for attempt in range(5): + try: + self.cmd(resize_cmd, checks=[self.check('vmSize', 'Standard_D4s_v5')]) + break + except Exception as ex: # pylint: disable=broad-except + if attempt == 4 or not any(code in str(ex) for code in ('OperationNotAllowed', 'EtagMismatch')): + raise + time.sleep(60) + self.cmd(wait_cmd, checks=[self.is_empty()]) + self.cmd('aks nodepool show --resource-group={resource_group} --cluster-name={name} ' + '--name={nodepool_name}', checks=[ + self.check('provisioningState', 'Succeeded'), + self.check('vmSize', 'Standard_D4s_v5'), + ]) + + # delete + self.cmd( + 'aks delete -g {resource_group} -n {name} --yes --no-wait', checks=[self.is_empty()])