Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 0 additions & 13 deletions src/azure-cli/azure/cli/command_modules/batch/_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,19 +168,6 @@ def node_list_table_format(result):
return table_output


def pool_node_agent_skus_list_table_format(result):
"""Format pool node-agent-skus list as a table."""
table_output = []
for item in result:
table_row = OrderedDict()
table_row['Agent Id'] = item.get('id', None)
table_row['Publisher'] = item.get('publisher', None)
table_row['Offer'] = item.get('offer', None)
table_row['Sku'] = item.get('sku', None)
table_output.append(table_row)
return table_output


def pool_list_table_format(result):
"""Format pool list as a table."""
table_output = []
Expand Down
17 changes: 14 additions & 3 deletions src/azure-cli/azure/cli/command_modules/batch/_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,11 +533,14 @@

helps['batch pool create'] = """
type: command
short-summary: Create a Batch pool in an account. When creating a pool, choose arguments from either Cloud Services Configuration or Virtual Machine Configuration.
short-summary: Create a Batch pool in an account.
examples:
- name: Create a Batch pool in an account. When creating a pool, choose arguments from either Cloud Services Configuration or Virtual Machine Configuration.
- name: Create a Batch pool from a JSON file.
text: >
az batch pool create --json-file batch-pool-create.json --account-name clibatch --account-key BatchAccountKey
az batch pool create --json-file batch-pool-create.json --account-name clibatch --account-key BatchAccountKey --account-endpoint https://clibatch.eastus.batch.azure.com
- name: Create a Batch pool of two Ubuntu 24.04 compute nodes.
text: >
az batch pool create --id mypool --vm-size Standard_D4ds_v5 --target-dedicated-nodes 2 --image canonical:ubuntu-24_04-lts:server --node-agent-sku-id "batch.node.ubuntu 24.04" --account-name clibatch --account-key BatchAccountKey --account-endpoint https://clibatch.eastus.batch.azure.com

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium Add focused coverage for the new pool example

The existing BatchDataPlaneScenarioTests.test_batch_pool_cmd still creates Ubuntu 18.04; its JSON fixture uses Windows with zero dedicated nodes. Please add a recorded scenario for this two-node Ubuntu 24.04 example and assert the returned VM size, target dedicated count, image reference and node-agent SKU, then verify playback. This is a batch scenario-coverage gap, not a confirmed runtime regression. The endpoint omission reported earlier is already fixed here.

X Engineering Agent · Reviewer · React with +1 or -1 to train the reviewer

"""

helps['batch pool node-counts'] = """
Expand Down Expand Up @@ -568,6 +571,14 @@
helps['batch pool supported-images list'] = """
type: command
short-summary: Lists all Virtual Machine Images supported by the Azure Batch service.
long-summary: This command needs a Batch account. Select one with 'az batch account login', or pass --account-name and --account-endpoint (and --account-key for Shared Key authentication).
examples:
- name: List the images supported by the Batch account selected with 'az batch account login'.
text: >
az batch pool supported-images list
- name: List the images supported by a Batch account, using your 'az login' credentials (Microsoft Entra ID).
text: >
az batch pool supported-images list --account-name mybatchaccount --account-endpoint https://mybatchaccount.eastus.batch.azure.com
"""

helps['batch pool usage-metrics'] = """
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@
'network_configuration.public_ip_address_configuration',
'network_configuration.subnet_id',
'enable_auto_scale',
'cloud_service_configuration.target_os_version',
'pool.auto_scale_evaluation_interval',
# 'pool.start_task.environment_settings',
# 'pool.start_task.max_task_retry_count',
Expand Down
9 changes: 3 additions & 6 deletions src/azure-cli/azure/cli/command_modules/batch/_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
AccountKeyType,
KeySource,
PublicNetworkAccessType,
ResourceIdentityType,
EndpointAccessDefaultAction)
from azure.batch.models import (
CachingType,
Expand Down Expand Up @@ -85,8 +84,7 @@ def load_arguments(self, _):
c.argument('public_network_access', help="The network access type for accessing Azure Batch account. Values can either be enabled or disabled.", arg_type=get_enum_type(PublicNetworkAccessType))
c.argument('encryption_key_source', help='Part of the encryption configuration for the Batch account. Type of the key source. Can be either Microsoft.Batch or Microsoft.KeyVault', arg_type=get_enum_type(KeySource))
c.argument('encryption_key_identifier', help='Part of the encryption configuration for the Batch account. '
'Full path to the versioned secret. Example https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053.')
c.argument('identity_type', help="The type of identity used for the Batch account. Possible values include: 'SystemAssigned', 'None'.", arg_type=get_enum_type(ResourceIdentityType), deprecate_info=c.deprecate(hide=True))
'Full path to the versioned secret. Example: `https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053`.')
c.argument('mi_user_assigned', help='Resource ID of the user assigned identity for the batch services account.', arg_group='Identity')
c.argument('mi_system_assigned', help='Set the system managed identity on the batch services account.', arg_group='Identity')
c.ignore('keyvault_url')
Expand All @@ -96,8 +94,7 @@ def load_arguments(self, _):
c.argument('storage_account', help='The storage account name or resource ID to be used for auto storage.', validator=storage_account_id)
c.argument('encryption_key_source', help='Part of the encryption configuration for the Batch account. Type of the key source. Can be either Microsoft.Batch or Microsoft.KeyVault')
c.argument('public_network_access', help="The network access type for accessing Azure Batch account. Values can either be enabled or disabled.", arg_type=get_enum_type(PublicNetworkAccessType))
c.argument('encryption_key_identifier', help='Part of the encryption configuration for the Batch account. Full path to the versioned secret. Example https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053.')
c.argument('identity_type', help="The type of identity used for the Batch account. Possible values include: 'SystemAssigned', 'None'.", arg_type=get_enum_type(ResourceIdentityType), deprecate_info=c.deprecate(hide=True))
c.argument('encryption_key_identifier', help='Part of the encryption configuration for the Batch account. Full path to the versioned secret. Example: `https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053`.')

with self.argument_context('batch account identity assign') as c:
c.argument('resource_group_name', resource_group_name_type, help='Name of the resource group. If not specified will display currently set account.')
Expand Down Expand Up @@ -419,7 +416,7 @@ def load_arguments(self, _):
arg_group="Pool: Virtual Machine Configuration",
help='A space separated list of DiskEncryptionTargets. current possible values include OsDisk and TemporaryDisk.', type=disk_encryption_configuration_format)
c.extra('image', completer=load_supported_images, arg_group="Pool: Virtual Machine Configuration",
help="OS image reference. This can be either 'publisher:offer:sku[:version]' format, or a fully qualified ARM image id of the form '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName}'. If 'publisher:offer:sku[:version]' format, version is optional and if omitted latest will be used. Valid values can be retrieved via 'az batch pool supported-images list'. For example: 'MicrosoftWindowsServer:WindowsServer:2012-R2-Datacenter:latest'")
help="OS image reference. This can be either 'publisher:offer:sku[:version]' format, or the ARM resource identifier of an Azure Compute Gallery image of the form '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName}[/versions/{versionId}]'. If 'publisher:offer:sku[:version]' format, version is optional and if omitted latest will be used. Valid values can be retrieved via 'az batch pool supported-images list'. For example: 'canonical:ubuntu-24_04-lts:server'")
c.argument('mode', options_list=['--upgrade-policy-mode'], help='The mode of the pool OS upgrade.')
c.argument('enable_cross_zone_upgrade', arg_type=get_three_state_flag())
c.argument('prioritize_unhealthy_instances', arg_type=get_three_state_flag())
Expand Down
16 changes: 0 additions & 16 deletions src/azure-cli/azure/cli/command_modules/batch/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,15 +216,6 @@ def validate_json_file(namespace):
raise ValueError(f"Invalid JSON file: {err}")


def validate_cert_file(namespace):
"""Validate the give cert file existing"""
try:
with open(namespace.certificate_file, "rb"):
pass
except OSError:
raise ValueError("Cannot access certificate file: " + namespace.certificate_file)


def validate_options(namespace):
"""Validate any flattened request header option arguments."""
try:
Expand Down Expand Up @@ -296,13 +287,6 @@ def validate_pool_settings(namespace, _):
namespace.enable_auto_scale = True


def validate_cert_settings(namespace):
"""Custom parsing for certificate commands - adds default thumbprint
algorithm.
"""
namespace.thumbprint_algorithm = 'sha1'


def validate_client_parameters(cmd, namespace):
"""Retrieves Batch connection parameters from environment variables"""
from azure.mgmt.batch import BatchManagementClient
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
from azure.core import MatchConditions
#from azure.batch._client import BatchClientOperationsMixin
from azure.batch import models, BatchClient
from azure.batch._operations._patch import BatchClientOperationsMixin
from azure.core.credentials import AzureNamedKeyCredential

from azure.cli.core.mock import DummyCli
from azure.cli.command_modules.batch import _validators
from azure.cli.command_modules.batch import _command_type
from azure.cli.core.util import rmtree_with_retry


class TestObj: # pylint: disable=too-few-public-methods
Expand Down Expand Up @@ -775,3 +777,65 @@ def test_batch_task_create_environment_settings(self):

self.assertEqual(exit_code, 2)
create_task.assert_not_called()


class TestBatchPoolCreate(unittest.TestCase):
"""Run 'az batch pool create' with the SDK's create_pool mocked, so nothing is sent to the service."""

# The "two Ubuntu 24.04 compute nodes" example in the 'az batch pool create' help
EXAMPLE_ARGS = ['batch', 'pool', 'create', '--id', 'mypool', '--vm-size', 'Standard_D4ds_v5',
'--target-dedicated-nodes', '2', '--image', 'canonical:ubuntu-24_04-lts:server',
'--node-agent-sku-id', 'batch.node.ubuntu 24.04',
'--account-name', 'clibatch', '--account-key', 'BatchAccountKey']
ENDPOINT_ARGS = ['--account-endpoint', 'https://clibatch.eastus.batch.azure.com']

def setUp(self):
# No Batch settings from AZURE_BATCH_* environment variables or the CLI config
environ = {name: value for name, value in os.environ.items() if not name.startswith('AZURE_BATCH_')}
environ_patch = mock.patch.dict(os.environ, environ, clear=True)
environ_patch.start()
self.addCleanup(environ_patch.stop)
self.cli = DummyCli(random_config_dir=True)
self.addCleanup(self.cli.env_patch.stop)
self.addCleanup(rmtree_with_retry, self.cli.config.config_dir)

# The CLI builds the command's arguments from the SDK method's docstring, so the mock keeps it
docstring = BatchClientOperationsMixin.create_pool.__doc__
create_pool_patch = mock.patch.object(BatchClientOperationsMixin, 'create_pool', autospec=True,
return_value=None)
self.create_pool = create_pool_patch.start()
self.addCleanup(create_pool_patch.stop)
self.create_pool.__doc__ = docstring

def test_batch_pool_create_missing_endpoint(self):
with self.assertLogs('cli.azure.cli.core.azclierror', 'ERROR') as logs, \
self.assertRaises(SystemExit) as ex:
self.cli.invoke(self.EXAMPLE_ARGS, out_file=io.StringIO())
self.assertEqual(ex.exception.code, 2)
self.assertIn('Specify batch endpoint in command line or environment variable.',
[record.getMessage() for record in logs.records])
self.create_pool.assert_not_called()

def test_batch_pool_create_ubuntu_example(self):
self.assertEqual(self.cli.invoke(self.EXAMPLE_ARGS + self.ENDPOINT_ARGS, out_file=io.StringIO()), 0)
self.create_pool.assert_called_once()
# The CLI passes the --target-dedicated-nodes value on as a string; the service accepts it
self.assertEqual(self.create_pool.call_args.kwargs['pool'], {
'id': 'mypool',
'vmSize': 'Standard_D4ds_v5',
'targetDedicatedNodes': '2',
'virtualMachineConfiguration': {
'imageReference': {'publisher': 'canonical', 'offer': 'ubuntu-24_04-lts', 'sku': 'server'},
'nodeAgentSKUId': 'batch.node.ubuntu 24.04'}})

def test_batch_pool_create_gallery_image(self):
image = ('/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/'
'Microsoft.Compute/galleries/mygallery/images/myimage')
for image_id in [image, image + '/versions/1.0.0']:
with self.subTest(image_id=image_id):
args = self.EXAMPLE_ARGS + self.ENDPOINT_ARGS
args[args.index('--image') + 1] = image_id
self.assertEqual(self.cli.invoke(args, out_file=io.StringIO()), 0)
self.assertEqual(self.create_pool.call_args.kwargs['pool']['virtualMachineConfiguration'], {
'imageReference': {'virtualMachineImageId': image_id},
'nodeAgentSKUId': 'batch.node.ubuntu 24.04'})
Loading