def _register_data_plane_account_arguments(self, command_name):
        """ Add parameters required to create a storage client """
        from azure.cli.core.commands.parameters import get_resource_name_completion_list
        from ._validators import validate_client_parameters
        command = self.command_loader.command_table.get(command_name, None)
        if not command:
            return

        group_name = 'Storage Account'

        command.add_argument('account_name', '--account-name', required=False, default=None,
                             arg_group=group_name,
                             completer=get_resource_name_completion_list('Microsoft.Storage/storageAccounts'),
                             help='Storage account name. Related environment variable: AZURE_STORAGE_ACCOUNT. Must be '
                                  'used in conjunction with either storage account key or a SAS token. If neither are '
                                  'present, the command will try to query the storage account key using the '
                                  'authenticated Azure account. If a large number of storage commands are executed the '
                                  'API quota may be hit')
        command.add_argument('account_key', '--account-key', required=False, default=None,
                             arg_group=group_name,
                             help='Storage account key. Must be used in conjunction with storage account name. '
                                  'Environment variable: AZURE_STORAGE_KEY')
        command.add_argument('connection_string', '--connection-string', required=False, default=None,
                             validator=validate_client_parameters, arg_group=group_name,
                             help='Storage account connection string. Environment variable: '
                                  'AZURE_STORAGE_CONNECTION_STRING')
        command.add_argument('sas_token', '--sas-token', required=False, default=None,
                             arg_group=group_name,
                             help='A Shared Access Signature (SAS). Must be used in conjunction with storage account '
                                  'name. Environment variable: AZURE_STORAGE_SAS_TOKEN')
Example #2
0
def load_arguments(self, _):
    with self.argument_context('cognitiveservices') as c:
        c.argument('account_name', arg_type=name_arg_type, help='cognitive service account name',
                   completer=get_resource_name_completion_list('Microsoft.CognitiveServices/accounts'))
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('sku_name', options_list=['--sku'], help='the Sku of cognitive services account')
        c.argument('kind', help='the API name of cognitive services account')
        c.argument('tags', tags_type)
        c.argument('key_name', required=True, help='Key name to generate', choices=['key1', 'key2'])

    with self.argument_context('cognitiveservices account create') as c:
        c.argument('yes', action='store_true', help='Do not prompt for terms confirmation')
Example #3
0
def load_arguments(self, _):
    with self.argument_context('signalr') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('signalr_name', options_list=['--name', '-n'],
                   completer=get_resource_name_completion_list(SIGNALR_RESOURCE_TYPE),
                   help='Name of signalr service.')
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('signalr create') as c:
        c.argument('sku', help='The sku name of the signalr service. E.g. Standard_S1')
        c.argument('unit_count', help='The number of signalr service unit count', type=int)

    with self.argument_context('signalr key renew') as c:
        c.argument('key_type', help='The name of access key to regenerate', choices=SIGNALR_KEY_TYPE)
    def load_arguments(self, _):
        # pylint: disable=line-too-long
        from knack.arguments import CLIArgumentType
        from azure.cli.core.commands.parameters import get_resource_name_completion_list
        name_arg_type = CLIArgumentType(options_list=['--name', '-n'], metavar='NAME')
        existing_vm_name = CLIArgumentType(overrides=name_arg_type,
                                           configured_default='vm',
                                           help="The name of the Virtual Machine. You can configure the default using `az configure --defaults vm=<name>`",
                                           completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachines'), id_part='name')

        with self.argument_context('vm aem') as c:
            c.argument('vm_name', existing_vm_name)
            c.argument('skip_storage_check', action='store_true',
                       help='Disables the test for table content')
            c.argument('skip_storage_analytics', action='store_true',
                       help='skip enabling analytics on storage accounts')
            c.argument('wait_time_in_minutes', type=int,
                       help='Maximum minutes to wait for the storage metrics to be available')
Example #5
0
def load_arguments(self, _):
    # Argument Definition
    maps_name_type = CLIArgumentType(options_list=['--name', '-n'],
                                     completer=get_resource_name_completion_list('Microsoft.Maps/accounts'),
                                     help='The name of the maps account')

    # Parameter Registration
    with self.argument_context('maps') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   id_part='resource_group',
                   help='Resource group name')
        c.argument('account_name',
                   id_part='name',
                   arg_type=maps_name_type)

    with self.argument_context('maps account') as c:
        c.argument('sku_name',
                   options_list=['--sku', '-s'],
                   help='The name of the SKU.',
                   arg_type=get_enum_type(['S0']))
        c.argument('tags',
                   arg_type=tags_type)

    with self.argument_context('maps account create') as c:
        c.argument('force',
                   options_list=['--accept-tos'],
                   action='store_true')

    # Prevent --ids argument in keys with id_part=None
    with self.argument_context('maps account keys') as c:
        c.argument('account_name',
                   id_part=None,
                   arg_type=maps_name_type)

    with self.argument_context('maps account keys renew') as c:
        c.argument('key_type',
                   options_list=['--key'],
                   arg_type=get_enum_type(KeyType))
Example #6
0
            # Remove leading and trailing quotes for dos/cmd.exe users
            value = value[1:-1]
        dictval = shell_safe_json_parse(value)
        self.extend([
            ScheduleEntry(row['dayOfWeek'], int(row['startHourUtc']),
                          row.get('maintenanceWindow', None))
            for row in dictval
        ])


register_cli_argument(
    'redis',
    'name',
    arg_type=name_type,
    help='Name of the redis cache.',
    completer=get_resource_name_completion_list('Microsoft.Cache/redis'),
    id_part='name')
register_cli_argument('redis', 'redis_configuration', type=JsonString)
register_cli_argument('redis', 'reboot_type', **enum_choice_list(RebootType))
register_cli_argument('redis', 'key_type', **enum_choice_list(RedisKeyType))
register_cli_argument('redis', 'shard_id', type=int)
register_cli_argument('redis', 'sku', **enum_choice_list(SkuName))
register_cli_argument(
    'redis',
    'vm_size',
    help='Size of redis cache to deploy. '
    'Example : values for C family (C0, C1, C2, C3, C4, C5, C6). '
    'For P family (P1, P2, P3, P4)')
register_cli_argument('redis', 'enable_non_ssl_port', action='store_true')
register_cli_argument('redis', 'shard_count', type=int)
register_cli_argument('redis', 'subnet_id')
Example #7
0
    if parsed_args.resource_group_name and parsed_args.webapp:
        rg = parsed_args.resource_group_name
        webapp = parsed_args.webapp
        slot = getattr(parsed_args, 'slot', None)
        result = _generic_site_operation(rg, webapp, 'get_site_host_name_bindings', slot)
        # workaround an api defect, that 'name' is '<webapp>/<hostname>'
        return [r.name.split('/', 1)[1] for r in result]


# pylint: disable=line-too-long
# PARAMETER REGISTRATION
name_arg_type = CliArgumentType(options_list=('--name', '-n'), metavar='NAME')
sku_arg_type = CliArgumentType(help='The pricing tiers, e.g., F1(Free), D1(Shared), B1(Basic Small), B2(Basic Medium), B3(Basic Large), S1(Standard Small), P1(Premium Small), etc',
                               **enum_choice_list(['F1', 'FREE', 'D1', 'SHARED', 'B1', 'B2', 'B3', 'S1', 'S2', 'S3', 'P1', 'P2', 'P3']))
webapp_name_arg_type = CliArgumentType(configured_default='web', options_list=('--name', '-n'), metavar='NAME',
                                       completer=get_resource_name_completion_list('Microsoft.Web/sites'), id_part='name',
                                       help="name of the web. You can configure the default using 'az configure --defaults web=<name>'")

# use this hidden arg to give a command the right instance, that functionapp commands
# work on function app and webapp ones work on web app
register_cli_argument('webapp', 'app_instance', ignore_type)
register_cli_argument('functionapp', 'app_instance', ignore_type)
# function app doesn't have slot support
register_cli_argument('functionapp', 'slot', ignore_type)

register_cli_argument('appservice', 'resource_group_name', arg_type=resource_group_name_type)
register_cli_argument('appservice', 'location', arg_type=location_type)

register_cli_argument('appservice list-locations', 'linux_workers_enabled', action='store_true', help='get regions which support hosting webapps on Linux workers')
register_cli_argument('appservice list-locations', 'sku', arg_type=sku_arg_type)
register_cli_argument('appservice plan', 'name', arg_type=name_arg_type, help='The name of the app service plan', completer=get_resource_name_completion_list('Microsoft.Web/serverFarms'), id_part='name')
Example #8
0
    try:
        location = parsed_args.location
    except AttributeError:
        location = get_one_of_subscription_locations()
    result = _compute_client_factory().virtual_machine_run_commands.list(location)
    return [r.id for r in result]


# REUSABLE ARGUMENT DEFINITIONS

name_arg_type = CliArgumentType(options_list=('--name', '-n'), metavar='NAME')
multi_ids_type = CliArgumentType(nargs='+')
existing_vm_name = CliArgumentType(overrides=name_arg_type,
                                   configured_default='vm',
                                   help="The name of the Virtual Machine. You can configure the default using `az configure --defaults vm=<name>`",
                                   completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachines'), id_part='name')
vmss_name_type = CliArgumentType(name_arg_type,
                                 configured_default='vmss',
                                 completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'),
                                 help="Scale set name. You can configure the default using `az configure --defaults vmss=<name>`",
                                 id_part='name')
disk_sku = CliArgumentType(required=False, help='underlying storage sku', **enum_choice_list(['Premium_LRS', 'Standard_LRS']))

# ARGUMENT REGISTRATION

register_cli_argument('vm', 'vm_name', existing_vm_name)
register_cli_argument('vm', 'size', completer=get_vm_size_completion_list)
for scope in ['vm', 'disk', 'snapshot', 'image']:
    register_cli_argument(scope, 'tags', tags_type)
register_cli_argument('vm', 'name', arg_type=name_arg_type)
Example #9
0
def load_arguments(self, _):
    (JsonWebKeyOperation, KeyAttributes, JsonWebKeyType, JsonWebKeyCurveName,
     SasTokenType, SasDefinitionAttributes, SecretAttributes,
     CertificateAttributes, StorageAccountAttributes) = self.get_models(
         'JsonWebKeyOperation',
         'KeyAttributes',
         'JsonWebKeyType',
         'JsonWebKeyCurveName',
         'SasTokenType',
         'SasDefinitionAttributes',
         'SecretAttributes',
         'CertificateAttributes',
         'StorageAccountAttributes',
         resource_type=ResourceType.DATA_KEYVAULT)

    (SkuName, KeyPermissions, SecretPermissions, CertificatePermissions,
     StoragePermissions,
     NetworkRuleBypassOptions, NetworkRuleAction) = self.get_models(
         'SkuName', 'KeyPermissions', 'SecretPermissions',
         'CertificatePermissions', 'StoragePermissions',
         'NetworkRuleBypassOptions', 'NetworkRuleAction')

    # ARGUMENT DEFINITIONS
    vault_name_type = CLIArgumentType(
        help='Name of the key vault.',
        options_list=['--vault-name'],
        metavar='NAME',
        id_part=None,
        completer=get_resource_name_completion_list(
            'Microsoft.KeyVault/vaults'))

    # region vault (management)
    with self.argument_context('keyvault') as c:
        c.argument(
            'resource_group_name',
            resource_group_name_type,
            id_part=None,
            required=False,
            help=
            'Proceed only if Key Vault belongs to the specified resource group.',
            validator=validate_resource_group_name)
        c.argument('vault_name',
                   vault_name_type,
                   options_list=['--name', '-n'])
        c.argument(
            'object_id',
            help=
            'a GUID that identifies the principal that will receive permissions'
        )
        c.argument(
            'spn',
            help='name of a service principal that will receive permissions')
        c.argument(
            'upn',
            help='name of a user principal that will receive permissions')
        c.argument('tags', tags_type)
        c.argument(
            'enabled_for_deployment',
            arg_type=get_three_state_flag(),
            help=
            'Allow Virtual Machines to retrieve certificates stored as secrets from the vault.'
        )
        c.argument(
            'enabled_for_disk_encryption',
            arg_type=get_three_state_flag(),
            help=
            'Allow Disk Encryption to retrieve secrets from the vault and unwrap keys.'
        )
        c.argument(
            'enabled_for_template_deployment',
            arg_type=get_three_state_flag(),
            help='Allow Resource Manager to retrieve secrets from the vault.')
        c.argument(
            'enable_soft_delete',
            arg_type=get_three_state_flag(),
            help=
            'Enable vault deletion recovery for the vault, and all contained entities'
        )
        c.argument(
            'enable_purge_protection',
            arg_type=get_three_state_flag(),
            help=
            'Prevents manual purging of deleted vault, and all contained entities'
        )

    with self.argument_context('keyvault',
                               arg_group='Network Rule',
                               min_api='2018-02-14') as c:
        c.argument('bypass',
                   arg_type=get_enum_type(NetworkRuleBypassOptions),
                   help='Bypass traffic for space-separated uses.')
        c.argument('default_action',
                   arg_type=get_enum_type(NetworkRuleAction),
                   help='Default action to apply when no rule matches.')

    with self.argument_context('keyvault create') as c:
        c.argument('resource_group_name',
                   resource_group_name_type,
                   required=True,
                   completer=None,
                   validator=None)
        c.argument('vault_name', completer=None)
        c.argument('sku',
                   arg_type=get_enum_type(SkuName,
                                          default=SkuName.standard.value))
        c.argument(
            'no_self_perms',
            arg_type=get_three_state_flag(),
            help=
            "Don't add permissions for the current user/service principal in the new vault."
        )
        c.argument('location',
                   validator=get_default_location_from_resource_group)

    with self.argument_context('keyvault list') as c:
        c.argument('resource_group_name',
                   resource_group_name_type,
                   validator=None)

    with self.argument_context('keyvault delete-policy') as c:
        c.argument('object_id', validator=validate_principal)

    with self.argument_context('keyvault set-policy',
                               arg_group='Permission') as c:
        c.argument('key_permissions',
                   arg_type=get_enum_type(KeyPermissions),
                   metavar='PERM',
                   nargs='*',
                   help='Space-separated list of key permissions to assign.',
                   validator=validate_policy_permissions)
        c.argument(
            'secret_permissions',
            arg_type=get_enum_type(SecretPermissions),
            metavar='PERM',
            nargs='*',
            help='Space-separated list of secret permissions to assign.')
        c.argument(
            'certificate_permissions',
            arg_type=get_enum_type(CertificatePermissions),
            metavar='PERM',
            nargs='*',
            help='Space-separated list of certificate permissions to assign.')
        c.argument(
            'storage_permissions',
            arg_type=get_enum_type(StoragePermissions),
            metavar='PERM',
            nargs='*',
            help='Space-separated list of storage permissions to assign.')

    with self.argument_context('keyvault network-rule',
                               min_api='2018-02-14') as c:
        c.argument('ip_address', help='IPv4 address or CIDR range.')
        c.argument(
            'subnet',
            help=
            'Name or ID of subnet. If name is supplied, `--vnet-name` must be supplied.'
        )
        c.argument('vnet_name',
                   help='Name of a virtual network.',
                   validator=validate_subnet)
    # endregion

    # region Shared
    for item in ['key', 'secret', 'certificate']:
        with self.argument_context('keyvault ' + item, arg_group='Id') as c:
            c.argument(item + '_name',
                       options_list=['--name', '-n'],
                       help='Name of the {}.'.format(item),
                       id_part='child_name_1',
                       completer=get_keyvault_name_completion_list(item))
            c.argument('vault_base_url',
                       vault_name_type,
                       type=get_vault_base_url_type(self.cli_ctx),
                       id_part=None)
            c.argument(
                item + '_version',
                options_list=['--version', '-v'],
                help='The {} version. If omitted, uses the latest version.'.
                format(item),
                default='',
                required=False,
                completer=get_keyvault_version_completion_list(item))

        for cmd in ['backup', 'delete', 'download', 'set-attributes', 'show']:
            with self.argument_context('keyvault {} {}'.format(item, cmd),
                                       arg_group='Id') as c:
                c.extra(
                    'identifier',
                    options_list=['--id'],
                    help=
                    'Id of the {}.  If specified all other \'Id\' arguments should be omitted.'
                    .format(item),
                    validator=validate_vault_id(item))
                c.argument(
                    item + '_name',
                    help='Name of the {}. Required if --id is not specified.'.
                    format(item),
                    required=False)
                c.argument(
                    'vault_base_url',
                    help=
                    'Name of the key vault. Required if --id is not specified.',
                    required=False)
                c.argument(item + '_version', required=False)

        for cmd in ['purge', 'recover', 'show-deleted']:
            with self.argument_context('keyvault {} {}'.format(item, cmd),
                                       arg_group='Id') as c:
                c.extra(
                    'identifier',
                    options_list=['--id'],
                    help=
                    'The recovery id of the {}.  If specified all other \'Id\' arguments should be omitted.'
                    .format(item),
                    validator=validate_vault_id('deleted' + item))
                c.argument(
                    item + '_name',
                    help='Name of the {}. Required if --id is not specified.'.
                    format(item),
                    required=False)
                c.argument(
                    'vault_base_url',
                    help=
                    'Name of the key vault. Required if --id is not specified.',
                    required=False)
                c.argument(item + '_version', required=False)
    # endregion

    # region keys
    with self.argument_context('keyvault key') as c:
        c.argument(
            'key_ops',
            arg_type=get_enum_type(JsonWebKeyOperation),
            options_list=['--ops'],
            nargs='*',
            help='Space-separated list of permitted JSON web key operations.')

    for scope in ['keyvault key create', 'keyvault key import']:
        with self.argument_context(scope) as c:
            c.argument('protection',
                       arg_type=get_enum_type(['software', 'hsm']),
                       options_list=['--protection', '-p'],
                       help='Specifies the type of key protection.')
            c.argument('disabled',
                       arg_type=get_three_state_flag(),
                       help='Create key in disabled state.')
            c.argument('key_size', options_list=['--size'], type=int)
            c.argument('expires',
                       default=None,
                       help='Expiration UTC datetime  (Y-m-d\'T\'H:M:S\'Z\').',
                       type=datetime_type)
            c.argument(
                'not_before',
                default=None,
                help=
                'Key not usable before the provided UTC datetime  (Y-m-d\'T\'H:M:S\'Z\').',
                type=datetime_type)

    with self.argument_context('keyvault key create') as c:
        c.argument('kty',
                   arg_type=get_enum_type(JsonWebKeyType),
                   validator=validate_key_type)
        c.argument('curve', arg_type=get_enum_type(JsonWebKeyCurveName))

    with self.argument_context('keyvault key import',
                               arg_group='Key Source') as c:
        c.argument('pem_file',
                   type=file_type,
                   help='PEM file containing the key to be imported.',
                   completer=FilesCompleter(),
                   validator=validate_key_import_source)
        c.argument('pem_password', help='Password of PEM file.')
        c.argument(
            'byok_file',
            type=file_type,
            help=
            'BYOK file containing the key to be imported. Must not be password protected.',
            completer=FilesCompleter())

    with self.argument_context('keyvault key backup') as c:
        c.argument('file_path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   help='Local file path in which to store key backup.')

    with self.argument_context('keyvault key restore') as c:
        c.argument('file_path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   help='Local key backup from which to restore key.')

    with self.argument_context('keyvault key set-attributes') as c:
        c.attributes_argument('key', KeyAttributes)
    # endregion

    # region KeyVault Secret
    with self.argument_context('keyvault secret set') as c:
        c.argument(
            'content_type',
            options_list=['--description'],
            help=
            'Description of the secret contents (e.g. password, connection string, etc)'
        )
        c.attributes_argument('secret', SecretAttributes, create=True)

    with self.argument_context('keyvault secret set',
                               arg_group='Content Source') as c:
        c.argument(
            'value',
            options_list=['--value'],
            help=
            "Plain text secret value. Cannot be used with '--file' or '--encoding'",
            required=False)
        c.extra(
            'file_path',
            options_list=['--file', '-f'],
            type=file_type,
            help="Source file for secret. Use in conjunction with '--encoding'",
            completer=FilesCompleter())
        c.extra(
            'encoding',
            arg_type=get_enum_type(secret_encoding_values, default='utf-8'),
            options_list=['--encoding', '-e'],
            help=
            'Source file encoding. The value is saved as a tag (`file-encoding=<val>`) and used during download to automatically encode the resulting file.'
        )

    with self.argument_context('keyvault secret set-attributes') as c:
        c.attributes_argument('secret', SecretAttributes)

    with self.argument_context('keyvault secret download') as c:
        c.argument('file_path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   help='File to receive the secret contents.')
        c.argument(
            'encoding',
            arg_type=get_enum_type(secret_encoding_values),
            options_list=['--encoding', '-e'],
            help=
            "Encoding of the destination file. By default, will look for the 'file-encoding' tag on the secret. Otherwise will assume 'utf-8'.",
            default=None)
    # endregion

    # region KeyVault Storage Account

    with self.argument_context('keyvault storage', arg_group='Id') as c:
        c.argument(
            'storage_account_name',
            options_list=['--name', '-n'],
            help='Name to identify the storage account in the vault.',
            id_part='child_name_1',
            completer=get_keyvault_name_completion_list('storage_account'))
        c.argument('vault_base_url',
                   vault_name_type,
                   type=get_vault_base_url_type(self.cli_ctx),
                   id_part=None)

    for scope in ['keyvault storage add', 'keyvault storage update']:
        with self.argument_context(scope) as c:
            c.extra('disabled',
                    arg_type=get_three_state_flag(),
                    help='Add the storage account in a disabled state.',
                    validator=validate_storage_disabled_attribute(
                        'storage_account_attributes',
                        StorageAccountAttributes))
            c.ignore('storage_account_attributes')
            c.argument('auto_regenerate_key',
                       arg_type=get_three_state_flag(),
                       required=False)
            c.argument(
                'regeneration_period',
                help=
                'The key regeneration time duration specified in ISO-8601 format, such as "P30D" for rotation every 30 days.'
            )
    for scope in ['backup', 'show', 'update', 'remove', 'regenerate-key']:
        with self.argument_context('keyvault storage ' + scope,
                                   arg_group='Id') as c:
            c.extra(
                'identifier',
                options_list=['--id'],
                help=
                'Id of the storage account.  If specified all other \'Id\' arguments should be omitted.',
                validator=validate_storage_account_id)
            c.argument(
                'storage_account_name',
                required=False,
                help=
                'Name to identify the storage account in the vault. Required if --id is not specified.'
            )
            c.argument(
                'vault_base_url',
                help=
                'Name of the key vault. Required if --id is not specified.',
                required=False)

    with self.argument_context('keyvault storage backup') as c:
        c.argument(
            'file_path',
            options_list=['--file', '-f'],
            type=file_type,
            completer=FilesCompleter(),
            help='Local file path in which to store storage account backup.')

    with self.argument_context('keyvault storagerestore') as c:
        c.argument(
            'file_path',
            options_list=['--file', '-f'],
            type=file_type,
            completer=FilesCompleter(),
            help='Local key backup from which to restore storage account.')

    with self.argument_context('keyvault storage sas-definition',
                               arg_group='Id') as c:
        c.argument(
            'storage_account_name',
            options_list=['--account-name'],
            help='Name to identify the storage account in the vault.',
            id_part='child_name_1',
            completer=get_keyvault_name_completion_list('storage_account'))
        c.argument('sas_definition_name',
                   options_list=['--name', '-n'],
                   help='Name to identify the SAS definition in the vault.',
                   id_part='child_name_2')

    for scope in [
            'keyvault storage sas-definition create',
            'keyvault storage sas-definition update'
    ]:
        with self.argument_context(scope) as c:
            c.extra('disabled',
                    arg_type=get_three_state_flag(),
                    help='Add the storage account in a disabled state.',
                    validator=validate_storage_disabled_attribute(
                        'sas_definition_attributes', SasDefinitionAttributes))
            c.ignore('sas_definition_attributes')
            c.argument('sas_type', arg_type=get_enum_type(SasTokenType))
            c.argument(
                'template_uri',
                help=
                'The SAS definition token template signed with the key 00000000.  In the case of an account token this is only the sas token itself, for service tokens, the full service endpoint url along with the sas token.  Tokens created according to the SAS definition will have the same properties as the template.'
            )
            c.argument(
                'validity_period',
                help=
                'The validity period of SAS tokens created according to the SAS definition in ISO-8601, such as "PT12H" for 12 hour tokens.'
            )
            c.argument('auto_regenerate_key', arg_type=get_three_state_flag())

    for scope in [
            'keyvault storage sas-definition delete',
            'keyvault storage sas-definition show',
            'keyvault storage sas-definition update'
    ]:
        with self.argument_context(scope, arg_group='Id') as c:
            c.extra(
                'identifier',
                options_list=['--id'],
                help=
                'Id of the SAS definition.  If specified all other \'Id\' arguments should be omitted.',
                validator=validate_sas_definition_id)
            c.argument(
                'storage_account_name',
                required=False,
                help=
                'Name to identify the storage account in the vault. Required if --id is not specified.'
            )
            c.argument(
                'sas_definition_name',
                required=False,
                help=
                'Name to identify the SAS definition in the vault. Required if --id is not specified.'
            )
            c.argument(
                'vault_base_url',
                help=
                'Name of the key vault. Required if --id is not specified.',
                required=False)
    # endregion

    # KeyVault Certificate
    with self.argument_context('keyvault certificate') as c:
        c.argument(
            'validity',
            type=int,
            help=
            'Number of months the certificate is valid for. Overrides the value specified with --policy/-p'
        )

    # TODO: Remove workaround when https://github.com/Azure/azure-rest-api-specs/issues/1153 is fixed
    with self.argument_context('keyvault certificate create') as c:
        c.attributes_argument('certificate',
                              CertificateAttributes,
                              True,
                              ignore=['expires', 'not_before'])

    with self.argument_context('keyvault certificate set-attributes') as c:
        c.attributes_argument('certificate',
                              CertificateAttributes,
                              ignore=['expires', 'not_before'])

    for item in ['create', 'set-attributes', 'import']:
        with self.argument_context('keyvault certificate ' + item) as c:
            c.argument(
                'certificate_policy',
                options_list=['--policy', '-p'],
                help=
                'JSON encoded policy defintion. Use @{file} to load from a file.',
                type=get_json_object)

    with self.argument_context('keyvault certificate import') as c:
        c.argument(
            'certificate_data',
            options_list=['--file', '-f'],
            completer=FilesCompleter(),
            help=
            'PKCS12 file or PEM file containing the certificate and private key.',
            type=certificate_type)
        c.argument(
            'password',
            help=
            "If the private key in certificate is encrypted, the password used for encryption."
        )
        c.extra('disabled',
                arg_type=get_three_state_flag(),
                help='Import the certificate in disabled state.')

    with self.argument_context('keyvault certificate download') as c:
        c.argument('file_path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   help='File to receive the binary certificate contents.')
        c.argument(
            'encoding',
            arg_type=get_enum_type(certificate_format_values),
            options_list=['--encoding', '-e'],
            help=
            'Encoding of the certificate. DER will create a binary DER formatted x509 certificate, and PEM will create a base64 PEM x509 certificate.'
        )

    # TODO: Fix once service side issue is fixed that there is no way to list pending certificates
    with self.argument_context('keyvault certificate pending') as c:
        c.argument('certificate_name',
                   options_list=['--name', '-n'],
                   help='Name of the pending certificate.',
                   id_part='child_name_1',
                   completer=None)

    with self.argument_context('keyvault certificate pending merge') as c:
        c.argument(
            'x509_certificates',
            options_list=['--file', '-f'],
            type=file_type,
            completer=FilesCompleter(),
            help=
            'File containing the certificate or certificate chain to merge.',
            validator=validate_x509_certificate_chain)
        c.attributes_argument('certificate', CertificateAttributes, True)

    with self.argument_context('keyvault certificate pending cancel') as c:
        c.ignore('cancellation_requested')

    with self.argument_context('keyvault certificate contact') as c:
        c.argument('contact_email',
                   options_list=['--email'],
                   help='Contact e-mail address. Must be unique.')
        c.argument('contact_name',
                   options_list=['--name'],
                   help='Full contact name.')
        c.argument('contact_phone',
                   options_list=['--phone'],
                   help='Contact phone number.')

    with self.argument_context('keyvault certificate issuer admin') as c:
        c.argument(
            'email',
            options_list=['--email'],
            help='Admin e-mail address. Must be unique within the vault.')
        c.argument('name', options_list=['--name'], help='Full admin name.')
        c.argument('phone',
                   options_list=['--phone'],
                   help='Amin phone number.')

    with self.argument_context('keyvault certificate issuer') as c:
        c.argument('issuer_name', help='Certificate issuer name.')
        c.argument('disabled',
                   arg_type=get_three_state_flag(),
                   help='Set issuer to disabled state.')
        c.argument('enabled',
                   arg_type=get_three_state_flag(),
                   help='Set issuer enabled state.')

    with self.argument_context('keyvault certificate issuer',
                               arg_group='Issuer Credential') as c:
        c.argument('account_id')
        c.argument('password')

    with self.argument_context('keyvault certificate issuer',
                               arg_group='Organization Detail') as c:
        c.argument('organization_id')
        c.argument('admin_first_name')
        c.argument('admin_last_name')
        c.argument('admin_email')
        c.argument('admin_phone')
Example #10
0
def load_arguments(self, _):

    from azure.mgmt.cosmosdb.models.cosmos_db_enums import KeyKind, DefaultConsistencyLevel, DatabaseAccountKind

    with self.argument_context('cosmosdb') as c:
        c.argument('account_name', arg_type=name_type, help='Name of the Cosmos DB database account', completer=get_resource_name_completion_list('Microsoft.DocumentDb/databaseAccounts'), id_part='name')
        c.argument('database_id', options_list=['--db-name', '-d'], help='Database Name')

    for scope in ['cosmosdb create', 'cosmosdb update']:
        with self.argument_context(scope) as c:
            c.argument('account_name', completer=None)
            c.ignore('resource_group_location')
            c.argument('locations', nargs='+', validator=validate_locations, help="space-separated locations in 'regionName=failoverPriority' format. E.g eastus=0 westus=1. Failover priority values are 0 for write regions and greater than 0 for read regions. A failover priority value must be unique and less than the total number of regions. Default: single region account in the location of the specified resource group.")
            c.argument('tags', arg_type=tags_type)
            c.argument('default_consistency_level', arg_type=get_enum_type(DefaultConsistencyLevel), help="default consistency level of the Cosmos DB database account")
            c.argument('max_staleness_prefix', type=int, help="when used with Bounded Staleness consistency, this value represents the number of stale requests tolerated. Accepted range for this value is 1 - 2,147,483,647")
            c.argument('max_interval', type=int, help="when used with Bounded Staleness consistency, this value represents the time amount of staleness (in seconds) tolerated. Accepted range for this value is 1 - 100")
            c.argument('ip_range_filter', nargs='+', validator=validate_ip_range_filter, help="firewall support. Specifies the set of IP addresses or IP address ranges in CIDR form to be included as the allowed list of client IPs for a given database account. IP addresses/ranges must be comma-separated and must not contain any spaces")
            c.argument('kind', arg_type=get_enum_type(DatabaseAccountKind), help='The type of Cosmos DB database account to create')
            c.argument('enable_automatic_failover', arg_type=get_three_state_flag(), help='Enables automatic failover of the write region in the rare event that the region is unavailable due to an outage. Automatic failover will result in a new write region for the account and is chosen based on the failover priorities configured for the account.')
            c.argument('capabilities', nargs='+', validator=validate_capabilities, help='set custom capabilities on the Cosmos DB database account.')
            c.argument('enable_virtual_network', arg_type=get_three_state_flag(), help='Enables virtual network on the Cosmos DB database account')
            c.argument('virtual_network_rules', nargs='+', validator=validate_virtual_network_rules, help='ACL\'s for virtual network')

    with self.argument_context('cosmosdb regenerate-key') as c:
        c.argument('key_kind', arg_type=get_enum_type(KeyKind))

    with self.argument_context('cosmosdb failover-priority-change') as c:
        c.argument('failover_policies', validator=validate_failover_policies, help="space-separated failover policies in 'regionName=failoverPriority' format. E.g eastus=0 westus=1", nargs='+')

    with self.argument_context('cosmosdb collection') as c:
        c.argument('collection_id', options_list=['--collection-name', '-c'], help='Collection Name')
        c.argument('throughput', type=int, help='Offer Throughput')
        c.argument('partition_key_path', help='Partition Key Path, e.g., \'/properties/name\'')
        c.argument('indexing_policy', type=shell_safe_json_parse, completer=FilesCompleter(), help='Indexing Policy, you can enter it as a string or as a file, e.g., --indexing-policy @policy-file.json)')
        c.argument('default_ttl', type=int, help='Default TTL')
Example #11
0
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long

from azure.cli.core.commands.parameters import \
    location_type, enum_choice_list, get_resource_name_completion_list, CliArgumentType
from azure.cli.core.commands import register_cli_argument
from azure.mgmt.iothub.models.iot_hub_client_enums import IotHubSku
from ._factory import iot_hub_service_factory
from .custom import iot_device_list, KeyType


def get_device_id_completion_list(prefix, action, parsed_args, **kwargs):  # pylint: disable=unused-argument
    client = iot_hub_service_factory(kwargs)
    return [d.device_id for d in iot_device_list(client, parsed_args.hub_name, top=100)] if parsed_args.hub_name else []

hub_name_type = CliArgumentType(completer=get_resource_name_completion_list('Microsoft.Devices/IotHubs'),
                                help='IoT Hub name.')

register_cli_argument('iot hub', 'hub_name', hub_name_type, options_list=('--name', '-n'))
for subgroup in ['consumer-group', 'policy', 'job']:
    register_cli_argument('iot hub {}'.format(subgroup), 'hub_name', options_list=('--hub-name',))

register_cli_argument('iot device', 'hub_name', hub_name_type)

register_cli_argument('iot', 'device_id', options_list=('--device-id', '-d'), help='Device Id.',
                      completer=get_device_id_completion_list)

# Arguments for 'iot hub consumer-group' group
register_cli_argument('iot hub consumer-group', 'consumer_group_name', options_list=('--name', '-n'),
                      help='Event hub consumer group name.')
register_cli_argument('iot hub consumer-group', 'event_hub_name', help='Target event hub name.')
Example #12
0
    get_urn_aliases_completion_list, get_vm_size_completion_list,
    get_vm_run_command_completion_list)
from azure.cli.command_modules.vm._validators import (
    validate_nsg_name, validate_vm_nics, validate_vm_nic, validate_vm_disk,
    validate_asg_names_or_ids)

# REUSABLE ARGUMENT DEFINITIONS

name_arg_type = CLIArgumentType(options_list=['--name', '-n'], metavar='NAME')
multi_ids_type = CLIArgumentType(nargs='+')
existing_vm_name = CLIArgumentType(
    overrides=name_arg_type,
    configured_default='vm',
    help=
    "The name of the Virtual Machine. You can configure the default using `az configure --defaults vm=<name>`",
    completer=get_resource_name_completion_list(
        'Microsoft.Compute/virtualMachines'),
    id_part='name')
existing_disk_name = CLIArgumentType(
    overrides=name_arg_type,
    help='The name of the managed disk',
    completer=get_resource_name_completion_list('Microsoft.Compute/disks'),
    id_part='name')
existing_snapshot_name = CLIArgumentType(
    overrides=name_arg_type,
    help='The name of the snapshot',
    completer=get_resource_name_completion_list('Microsoft.Compute/snapshots'),
    id_part='name')
existing_image_name = CLIArgumentType(
    overrides=name_arg_type,
    help='The name of the custom image',
    completer=get_resource_name_completion_list('Microsoft.Compute/images'),
Example #13
0
def load_arguments(self, _):
    signalr_name_type = CLIArgumentType(options_list='--signalr-name', help='Name of the SignalR.', id_part='name')

    with self.argument_context('signalr') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('signalr_name', signalr_name_type, options_list=['--name', '-n'],
                   completer=get_resource_name_completion_list(SIGNALR_RESOURCE_TYPE),
                   help='Name of signalr service.')
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('signalr create') as c:
        c.argument('sku', help='The sku name of the signalr service. E.g. Standard_S1')
        c.argument('unit_count', help='The number of signalr service unit count', type=int)
        c.argument('service_mode', help='The service mode which signalr service will be working on', choices=SIGNALR_SERVICE_MODE_TYPE)
        c.argument('enable_message_logs', help='The switch for messaging logs which signalr service will generate or not', arg_type=get_three_state_flag())
        c.argument('allowed_origins', options_list=['--allowed-origins', '-a'], nargs='*', help='space separated origins that should be allowed to make cross-origin calls (for example: http://example.com:12345). To allow all, use "*"')

    with self.argument_context('signalr update') as c:
        c.argument('sku', help='The sku name of the signalr service. E.g. Standard_S1')
        c.argument('unit_count', help='The number of signalr service unit count', type=int)
        c.argument('service_mode', help='The service mode which signalr service will be working on', choices=SIGNALR_SERVICE_MODE_TYPE)
        c.argument('enable_message_logs', help='The switch for messaging logs which signalr service will generate or not', arg_type=get_three_state_flag())
        c.argument('allowed_origins', options_list=['--allowed-origins', '-a'], nargs='*', help='space separated origins that should be allowed to make cross-origin calls (for example: http://example.com:12345). To allow all, use "*"')

    for scope in ['signalr create', 'signalr update']:
        with self.argument_context(scope, arg_group='Network Rule') as c:
            c.argument('default_action', arg_type=get_enum_type(['Allow', 'Deny']), help='Default action to apply when no rule matches.', required=False)

    with self.argument_context('signalr key renew') as c:
        c.argument('key_type', help='The name of access key to regenerate', choices=SIGNALR_KEY_TYPE)

    with self.argument_context('signalr key list') as c:
        c.argument('signalr_name', id_part=None)

    with self.argument_context('signalr cors add') as c:
        c.argument('allowed_origins', options_list=['--allowed-origins', '-a'], nargs='*', help='space separated origins that should be allowed to make cross-origin calls (for example: http://example.com:12345). To allow all, use "*"')

    with self.argument_context('signalr cors remove') as c:
        c.argument('allowed_origins', options_list=['--allowed-origins', '-a'], nargs='*', help='space separated origins that should be allowed to make cross-origin calls (for example: http://example.com:12345). To allow all, use "*"')

    with self.argument_context('signalr cors update') as c:
        c.argument('allowed_origins', options_list=['--allowed-origins', '-a'], nargs='*', help='space separated origins that should be allowed to make cross-origin calls (for example: http://example.com:12345). To allow all, use "*"')

    with self.argument_context('signalr cors list') as c:
        c.argument('signalr_name', id_part=None)

    # Network Rule
    with self.argument_context('signalr network-rule update') as c:
        c.argument('connection_name', nargs='*', help='Space-separeted list of private endpoint connection name.', required=False, arg_group='Private Endpoint Connection')
        c.argument('public_network', arg_type=get_three_state_flag(), help='Set rules for public network.', required=False, arg_group='Public Network')
        c.argument('allow', nargs='*', help='The allowed virtual network rule. Space-separeted list of scope to assign. Allowed values: ClientConnection, ServerConnection, RESTAPI', type=SignalRRequestType, required=False)
        c.argument('deny', nargs='*', help='The denied virtual network rule. Space-separeted list of scope to assign. Allowed values: ClientConnection, ServerConnection, RESTAPI', type=SignalRRequestType, required=False)

    with self.argument_context('signalr network-rule list') as c:
        c.argument('signalr_name', id_part=None)

    # Upstream Settings
    with self.argument_context('signalr upstream update') as c:
        c.argument('template', action=UpstreamTemplateAddAction, nargs='+', help='Template item for upstream settings. Use key=value pattern to set properties. Supported keys are "url-template", "hub-pattern", "event-pattern", "category-pattern".')

    with self.argument_context('signalr upstream list') as c:
        c.argument('signalr_name', id_part=None)

    # Managed Identity
    with self.argument_context('signalr identity assign') as c:
        c.argument('identity', help="Assigns managed identities to the service. Use '[system]' to refer to the system-assigned identity or a resource ID to refer to a user-assigned identity. You can only assign either on of them.")
Example #14
0
def load_arguments(self, _):
    from ._completers import subnet_completion_list, cluster_admin_account_completion_list, \
        cluster_user_group_completion_list, get_resource_name_completion_list_under_subscription
    from knack.arguments import CLIArgumentType
    from azure.mgmt.hdinsight.models import Tier, JsonWebKeyEncryptionAlgorithm, ResourceProviderConnection
    from argcomplete.completers import FilesCompleter
    node_size_type = CLIArgumentType(arg_group='Node',
                                     help='The size of the node. See also: https://docs.microsoft.com/azure/'
                                          'hdinsight/hdinsight-hadoop-provision-linux-clusters#configure-cluster-size')

    # cluster
    with self.argument_context('hdinsight') as c:
        # Cluster
        c.argument('cluster_name', arg_type=name_type,
                   completer=get_resource_name_completion_list('Microsoft.HDInsight/clusters'),
                   help='The name of the cluster.')
        c.argument('tags', tags_type)
        c.argument('no_validation_timeout', action='store_true',
                   help='Permit timeout error during argument validation phase. If omitted, '
                        'validation timeout error will be permitted.')
        c.argument('cluster_version', options_list=['--version', '-v'], arg_group='Cluster',
                   help='The HDInsight cluster version. See also: https://docs.microsoft.com/azure/'
                        'hdinsight/hdinsight-component-versioning#supported-hdinsight-versions')
        c.argument('cluster_type', options_list=['--type', '-t'], arg_group='Cluster',
                   completer=get_generic_completion_list(known_cluster_types),
                   help='Type of HDInsight cluster, like: {}. '
                        'See also: https://docs.microsoft.com/azure/hdinsight/hdinsight-'
                        'hadoop-provision-linux-clusters#cluster-types'.format(', '.join(known_cluster_types)))
        c.argument('component_version', arg_group='Cluster', nargs='*', validator=validate_component_version,
                   help='The versions of various Hadoop components, in space-'
                        'separated versions in \'component=version\' format. Example: '
                        'Spark=2.0 Hadoop=2.7.3 '
                        'See also: https://docs.microsoft.com/azure/hdinsight/hdinsight'
                        '-component-versioning#hadoop-components-available-with-different-'
                        'hdinsight-versions')
        c.argument('cluster_configurations', arg_group='Cluster', type=shell_safe_json_parse,
                   completer=FilesCompleter(),
                   help='Extra configurations of various components. '
                        'Configurations may be supplied from a file using the `@{path}` syntax or a JSON string. '
                        'See also: https://docs.microsoft.com/azure/hdinsight/'
                        'hdinsight-hadoop-customize-cluster-bootstrap')
        c.argument('cluster_tier', arg_type=get_enum_type(Tier), arg_group='Cluster',
                   help='The tier of the cluster')
        c.argument('esp', arg_group='Cluster', action='store_true',
                   help='Specify to create cluster with Enterprise Security Package. If omitted, '
                        'creating cluster with Enterprise Security Package will not not allowed.')
        c.argument('idbroker', arg_group='Cluster', action='store_true',
                   help='Specify to create ESP cluster with HDInsight ID Broker. If omitted, '
                        'creating ESP cluster with HDInsight ID Broker will not not allowed.')
        c.argument('minimal_tls_version', arg_type=get_enum_type(['1.0', '1.1', '1.2']),
                   arg_group='Cluster', help='The minimal supported TLS version.')

        # HTTP
        c.argument('http_username', options_list=['--http-user', '-u'], arg_group='HTTP',
                   help='HTTP username for the cluster.  Default: admin.')
        c.argument('http_password', options_list=['--http-password', '-p'], arg_group='HTTP',
                   help='HTTP password for the cluster. Will prompt if not given.')

        # SSH
        c.argument('ssh_username', options_list=['--ssh-user', '-U'], arg_group='SSH',
                   help='SSH username for the cluster nodes.')
        c.argument('ssh_password', options_list=['--ssh-password', '-P'], arg_group='SSH',
                   help='SSH password for the cluster nodes. If none specified, uses the HTTP password.')
        c.argument('ssh_public_key', options_list=['--ssh-public-key', '-K'], arg_group='SSH',
                   help='SSH public key for the cluster nodes.')

        # Node
        c.argument('headnode_size', arg_type=node_size_type,
                   help='Incoming BREAKING CHANGE: The default value "large" will be removed in next CLI version.'
                        'The size of the node. See also: https://docs.microsoft.com/azure/'
                        'hdinsight/hdinsight-hadoop-provision-linux-clusters#configure-cluster-size')
        c.argument('workernode_size', arg_type=node_size_type,
                   help='Incoming BREAKING CHANGE: The default value "large" will be removed in next CLI version.'
                        'The size of the node. See also: https://docs.microsoft.com/azure/'
                        'hdinsight/hdinsight-hadoop-provision-linux-clusters#configure-cluster-size')
        c.argument('workernode_data_disks_per_node', arg_group='Node',
                   help='The number of data disks to use per worker node.')
        c.argument('workernode_data_disk_storage_account_type', arg_group='Node',
                   arg_type=get_enum_type(['standard_lrs', 'premium_lrs']),
                   help='The type of storage account that will be used for the data disks: standard_lrs or premium_lrs')
        c.argument('workernode_data_disk_size', arg_group='Node',
                   help='The size of the data disk in GB, e.g. 1023.')
        c.argument('zookeepernode_size', arg_type=node_size_type)
        c.argument('edgenode_size', arg_type=node_size_type)
        c.argument('kafka_management_node_size', arg_type=node_size_type)
        c.argument('workernode_count', options_list=['--workernode-count', '-c'], arg_group='Node',
                   help='The number of worker nodes in the cluster.')
        c.argument('kafka_management_node_count', arg_group='Node',
                   help='The number of kafka management node in the cluster')

        # Storage
        c.argument('storage_account', arg_group='Storage', validator=validate_storage_account,
                   completer=get_resource_name_completion_list_under_subscription('Microsoft.Storage/storageAccounts'),
                   help='The name or ID of the storage account.')
        c.argument('storage_account_key', arg_group='Storage',
                   help='The storage account key. A key can be retrieved automatically '
                        'if the user has access to the storage account.')
        c.argument('storage_default_container', arg_group='Storage', options_list=['--storage-container'],
                   help='The storage container the cluster will use. '
                        'Uses the cluster name if none was specified. (WASB only)')
        c.argument('storage_default_filesystem', arg_group='Storage', options_list=['--storage-filesystem'],
                   help='The storage filesystem the cluster will use. '
                        'Uses the cluster name if none was specified. (DFS only)')
        c.argument('storage_account_managed_identity', arg_group='Storage', validator=validate_storage_msi,
                   completer=get_resource_name_completion_list_under_subscription(
                       'Microsoft.ManagedIdentity/userAssignedIdentities'),
                   help='User-assigned managed identity with access to the storage account filesystem. '
                        'Only required when storage account type is Azure Data Lake Storage Gen2.')

        # Network
        c.argument('vnet_name', arg_group='Network', validator=validate_subnet,
                   completer=get_resource_name_completion_list_under_subscription('Microsoft.Network/virtualNetworks'),
                   help='The name of a virtual network.')
        c.argument('subnet', arg_group='Network',
                   completer=subnet_completion_list,
                   help='The name or ID of subnet. If name is supplied, `--vnet-name` must be supplied.')

        # Script Action
        c.argument('script_action_name', arg_group='Script Action', help='The name of the script action.')
        c.argument('script_uri', arg_group='Script Action', help='The URI to the script.')
        c.argument('script_parameters', arg_group='Script Action', help='The parameters for the script.')

        # Domain Service
        c.argument('domain', arg_group='Domain Service', validator=validate_domain_service,
                   completer=get_resource_name_completion_list_under_subscription('Microsoft.AAD/domainServices'),
                   help='The name or resource ID of the user\'s Azure Active Directory Domain Service. '
                        'Required only when create cluster with Enterprise Security Package.')
        c.argument('cluster_users_group_dns', arg_group='Domain Service', nargs='+',
                   completer=cluster_user_group_completion_list,
                   help='A space-delimited list of Distinguished Names for cluster user groups. '
                        'Required only when create cluster with Enterprise Security Package. ')
        c.argument('cluster_admin_password', arg_group='Domain Service',
                   help='The domain admin password. '
                        'Required only when create cluster with Enterprise Security Package.')
        c.argument('cluster_admin_account', arg_group='Domain Service',
                   completer=cluster_admin_account_completion_list,
                   help='The domain user account that will have admin privileges on the cluster. '
                        'Required only when create cluster with Enterprise Security Package.')
        c.argument('ldaps_urls', arg_group='Domain Service', nargs='+',
                   help='A space-delimited list of LDAPS protocol URLs to communicate with the Active Directory. '
                        'Required only when create cluster with Enterprise Security Package.')

        # Customer Managed Key
        c.argument('encryption_vault_uri', arg_group='Customer Managed Key',
                   help='Base key vault URI where the customers key is located eg. https://myvault.vault.azure.net')
        c.argument('encryption_key_name', arg_group='Customer Managed Key',
                   help='Key name that is used for enabling disk encryption.')
        c.argument('encryption_key_version', arg_group='Customer Managed Key',
                   help='Key version that is used for enabling disk encryption.')
        c.argument('encryption_algorithm', arg_type=get_enum_type(JsonWebKeyEncryptionAlgorithm),
                   arg_group='Customer Managed Key', help='Algorithm identifier for encryption.')

        # Kafka Rest Proxy
        c.argument('kafka_client_group_id', arg_group='Kafka Rest Proxy',
                   help='The client AAD security group id for Kafka Rest Proxy')
        c.argument('kafka_client_group_name', arg_group='Kafka Rest Proxy',
                   help='The client AAD security group name for Kafka Rest Proxy')

        # Managed Service Identity
        c.argument('assign_identity', arg_group='Managed Service Identity', validator=validate_msi,
                   completer=get_resource_name_completion_list_under_subscription(
                       'Microsoft.ManagedIdentity/userAssignedIdentities'),
                   help="The name or ID of user assigned identity.")

        # Encryption In Transit
        c.argument('encryption_in_transit', arg_group='Encryption In Transit', arg_type=get_three_state_flag(),
                   help='Indicates whether enable encryption in transit.')

        # Encryption At Host
        c.argument('encryption_at_host', arg_group='Encryption At Host', arg_type=get_three_state_flag(),
                   help='Indicates whether enable encryption at host or not.')

        # Autoscale Configuration
        c.argument('autoscale_type', arg_group='Autoscale Configuration', arg_type=get_enum_type(known_autoscale_types),
                   help='The autoscale type.')
        c.argument('autoscale_min_workernode_count', type=int,
                   options_list=['--autoscale-min-workernode-count', '--autoscale-min-count'],
                   arg_group='Autoscale Configuration',
                   help='The minimal workernode count for Load-based atuoscale.')
        c.argument('autoscale_max_workernode_count', type=int,
                   options_list=['--autoscale-max-workernode-count', '--autoscale-max-count'],
                   arg_group='Autoscale Configuration',
                   help='The max workernode count for Load-based atuoscale.')
        c.argument('timezone', arg_group='Autoscale Configuration', validator=validate_timezone_name,
                   completer=get_generic_completion_list(AUTOSCALE_TIMEZONES),
                   help='The timezone for schedule autoscale type. Values from `az hdinsight autoscale list-timezones`')
        c.argument('days', nargs='+', arg_group='Autoscale Configuration',
                   arg_type=get_enum_type(week_days),
                   completer=get_generic_completion_list(week_days),
                   help='A space-delimited list of schedule day.')
        c.argument('time', arg_group='Autoscale Configuration', validator=validate_time,
                   help='The 24-hour time in the form of xx:xx in days.')
        c.argument('autoscale_workernode_count', type=int,
                   options_list=['--autoscale-workernode-count', '--autoscale-count'],
                   arg_group='Autoscale Configuration',
                   help='The scheduled workernode count.')

        # relay outbound and private link
        c.argument('resource_provider_connection', options_list=['--resource-provider-connection', '--rp-connection'],
                   arg_group='Resource provider connection',
                   arg_type=get_enum_type(ResourceProviderConnection), help='The resource provider connection type')
        c.argument('enable_private_link', arg_group='Private Link', arg_type=get_three_state_flag(),
                   help='Indicate whether enable the private link or not.')

        # compute isolation
        c.argument('enable_compute_isolation', options_list=['--enable-compute-isolation', '--compute-isolation'],
                   arg_group="Compute Isolation", arg_type=get_three_state_flag(),
                   help='Indicate whether enable compute isolation or not.')
        c.argument('host_sku', arg_group='Compute Isolation', help="The dedicated host sku of compute isolation.")

        # resize
        with self.argument_context('hdinsight resize') as c:
            c.argument('target_instance_count', options_list=['--workernode-count', '-c'],
                       help='The target worker node instance count for the operation.', required=True)

        # application
        with self.argument_context('hdinsight application') as c:
            c.argument('cluster_name', options_list=['--cluster-name'],
                       completer=get_resource_name_completion_list('Microsoft.HDInsight/clusters'),
                       help='The name of the cluster.')
            c.argument('application_name', arg_type=name_type,
                       help='The constant value for the application name.')
            c.argument('application_type', options_list=['--type', '-t'],
                       arg_type=get_enum_type(['CustomApplication', 'RServer']),
                       help='The application type.')
            c.argument('marketplace_identifier', options_list=['--marketplace-id'],
                       help='The marketplace identifier.')
            c.argument('https_endpoint_access_mode', arg_group='HTTPS Endpoint',
                       options_list=['--access-mode'],
                       help='The access mode for the application.')
            c.argument('https_endpoint_destination_port', arg_group='HTTPS Endpoint',
                       options_list=['--destination-port'],
                       help='The destination port to connect to.')
            c.argument('sub_domain_suffix', arg_group='HTTPS Endpoint', help='The subdomain suffix of the application.')
            c.argument('disable_gateway_auth', arg_group='HTTPS Endpoint', arg_type=get_three_state_flag(),
                       help='Indicates whether to disable gateway authentication. '
                            'Default is to enable gateway authentication. Default: false. ')
            c.argument('tags', tags_type)
            c.argument('ssh_password', options_list=['--ssh-password', '-P'], arg_group='SSH',
                       help='SSH password for the cluster nodes.')

        # script action
        with self.argument_context('hdinsight script-action') as c:
            c.argument('cluster_name', options_list=['--cluster-name'],
                       completer=get_resource_name_completion_list('Microsoft.HDInsight/clusters'),
                       help='The name of the cluster.')
            c.argument('roles', nargs='+', completer=get_generic_completion_list(known_role_types),
                       help='A space-delimited list of roles (nodes) where the script will be executed. '
                            'Valid roles are {}.'.format(', '.join(known_role_types)))
            c.argument('persist_on_success', help='If the scripts needs to be persisted.')
            c.argument('script_action_name', arg_type=name_type, arg_group=None,
                       help='The name of the script action.')
            c.argument('script_uri', arg_group=None, help='The URI to the script.')
            c.argument('script_parameters', arg_group=None, help='The parameters for the script.')
            c.argument('script_execution_id', options_list=['--execution-id'], arg_group=None,
                       help='The script execution id')

        with self.argument_context('hdinsight script-action delete') as c:
            c.argument('script_name', arg_type=name_type, arg_group=None, help='The name of the script.')

        # Monitoring
        with self.argument_context('hdinsight monitor') as c:
            c.argument('workspace', validator=validate_workspace,
                       completer=get_resource_name_completion_list_under_subscription(
                           'Microsoft.OperationalInsights/workspaces'),
                       help='The name, resource ID or workspace ID of Log Analytics workspace.')
            c.argument('primary_key', help='The certificate for the Log Analytics workspace. '
                                           'Required when workspace ID is provided.')
            c.ignore('workspace_type')

        with self.argument_context('hdinsight host') as c:
            c.argument('cluster_name', options_list=['--cluster-name'],
                       completer=get_resource_name_completion_list('Microsoft.HDInsight/clusters'),
                       help='The name of the cluster.')
            c.argument('hosts', options_list=['--host-names'], nargs='+',
                       help='A space-delimited list of host names that need to be restarted.')

        # autoscale
        autoscale_commands = ['create', 'update', 'delete', 'show']
        for command in autoscale_commands:
            with self.argument_context('hdinsight autoscale ' + command) as c:
                c.argument('cluster_name', options_list=['--cluster-name'],
                           completer=get_resource_name_completion_list('Microsoft.HDInsight/clusters'),
                           help='The name of the cluster.')

        for command in ['create', 'update']:
            with self.argument_context('hdinsight autoscale ' + command) as c:
                c.argument('min_workernode_count', type=int, arg_group='Load-based Autoscale',
                           help='The minimal workernode count for Load-based atuoscale.')
                c.argument('max_workernode_count', type=int, arg_group='Load-based Autoscale',
                           help='The max workernode count for Load-based atuoscale.')
                c.argument('timezone', arg_group='Schedule-based Autoscale', validator=validate_timezone_name,
                           completer=get_generic_completion_list(AUTOSCALE_TIMEZONES),
                           help='The timezone for schedule autoscale type. '
                                'Values from `az hdinsight autoscale list-timezones`')

        with self.argument_context('hdinsight autoscale create') as c:
            c.argument('type', arg_type=get_enum_type(known_autoscale_types), help='The autoscale type.')
            c.argument('days', nargs='+', arg_group='Schedule-based Autoscale',
                       arg_type=get_enum_type(week_days),
                       completer=get_generic_completion_list(week_days),
                       help='A space-delimited list of schedule day.')
            c.argument('time', arg_group='Schedule-based Autoscale', validator=validate_time,
                       help='The 24-hour time in the form xx:xx in days.')
            c.argument('workernode_count', type=int, options_list=['--workernode-count'],
                       arg_group='Schedule-based Autoscale',
                       help='The schedule workernode count.')
            c.argument('yes', options_list=['--yes', '-y'], help='Do not prompt for confirmation.', action='store_true')

        # autoscale condition
        autoscale_condition_commands = ['create', 'update', 'delete', 'list']
        for command in autoscale_condition_commands:
            with self.argument_context('hdinsight autoscale condition ' + command) as c:
                c.argument('cluster_name', options_list=['--cluster-name'],
                           completer=get_resource_name_completion_list('Microsoft.HDInsight/clusters'),
                           help='The name of the cluster.')

        for command in ['create', 'update']:
            with self.argument_context('hdinsight autoscale condition ' + command) as c:
                c.argument('days', nargs='+', arg_group=None, arg_type=get_enum_type(week_days),
                           completer=get_generic_completion_list(week_days),
                           help='A space-delimited list of schedule day.')
                c.argument('time', arg_group=None, validator=validate_time,
                           help='The 24-hour time in the form xx:xx in days.')
                c.argument('workernode_count', type=int, options_list=['--workernode-count'], arg_group=None,
                           help='The schedule workernode count.')
        for command in ['create', 'update']:
            with self.argument_context('hdinsight autoscale condition ' + command) as c:
                c.argument('index', type=int, help='The schedule condition index which starts with 0.')

        with self.argument_context('hdinsight autoscale condition delete') as c:
            c.argument('index', nargs='+', type=int,
                       help='The Space-separated list of condition indices which starts with 0 to delete.')
Example #15
0
    IotDpsSku, AllocationPolicy, AccessRightsDescription)
from azure.cli.command_modules.iot.shared import (EndpointType,
                                                  RouteSourceType,
                                                  EncodingFormat, RenewKeyType,
                                                  AuthenticationType)
from .custom import KeyType, SimpleAccessRights
from ._validators import (validate_policy_permissions, validate_retention_days,
                          validate_fileupload_notification_max_delivery_count,
                          validate_fileupload_notification_ttl,
                          validate_fileupload_sas_ttl, validate_feedback_ttl,
                          validate_feedback_lock_duration,
                          validate_feedback_max_delivery_count,
                          validate_c2d_max_delivery_count, validate_c2d_ttl)

hub_name_type = CLIArgumentType(
    completer=get_resource_name_completion_list('Microsoft.Devices/IotHubs'),
    help='IoT Hub name.')

dps_name_type = CLIArgumentType(options_list=['--dps-name'],
                                completer=get_resource_name_completion_list(
                                    'Microsoft.Devices/ProvisioningServices'),
                                help='IoT Provisioning Service name')

app_name_type = CLIArgumentType(completer=get_resource_name_completion_list(
    'Microsoft.IoTCentral/IoTApps'),
                                help='IoT Central application name.')


def load_arguments(self, _):  # pylint: disable=too-many-statements
    # Arguments for IoT DPS
    with self.argument_context('iot dps') as c:
Example #16
0
def load_arguments(self, _):

    from azext_front_door.vendored_sdks.models import (
        PolicyMode, FrontDoorProtocol, FrontDoorHealthProbeMethod,
        FrontDoorCertificateSource, FrontDoorQuery, ActionType, RuleType,
        TransformType, FrontDoorRedirectType, FrontDoorRedirectProtocol,
        MinimumTLSVersion, Transform, HeaderActionType, RulesEngineOperator,
        RulesEngineMatchVariable, FrontDoorForwardingProtocol,
        MatchProcessingBehavior, PolicyRequestBodyCheck, SkuName, ResourceType)

    frontdoor_name_type = CLIArgumentType(
        options_list=['--front-door-name', '-f'],
        help='Name of the Front Door.',
        completer=get_resource_name_completion_list(
            'Microsoft.Network/frontdoors'),
        id_part='name')
    waf_policy_name_type = CLIArgumentType(
        options_list='--policy-name',
        help='Name of the WAF policy.',
        completer=get_resource_name_completion_list(
            'Microsoft.Network/frontDoorWebApplicationFirewallPolicies'),
        id_part='name')
    rules_engine_name_type = CLIArgumentType(
        options_list=['--rules-engine-name', '-r'],
        help='Name of the Rules Engine.',
        completer=get_fd_subresource_completion_list('rules_engines'),
        id_part='child_name_1')

    # region FrontDoors
    fd_subresources = [{
        'name': 'backend-pool',
        'display': 'backend pool',
        'ref': 'backend_pools'
    }, {
        'name': 'frontend-endpoint',
        'display': 'frontend endpoint',
        'ref': 'frontend_endpoints'
    }, {
        'name': 'load-balancing',
        'display': 'load balancing settings',
        'ref': 'load_balancing_settings'
    }, {
        'name': 'probe',
        'display': 'health probe',
        'ref': 'health_probe_settings'
    }, {
        'name': 'routing-rule',
        'display': 'routing rule',
        'ref': 'routing_rules'
    }]
    for item in fd_subresources:
        with self.argument_context('network front-door {}'.format(
                item['name'])) as c:
            c.argument('item_name',
                       options_list=['--name', '-n'],
                       help='Name of the {}'.format(item['display']),
                       completer=get_fd_subresource_completion_list(
                           item['ref']),
                       id_part='child_name_1')
            c.argument('front_door_name', frontdoor_name_type, id_part=None)
            c.argument('resource_name', frontdoor_name_type, id_part=None)

    with self.argument_context('network front-door') as c:
        c.argument('front_door_name',
                   frontdoor_name_type,
                   options_list=['--name', '-n'])
        c.argument('friendly_name', help='Friendly name of the Front Door.')
        c.argument('tags', tags_type)
        c.argument('disabled',
                   arg_type=get_three_state_flag(),
                   help='Create in a disabled state.')
        c.argument('enabled',
                   arg_type=get_three_state_flag(positive_label='Enabled',
                                                 negative_label='Disabled',
                                                 return_label=True),
                   help='Enabled status.')

    with self.argument_context('network front-door',
                               arg_group='Frontend Endpoint') as c:
        c.argument('frontend_host_name',
                   help='Domain name of the frontend endpoint.')

    with self.argument_context('network front-door', arg_group='HTTPS') as c:
        c.argument('certificate_source',
                   arg_type=get_enum_type(FrontDoorCertificateSource),
                   help='Certificate source to enable HTTPS.')
        c.argument(
            'secret_name',
            help=
            'The name of the Key Vault secret representing the full certificate PFX'
        )
        c.argument(
            'secret_version',
            help=
            'The version of the Key Vault secret representing the full certificate PFX, '
            'the "Latest" version will always be used if not specified and your certificate will be auto-rotated when a new version of secret generated.'
        )
        c.argument(
            'vault_id',
            help=
            'The resource id of the Key Vault containing the SSL certificate')
        c.argument(
            'minimum_tls_version',
            arg_type=get_enum_type(MinimumTLSVersion),
            help=
            'The minimum TLS version required from the clients to establish an SSL handshake with Front Door.'
        )

    with self.argument_context('network front-door',
                               arg_group='BackendPools Settings') as c:
        c.argument(
            'enforce_certificate_name_check',
            arg_type=get_three_state_flag(positive_label='Enabled',
                                          negative_label='Disabled',
                                          return_label=True),
            help=
            'Whether to disable certificate name check on HTTPS requests to all backend pools. No effect on non-HTTPS requests.'
        )
        c.argument(
            'send_recv_timeout',
            type=int,
            help=
            'Send and receive timeout in seconds on forwarding request to the backend. When timeout is reached, the request fails and returns.'
        )

    with self.argument_context('network front-door', arg_group='Backend') as c:
        c.argument('backend_address', help='FQDN of the backend endpoint.')
        c.argument('backend_host_header',
                   help='Host header sent to the backend.')

    with self.argument_context('network front-door',
                               arg_group='Probe Setting') as c:
        c.argument('probe_path', options_list='--path', help='Path to probe.')
        c.argument('probe_protocol',
                   options_list='--protocol',
                   arg_type=get_enum_type(FrontDoorProtocol),
                   help='Protocol to use for sending probes.')
        c.argument('probe_interval',
                   options_list='--interval',
                   type=int,
                   help='Interval in seconds between probes.')
        c.argument('enabled',
                   arg_type=get_three_state_flag(positive_label='Enabled',
                                                 negative_label='Disabled',
                                                 return_label=True),
                   help='Enabled status.')
        c.argument(
            'probe_method',
            options_list='--probeMethod',
            arg_type=get_enum_type(FrontDoorHealthProbeMethod),
            help=
            'Configures which HTTP method to use to probe the backends defined under backendPools.'
        )

    with self.argument_context('network front-door',
                               arg_group='Routing Rule') as c:
        c.argument(
            'accepted_protocols',
            nargs='+',
            help='Space-separated list of protocols to accept. Default: Http')
        c.argument(
            'patterns_to_match',
            options_list='--patterns',
            nargs='+',
            help='Space-separated list of patterns to match. Default: \'/*\'.')
        c.argument('forwarding_protocol',
                   arg_type=get_enum_type(FrontDoorForwardingProtocol),
                   help='Protocol to use for forwarding traffic.')
        c.argument(
            'route_type',
            arg_type=get_enum_type(RouteType),
            help=
            'Route type to define how Front Door should handle requests for this route i.e. forward them to a backend or redirect the users to a different URL.'
        )

    with self.argument_context('network front-door purge-endpoint') as c:
        c.argument(
            'content_paths',
            nargs='+',
            help=
            "The path to the content to be purged. Can describe a file path or a wildcard directory."
        )

    with self.argument_context(
            'network front-door check-name-availability') as c:
        c.argument('name', help='The resource name to be validated.')
        c.argument(
            'resource_type',
            arg_type=get_enum_type(ResourceType),
            help='The type of the resource whose name is to be validated.')

    with self.argument_context('network front-door backend-pool') as c:
        c.argument('load_balancing_settings',
                   options_list='--load-balancing',
                   help='Name or ID of the load balancing settings.',
                   validator=validate_load_balancing_settings)
        c.argument('probe_settings',
                   options_list='--probe',
                   help='Name or ID of the probe settings.',
                   validator=validate_probe_settings)

    with self.argument_context('network front-door frontend-endpoint') as c:
        c.argument('host_name', help='Domain name of the frontend endpoint.')
        c.argument('session_affinity_enabled',
                   arg_type=get_three_state_flag(positive_label='Enabled',
                                                 negative_label='Disabled',
                                                 return_label=True),
                   help='Whether to allow session affinity on this host.')
        c.argument('session_affinity_ttl',
                   help='The TTL to use in seconds for session affinity.',
                   type=int)
        c.argument('waf_policy',
                   help='Name or ID of a web application firewall policy.',
                   validator=validate_waf_policy)

    with self.argument_context('network front-door load-balancing') as c:
        c.argument(
            'additional_latency',
            type=int,
            help=
            'The additional latency in milliseconds for probes to fall in the lowest latency bucket.'
        )
        c.argument(
            'sample_size',
            type=int,
            help=
            'The number of samples to consider for load balancing decisions.')
        c.argument(
            'successful_samples_required',
            options_list=['--successful-samples-required', '-s'],
            type=int,
            help=
            'The number of samples within the sample period that must succeed.'
        )

    with self.argument_context('network front-door probe') as c:
        c.argument('path', help='Path to probe.')
        c.argument('protocol',
                   arg_type=get_enum_type(FrontDoorProtocol),
                   help='Protocol to use for sending probes.')
        c.argument('interval', help='Interval in seconds between probes.')

    for scope in ['backend-pool', 'backend-pool backend']:
        arg_group = 'Backend' if scope == 'backend-pool' else None
        with self.argument_context('network front-door {}'.format(scope),
                                   arg_group=arg_group) as c:
            c.argument('address', help='FQDN of the backend endpoint.')
            c.argument('host_header', help='Host header sent to the backend.')
            c.argument(
                'priority',
                type=int,
                help=
                'Priority to use for load balancing. Higher priorities will not be used for load balancing if any lower priority backend is healthy.'
            )
            c.argument('http_port', type=int, help='HTTP TCP port number.')
            c.argument('https_port', type=int, help='HTTPS TCP port number.')
            c.argument(
                'weight',
                type=int,
                help='Weight of this endpoint for load balancing purposes.')
            c.argument(
                'private_link_alias',
                help=
                'The Alias of the Private Link resource. Populating this optional field indicates that this backend is \'Private\'.'
            )
            c.argument(
                'private_link_resource_id',
                help=
                'The Resource Id of the Private Link. Populating this optional field indicates that this backend is \'Private\'.'
            )
            c.argument(
                'private_link_location',
                help=
                'The location of the Private Link resource. Required only if \'privateLinkResourceId\' is populated.'
            )
            c.argument(
                'private_link_approval_message',
                help=
                'A custom message to be included in the approval request to connect to the Private Link.'
            )
            c.argument('backend_host_header',
                       help='Host header sent to the backend.')
            c.argument('backend_pool_name',
                       options_list='--pool-name',
                       help='Name of the backend pool.')
            c.argument(
                'index',
                type=int,
                help='Index of the backend to remove (starting with 1).')

    with self.argument_context('network front-door routing-rule',
                               arg_group=None) as c:
        c.argument(
            'accepted_protocols',
            nargs='+',
            help='Space-separated list of protocols to accept. Default: Http')
        c.argument(
            'patterns_to_match',
            options_list='--patterns',
            nargs='+',
            help='Space-separated list of patterns to match. Default: \'/*\'.')
        c.argument(
            'rules_engine',
            help=
            'Name or ID of a Rules Engine configuration. To unlink property, \"--remove rulesEngine\"',
            validator=validate_rules_engine)
        c.argument(
            'frontend_endpoints',
            help='Space-separated list of frontend endpoint names or IDs.',
            nargs='+',
            validator=validate_frontend_endpoints)
    with self.argument_context('network front-door routing-rule',
                               arg_group='Forward Routing Rule') as c:
        c.argument(
            'backend_pool',
            help=
            "Name or ID of a backend pool. It's required to create a Forward routing rule.",
            validator=validate_backend_pool)
        c.argument('forwarding_protocol',
                   arg_type=get_enum_type(FrontDoorForwardingProtocol),
                   help='Protocol to use for forwarding traffic.')
        c.argument(
            'custom_forwarding_path',
            help=
            'Custom path used to rewrite resource paths matched by this rule. Leave empty to use incoming path.'
        )
        c.argument('caching',
                   arg_type=get_three_state_flag(positive_label='Enabled',
                                                 negative_label='Disabled',
                                                 return_label=False),
                   help='Whether to enable caching for this route.')
        c.argument(
            'cache_duration',
            help=
            'The duration for which the content needs to be cached. Allowed format is ISO 8601 duration'
        )
        c.argument('dynamic_compression',
                   arg_type=get_three_state_flag(positive_label='Enabled',
                                                 negative_label='Disabled',
                                                 return_label=True),
                   help='Use dynamic compression for cached content.')
        c.argument(
            'query_parameter_strip_directive',
            arg_type=get_enum_type(FrontDoorQuery),
            help='Treatment of URL query terms when forming the cache key.')
        c.argument(
            'query_parameters',
            help=
            'Query parameters to include or exclude (comma separated) when using query-parameter-strip-directive type StripAllExcept or StripOnly respectively.'
        )
    with self.argument_context('network front-door routing-rule',
                               arg_group='Redirect Routing Rule') as c:
        c.argument(
            'redirect_type',
            arg_type=get_enum_type(FrontDoorRedirectType),
            help='The redirect type the rule will use when redirecting traffic.'
        )
        c.argument(
            'redirect_protocol',
            arg_type=get_enum_type(FrontDoorRedirectProtocol),
            help=
            'The protocol of the destination to where the traffic is redirected.'
        )
        c.argument(
            'custom_host',
            help=
            'Host to redirect. Leave empty to use use the incoming host as the destination host.'
        )
        c.argument(
            'custom_path',
            help=
            'The full path to redirect. Path cannot be empty and must start with /. Leave empty to use the incoming path as destination path.'
        )
        c.argument(
            'custom_fragment',
            help=
            'Fragment to add to the redirect URL. Fragment is the part of the URL that comes after #. Do not include the #.'
        )
        c.argument(
            'custom_query_string',
            help=
            'The set of query strings to be placed in the redirect URL. Setting this value would replace any existing query string; leave empty to preserve the incoming query string. Query string must be in <key>=<value> format. The first ? and & will be added automatically so do not include them in the front, but do separate multiple query strings with &.'
        )
    # endregion

    # region WafPolicy
    with self.argument_context('network front-door waf-policy') as c:
        c.argument('tags', tags_type)
        c.argument('disabled',
                   arg_type=get_three_state_flag(),
                   help='Create in a disabled state.')
        c.argument('enabled',
                   arg_type=get_three_state_flag(positive_label='Enabled',
                                                 negative_label='Disabled',
                                                 return_label=True),
                   help='Enabled status.')
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('mode',
                   arg_type=get_enum_type(PolicyMode),
                   help='Firewall policy mode.')
        c.argument('policy_name',
                   waf_policy_name_type,
                   options_list=['--name', '-n'])
        c.argument('redirect_url', help='URL used for redirect rule action.')
        c.argument('custom_block_response_status_code',
                   help='HTTP status to return for blocked requests.')
        c.argument('custom_block_response_body',
                   help='Body to return for blocked requests.')
        c.argument(
            'request_body_check',
            arg_type=get_three_state_flag(positive_label='Enabled',
                                          negative_label='Disabled',
                                          return_label=True),
            help='Disabled or Enabled status. Default value is Disabled')
        c.argument(
            'sku',
            arg_type=get_enum_type(SkuName),
            help=
            'SKU of Firewall policy. This field cannot be updated after creation. Default value is Classic_AzureFrontDoor'
        )

    with self.argument_context(
            'network front-door waf-policy managed-rules add') as c:
        c.argument('policy_name', waf_policy_name_type)
        c.argument('action',
                   arg_type=get_enum_type(ActionType),
                   help='Action for applied rulesets.')
        c.argument('rule_set_type',
                   options_list=['--type'],
                   help='ID of the ruleset to apply.')
        c.argument('version', help='Rule set version.')

    with self.argument_context(
            'network front-door waf-policy managed-rules list') as c:
        c.argument('policy_name', waf_policy_name_type, id_part=None)

    with self.argument_context(
            'network front-door waf-policy managed-rules override add') as c:
        c.argument('policy_name', waf_policy_name_type)
        c.argument('action',
                   arg_type=get_enum_type(ActionType),
                   help='Action for applied rulesets.')
        c.argument('rule_set_type',
                   options_list=['--type'],
                   help='ID of the ruleset to override.')
        c.argument(
            'rule_group_id',
            help='ID of the rule group containing the rule to override.')
        c.argument('rule_id', help='ID of the rule to override.')
        c.argument('disabled', help='Whether to disable the rule.')

    with self.argument_context(
            'network front-door waf-policy managed-rules override remove'
    ) as c:
        c.argument('policy_name', waf_policy_name_type)
        c.argument('rule_set_type',
                   options_list=['--type'],
                   help='ID of the ruleset with the override to remove.')
        c.argument(
            'rule_group_id',
            help='ID of the rule group containing the override to remove.')
        c.argument('rule_id', help='ID of the rule override to remove.')

    with self.argument_context(
            'network front-door waf-policy managed-rules override list') as c:
        c.argument('policy_name', waf_policy_name_type, id_part=None)
        c.argument('rule_set_type',
                   options_list=['--type'],
                   help='ID of the ruleset with the overrides to list.')

    with self.argument_context(
            'network front-door waf-policy managed-rules exclusion add') as c:
        c.argument('policy_name', waf_policy_name_type)
        c.argument('rule_set_type',
                   options_list=['--type'],
                   help='ID of the ruleset to exclusion.')
        c.argument(
            'rule_group_id',
            help='ID of the rule group containing the rule to exclusion.')
        c.argument('rule_id', help='ID of the rule to apply exclusion.')
        c.argument(
            'match_variable',
            help=
            'Which kind of variable\'s content will be ignored, e.g. RequestHeaderNames, RequestCookieNames, QueryStringArgNames, RequestBodyPostArgNames.'
        )
        c.argument(
            'operator',
            help=
            'Operator used to compare the variable name to the value, e.g. Equals, Contains, StartsWith, EndsWith, EqualsAny.'
        )
        c.argument('value', help='Values to match the variable name against.')

    with self.argument_context(
            'network front-door waf-policy managed-rules exclusion remove'
    ) as c:
        c.argument('policy_name', waf_policy_name_type)
        c.argument('rule_set_type',
                   options_list=['--type'],
                   help='ID of the ruleset with the exclusion to remove.')
        c.argument(
            'rule_group_id',
            help='ID of the rule group containing the exclusion to remove.')
        c.argument('rule_id', help='ID of the rule to remove from exclusion.')
        c.argument(
            'match_variable',
            help=
            'Which kind of variable\'s content will be ignored, e.g. RequestHeaderNames, RequestCookieNames, QueryStringArgNames, RequestBodyPostArgNames.'
        )
        c.argument(
            'operator',
            help=
            'Operator used to compare the variable name to the value, e.g. Equals, Contains, StartsWith, EndsWith, EqualsAny.'
        )
        c.argument('value', help='Values to match the variable name against.')

    with self.argument_context(
            'network front-door waf-policy managed-rules exclusion list') as c:
        c.argument('policy_name', waf_policy_name_type, id_part=None)
        c.argument('rule_set_type',
                   options_list=['--type'],
                   help='ID of the ruleset with the exclusions to list.')
        c.argument(
            'rule_group_id',
            help='ID of the rule group containing the exclusions to list.')
        c.argument('rule_id', help='ID of the rule to list exclusion for.')

    with self.argument_context(
            'network front-door waf-policy managed-rules remove') as c:
        c.argument('policy_name', waf_policy_name_type)
        c.argument('rule_set_type',
                   options_list=['--type'],
                   help='ID of the ruleset to remove.')

    with self.argument_context(
            'network front-door waf-policy managed-rule-definition list') as c:
        c.argument('policy_name', waf_policy_name_type)

    with self.argument_context(
            'network front-door waf-policy rule create') as c:
        c.argument('rule_name',
                   options_list=['--name', '-n'],
                   help='Name of the custom rule.',
                   id_part='child_name_1')
        c.argument('policy_name', waf_policy_name_type)
        c.argument('priority', type=int, help='Priority of the rule.')
        c.argument('rate_limit_duration',
                   type=int,
                   help='Rate limit duration in minutes.')
        c.argument('rate_limit_threshold',
                   type=int,
                   help='Rate limit threshold.')
        c.argument('rule_type',
                   arg_type=get_enum_type(RuleType),
                   help='Type of rule.')
        c.argument('action',
                   arg_type=get_enum_type(ActionType),
                   help='Rule action.')
        c.argument('disabled', help='Whether to disable the rule.')

    with self.argument_context(
            'network front-door waf-policy rule delete') as c:
        c.argument('rule_name',
                   options_list=['--name', '-n'],
                   help='Name of the custom rule.',
                   id_part='child_name_1')
        c.argument('policy_name', waf_policy_name_type)

    with self.argument_context('network front-door waf-policy rule show') as c:
        c.argument('rule_name',
                   options_list=['--name', '-n'],
                   help='Name of the custom rule.',
                   id_part='child_name_1')
        c.argument('policy_name', waf_policy_name_type)

    with self.argument_context(
            'network front-door waf-policy rule update') as c:
        c.argument('rule_name',
                   options_list=['--name', '-n'],
                   help='Name of the custom rule.',
                   id_part='child_name_1')
        c.argument('policy_name', waf_policy_name_type)
        c.argument('priority', type=int, help='Priority of the rule.')
        c.argument('rate_limit_duration',
                   type=int,
                   help='Rate limit duration in minutes.')
        c.argument('rate_limit_threshold',
                   type=int,
                   help='Rate limit threshold.')
        c.argument('rule_type',
                   arg_type=get_enum_type(RuleType),
                   help='Type of rule.')
        c.argument('action',
                   arg_type=get_enum_type(ActionType),
                   help='Rule action.')
        c.argument('disabled', help='Whether to disable the rule.')

    with self.argument_context('network front-door waf-policy rule list') as c:
        c.argument('policy_name', waf_policy_name_type, id_part=None)

    with self.argument_context(
            'network front-door waf-policy rule match-condition add') as c:
        c.argument('rule_name',
                   options_list=['--name', '-n'],
                   help='Name of the custom rule.',
                   id_part='child_name_1')
        c.argument('policy_name', waf_policy_name_type)
        c.argument(
            'match_variable',
            help=
            'Variable[.Selector] Request variable to test with optional selector.'
        )
        c.argument('operator',
                   help='Operator used to compare the variable to the values.')
        c.argument('values',
                   nargs='+',
                   help='Space-separated list of values to match against.')
        c.argument('negate',
                   arg_type=get_three_state_flag(),
                   help='Applies "Not" to the operator.')
        c.argument('transforms',
                   nargs='+',
                   arg_type=get_enum_type(TransformType),
                   help='Space-separated list of transforms to apply.')

    with self.argument_context(
            'network front-door waf-policy rule match-condition remove') as c:
        c.argument('rule_name',
                   options_list=['--name', '-n'],
                   help='Name of the custom rule.',
                   id_part='child_name_1')
        c.argument('policy_name', waf_policy_name_type)
        c.argument('index',
                   type=int,
                   help='0-based index of the match condition to remove')

    with self.argument_context(
            'network front-door waf-policy rule match-condition list') as c:
        c.argument('rule_name',
                   options_list=['--name', '-n'],
                   help='Name of the custom rule.')
        c.argument('policy_name', waf_policy_name_type, id_part=None)
    # endregion

    # region RulesEngine
    with self.argument_context('network front-door rules-engine') as c:
        c.argument('front_door_name', frontdoor_name_type, id_part=None)
        c.argument('rules_engine_name',
                   rules_engine_name_type,
                   options_list=['--name', '-n'],
                   id_part=None)

    with self.argument_context('network front-door rules-engine rule') as c:
        c.argument('front_door_name', frontdoor_name_type, id_part=None)
        c.argument('rules_engine_name', rules_engine_name_type, id_part=None)
        c.argument('rule_name',
                   options_list=['--name', '-n'],
                   help='Name of the rule')
        c.argument('action_type',
                   arg_group="Action",
                   arg_type=get_enum_type(['RequestHeader', 'ResponseHeader']),
                   help='Action type to apply for a rule.')
        c.argument('header_action',
                   arg_group="Action",
                   arg_type=get_enum_type(HeaderActionType),
                   help='Header action type for the requests.')
        c.argument('header_name',
                   arg_group="Action",
                   help='Name of the header to modify.')
        c.argument('header_value',
                   arg_group="Action",
                   help='Value of the header.')
        c.argument('match_variable',
                   arg_group="Match Condition",
                   arg_type=get_enum_type(RulesEngineMatchVariable),
                   help='Name of the match condition.')
        c.argument('operator',
                   arg_group="Match Condition",
                   arg_type=get_enum_type(RulesEngineOperator),
                   help='Operator of the match condition.')
        c.argument('match_values',
                   arg_group="Match Condition",
                   nargs='+',
                   help='Space-separated list of values to match against.')
        c.argument('selector',
                   arg_group="Match Condition",
                   help='Optional selector for the match condition variable.')
        c.argument('negate_condition',
                   arg_group="Match Condition",
                   arg_type=get_three_state_flag(),
                   help='Applies "Not" to the operator.')
        c.argument('transforms',
                   arg_group="Match Condition",
                   nargs='+',
                   arg_type=get_enum_type(Transform),
                   help='Space-separated list of transforms to apply.')
        c.argument(
            'priority',
            help=
            'The priority number must start from 0 and consecutive. Rule with greater priority value will be applied later.'
        )
        c.argument(
            'match_processing_behavior',
            arg_type=get_enum_type(MatchProcessingBehavior),
            help=
            'Whether to stop processing rules after conditions in a rule is satisfied.'
        )

    with self.argument_context('network front-door rules-engine rule action',
                               arg_group='Forward Route Override') as c:
        c.argument('action_type',
                   arg_group="Action",
                   arg_type=get_enum_type([
                       'RequestHeader', 'ResponseHeader',
                       'ForwardRouteOverride', 'RedirectRouteOverride'
                   ]),
                   help='Action type to apply for a rule.')
        c.argument('backend_pool',
                   help='Name or ID of a backend pool.',
                   validator=validate_backend_pool)
        c.argument('forwarding_protocol',
                   arg_type=get_enum_type(FrontDoorForwardingProtocol),
                   help='Protocol to use for forwarding traffic.')
        c.argument(
            'custom_forwarding_path',
            help=
            'Custom path used to rewrite resource paths matched by this rule. Leave empty to use incoming path.'
        )
        c.argument('caching',
                   arg_type=get_three_state_flag(positive_label='Enabled',
                                                 negative_label='Disabled',
                                                 return_label=False),
                   help='Whether to enable caching for this route.')
        c.argument(
            'cache_duration',
            help=
            'The duration for which the content needs to be cached. Allowed format is ISO 8601 duration'
        )
        c.argument('dynamic_compression',
                   arg_type=get_three_state_flag(positive_label='Enabled',
                                                 negative_label='Disabled',
                                                 return_label=True),
                   help='Use dynamic compression for cached content.')
        c.argument(
            'query_parameter_strip_directive',
            arg_type=get_enum_type(FrontDoorQuery),
            help='Treatment of URL query terms when forming the cache key.')
        c.argument(
            'query_parameters',
            help=
            'Query parameters to include or exclude (comma separated) when using query-parameter-strip-directive type StripAllExcept or StripOnly respectively.'
        )

    with self.argument_context('network front-door rules-engine rule action',
                               arg_group='Redirect Route Override') as c:
        c.argument(
            'redirect_type',
            arg_type=get_enum_type(FrontDoorRedirectType),
            help='The redirect type the rule will use when redirecting traffic.'
        )
        c.argument(
            'redirect_protocol',
            arg_type=get_enum_type(FrontDoorRedirectProtocol),
            help=
            'The protocol of the destination to where the traffic is redirected.'
        )
        c.argument(
            'custom_host',
            help=
            'Host to redirect. Leave empty to use use the incoming host as the destination host.'
        )
        c.argument(
            'custom_path',
            help=
            'The full path to redirect. Path cannot be empty and must start with /. Leave empty to use the incoming path as destination path.'
        )
        c.argument(
            'custom_fragment',
            help=
            'Fragment to add to the redirect URL. Fragment is the part of the URL that comes after #. Do not include the #.'
        )
        c.argument(
            'custom_query_string',
            help=
            'The set of query strings to be placed in the redirect URL. Setting this value would replace any existing query string; leave empty to preserve the incoming query string. Query string must be in <key>=<value> format. The first ? and & will be added automatically so do not include them in the front, but do separate multiple query strings with &.'
        )

    with self.argument_context(
            'network front-door rules-engine rule condition remove') as c:
        c.argument('index',
                   type=int,
                   help='0-based index of the match condition to remove')

    with self.argument_context(
            'network front-door rules-engine rule action remove') as c:
        c.argument(
            'index',
            type=int,
            help=
            '0-based index of the request or response header action to remove. Index parameter is not required for "ForwardRouteOverride" or "RedirectRouteOverride" action remove'
        )

    with self.argument_context(
            'network front-door rules-engine rule list') as c:
        c.argument('front_door_name', frontdoor_name_type, id_part=None)
        c.argument('rules_engine_name',
                   rules_engine_name_type,
                   options_list=['--name', '-n'],
                   id_part=None)
Example #17
0
def load_arguments(self, _):

    # AKS command argument configuration
    with self.argument_context('aks') as c:
        c.argument('resource_name',
                   name_type,
                   help='Name of the managed cluster.',
                   completer=get_resource_name_completion_list(
                       'Microsoft.ContainerService/ManagedClusters'))
        c.argument('name',
                   name_type,
                   help='Name of the managed cluster.',
                   completer=get_resource_name_completion_list(
                       'Microsoft.ContainerService/ManagedClusters'))
        c.argument('kubernetes_version',
                   options_list=['--kubernetes-version', '-k'],
                   validator=validate_k8s_version)
        c.argument('node_count', options_list=['--node-count', '-c'], type=int)
        c.argument('tags', tags_type)

    with self.argument_context('aks create') as c:
        c.argument('name', validator=validate_linux_host_name)
        c.argument('kubernetes_version',
                   completer=get_k8s_versions_completion_list)
        c.argument('admin_username',
                   options_list=['--admin-username', '-u'],
                   default='azureuser')
        c.argument('windows_admin_username',
                   options_list=['--windows-admin-username'])
        c.argument('windows_admin_password',
                   options_list=['--windows-admin-password'])
        c.argument('dns_name_prefix', options_list=['--dns-name-prefix', '-p'])
        c.argument('generate_ssh_keys',
                   action='store_true',
                   validator=validate_create_parameters)
        c.argument('node_vm_size',
                   options_list=['--node-vm-size', '-s'],
                   completer=get_vm_size_completion_list)
        c.argument('nodepool_name',
                   type=str,
                   default='nodepool1',
                   help='Node pool name, upto 12 alphanumeric characters',
                   validator=validate_nodepool_name)
        c.argument('ssh_key_value',
                   required=False,
                   type=file_type,
                   default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(),
                   validator=validate_ssh_key)
        c.argument('aad_client_app_id')
        c.argument('aad_server_app_id')
        c.argument('aad_server_app_secret')
        c.argument('aad_tenant_id')
        c.argument('dns_service_ip')
        c.argument('docker_bridge_address')
        c.argument('load_balancer_sku')
        c.argument('enable_addons', options_list=['--enable-addons', '-a'])
        c.argument('disable_rbac', action='store_true')
        c.argument('enable_rbac',
                   action='store_true',
                   options_list=['--enable-rbac', '-r'],
                   deprecate_info=c.deprecate(redirect="--disable-rbac",
                                              hide="2.0.45"))
        c.argument('max_pods',
                   type=int,
                   options_list=['--max-pods', '-m'],
                   validator=validate_max_pods)
        c.argument('network_plugin')
        c.argument('network_policy')
        c.argument('no_ssh_key', options_list=['--no-ssh-key', '-x'])
        c.argument('pod_cidr')
        c.argument('service_cidr')
        c.argument('vnet_subnet_id')
        c.argument('workspace_resource_id')
        c.argument('skip_subnet_role_assignment', action='store_true')
        c.argument('enable_cluster_autoscaler', action='store_true')
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('enable_vmss', action='store_true')
        c.argument(
            'node_zones',
            zones_type,
            options_list='--node-zones',
            help=
            '(PREVIEW) Space-separated list of availability zones where agent nodes will be placed.'
        )
        c.argument('enable_pod_security_policy', action='store_true')
        c.argument('node_resource_group')
        c.argument('enable_acr')
        c.argument('acr')

    with self.argument_context('aks update') as c:
        c.argument('enable_cluster_autoscaler',
                   options_list=["--enable-cluster-autoscaler", "-e"],
                   action='store_true')
        c.argument('disable_cluster_autoscaler',
                   options_list=["--disable-cluster-autoscaler", "-d"],
                   action='store_true')
        c.argument('update_cluster_autoscaler',
                   options_list=["--update-cluster-autoscaler", "-u"],
                   action='store_true')
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)
        c.argument('enable_pod_security_policy', action='store_true')
        c.argument('disable_pod_security_policy', action='store_true')
        c.argument('enable_acr')
        c.argument('acr')

    with self.argument_context('aks scale') as c:
        c.argument('nodepool_name',
                   type=str,
                   help='Node pool name, upto 12 alphanumeric characters',
                   validator=validate_nodepool_name)

    with self.argument_context('aks upgrade') as c:
        c.argument('kubernetes_version',
                   completer=get_k8s_upgrades_completion_list)

    with self.argument_context('aks nodepool') as c:
        c.argument('cluster_name', type=str, help='The cluster name.')

    for scope in ['aks nodepool add']:
        with self.argument_context(scope) as c:
            c.argument('nodepool_name',
                       type=str,
                       options_list=['--name', '-n'],
                       validator=validate_nodepool_name,
                       help='The node pool name.')
            c.argument(
                'node_zones',
                zones_type,
                options_list='--node-zones',
                help=
                '(PREVIEW) Space-separated list of availability zones where agent nodes will be placed.'
            )
            c.argument('node_vm_size',
                       options_list=['--node-vm-size', '-s'],
                       completer=get_vm_size_completion_list)
            c.argument('max_pods',
                       type=int,
                       options_list=['--max-pods', '-m'],
                       validator=validate_max_pods)
            c.argument('os_type', type=str)
            c.argument('enable_cluster_autoscaler',
                       options_list=["--enable-cluster-autoscaler", "-e"],
                       action='store_true')

    for scope in [
            'aks nodepool show', 'aks nodepool delete', 'aks nodepool scale',
            'aks nodepool upgrade', 'aks nodepool update'
    ]:
        with self.argument_context(scope) as c:
            c.argument('nodepool_name',
                       type=str,
                       options_list=['--name', '-n'],
                       validator=validate_nodepool_name,
                       help='The node pool name.')

    with self.argument_context('aks nodepool update') as c:
        c.argument('enable_cluster_autoscaler',
                   options_list=["--enable-cluster-autoscaler", "-e"],
                   action='store_true')
        c.argument('disable_cluster_autoscaler',
                   options_list=["--disable-cluster-autoscaler", "-d"],
                   action='store_true')
        c.argument('update_cluster_autoscaler',
                   options_list=["--update-cluster-autoscaler", "-u"],
                   action='store_true')

    with self.argument_context('aks disable-addons') as c:
        c.argument('addons', options_list=['--addons', '-a'])

    with self.argument_context('aks enable-addons') as c:
        c.argument('addons', options_list=['--addons', '-a'])
        c.argument('subnet_name', options_list=['--subnet-name', '-s'])

    with self.argument_context('aks get-credentials') as c:
        c.argument('admin', options_list=['--admin', '-a'], default=False)
        c.argument('path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   default=os.path.join(os.path.expanduser('~'), '.kube',
                                        'config'))
Example #18
0
def load_arguments(self, _):
    from knack.arguments import CLIArgumentType
    from azure.mgmt.cosmosdb.models import KeyKind, DefaultConsistencyLevel, DatabaseAccountKind, TriggerType, TriggerOperation

    with self.argument_context('cosmosdb') as c:
        c.argument('account_name',
                   arg_type=name_type,
                   help='Name of the Cosmos DB database account',
                   completer=get_resource_name_completion_list(
                       'Microsoft.DocumentDb/databaseAccounts'),
                   id_part='name')
        c.argument('database_id',
                   options_list=['--db-name', '-d'],
                   help='Database Name')

    with self.argument_context('cosmosdb create') as c:
        c.argument('account_name', completer=None)

    for scope in ['cosmosdb create', 'cosmosdb update']:
        with self.argument_context(scope) as c:
            c.ignore('resource_group_location')
            c.argument('locations', nargs='+', action=CreateLocation)
            c.argument('tags', arg_type=tags_type)
            c.argument(
                'default_consistency_level',
                arg_type=get_enum_type(DefaultConsistencyLevel),
                help=
                "default consistency level of the Cosmos DB database account")
            c.argument(
                'max_staleness_prefix',
                type=int,
                help=
                "when used with Bounded Staleness consistency, this value represents the number of stale requests tolerated. Accepted range for this value is 1 - 2,147,483,647"
            )
            c.argument(
                'max_interval',
                type=int,
                help=
                "when used with Bounded Staleness consistency, this value represents the time amount of staleness (in seconds) tolerated. Accepted range for this value is 1 - 100"
            )
            c.argument(
                'ip_range_filter',
                nargs='+',
                validator=validate_ip_range_filter,
                help=
                "firewall support. Specifies the set of IP addresses or IP address ranges in CIDR form to be included as the allowed list of client IPs for a given database account. IP addresses/ranges must be comma-separated and must not contain any spaces"
            )
            c.argument('kind',
                       arg_type=get_enum_type(DatabaseAccountKind),
                       help='The type of Cosmos DB database account to create')
            c.argument(
                'enable_automatic_failover',
                arg_type=get_three_state_flag(),
                help=
                'Enables automatic failover of the write region in the rare event that the region is unavailable due to an outage. Automatic failover will result in a new write region for the account and is chosen based on the failover priorities configured for the account.'
            )
            c.argument(
                'capabilities',
                nargs='+',
                validator=validate_capabilities,
                help=
                'set custom capabilities on the Cosmos DB database account.')
            c.argument(
                'enable_virtual_network',
                arg_type=get_three_state_flag(),
                help='Enables virtual network on the Cosmos DB database account'
            )
            c.argument('virtual_network_rules',
                       nargs='+',
                       validator=validate_virtual_network_rules,
                       help='ACL\'s for virtual network')
            c.argument('enable_multiple_write_locations',
                       arg_type=get_three_state_flag(),
                       help="Enable Multiple Write Locations")
            c.argument(
                'disable_key_based_metadata_write_access',
                arg_type=get_three_state_flag(),
                help=
                "Disable write operations on metadata resources (databases, containers, throughput) via account keys"
            )

    for scope in ['cosmosdb regenerate-key', 'cosmosdb keys regenerate']:
        with self.argument_context(scope) as c:
            c.argument('key_kind', arg_type=get_enum_type(KeyKind))

    with self.argument_context('cosmosdb failover-priority-change') as c:
        c.argument(
            'failover_policies',
            validator=validate_failover_policies,
            help=
            "space-separated failover policies in 'regionName=failoverPriority' format. E.g eastus=0 westus=1",
            nargs='+')

    with self.argument_context('cosmosdb network-rule list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('cosmosdb keys list') as c:
        c.argument('account_name', help="Cosmosdb account name", id_part=None)
        c.argument('key_type',
                   arg_type=get_enum_type(CosmosKeyTypes),
                   options_list=['--type'],
                   help="The type of account key.")

    with self.argument_context('cosmosdb network-rule add') as c:
        c.argument('subnet', help="Name or ID of the subnet")
        c.argument(
            'virtual_network',
            options_list=['--vnet-name', '--virtual-network'],
            help=
            "The name of the VNET, which must be provided in conjunction with the name of the subnet"
        )
        c.argument(
            "ignore_missing_vnet_service_endpoint",
            options_list=[
                '--ignore-missing-endpoint',
                '--ignore-missing-vnet-service-endpoint'
            ],
            arg_type=get_three_state_flag(),
            help=
            "Create firewall rule before the virtual network has vnet service endpoint enabled."
        )

    with self.argument_context('cosmosdb network-rule remove') as c:
        c.argument('subnet', help="Name or ID of the subnet")
        c.argument(
            'virtual_network',
            options_list=['--vnet-name', '--virtual-network'],
            help=
            "The name of the VNET, which must be provided in conjunction with the name of the subnet"
        )

    with self.argument_context('cosmosdb collection') as c:
        c.argument('collection_id',
                   options_list=['--collection-name', '-c'],
                   help='Collection Name')
        c.argument('throughput', type=int, help='Offer Throughput (RU/s)')
        c.argument('partition_key_path',
                   help='Partition Key Path, e.g., \'/properties/name\'')
        c.argument(
            'indexing_policy',
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexing Policy, you can enter it as a string or as a file, e.g., --indexing-policy @policy-file.json)'
        )
        c.argument('default_ttl',
                   type=int,
                   help='Default TTL. Provide 0 to disable.')

    with self.argument_context('cosmosdb database') as c:
        c.argument('throughput', type=int, help='Offer Throughput (RU/s)')

    account_name_type = CLIArgumentType(options_list=['--account-name', '-a'],
                                        help="Cosmosdb account name.")
    database_name_type = CLIArgumentType(
        options_list=['--database-name', '-d'], help='Database name.')
    container_name_type = CLIArgumentType(
        options_list=['--container-name', '-c'], help='Container name.')

    # SQL database
    with self.argument_context('cosmosdb sql database') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument(
            'throughput',
            help='The throughput of SQL database (RU/s). Default value is 400')

# SQL container
    with self.argument_context('cosmosdb sql container') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name',
                   options_list=['--name', '-n'],
                   help="Container name")
        c.argument('partition_key_path',
                   options_list=['--partition-key-path', '-p'],
                   help='Partition Key Path, e.g., \'/address/zipcode\'')
        c.argument(
            'default_ttl',
            options_list=['--ttl'],
            type=int,
            help=
            'Default TTL. If the value is missing or set to "-1", items don’t expire. If the value is set to "n", items will expire "n" seconds after last modified time.'
        )
        c.argument(
            'indexing_policy',
            options_list=['--idx'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexing Policy, you can enter it as a string or as a file, e.g., --idx @policy-file.json or '
            + SQL_GREMLIN_INDEXING_POLICY_EXAMPLE)
        c.argument(
            'unique_key_policy',
            options_list=['--unique-key-policy', '-u'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Unique Key Policy, you can enter it as a string or as a file, e.g., --unique-key-policy @policy-file.json or '
            + SQL_UNIQUE_KEY_POLICY_EXAMPLE)
        c.argument(
            'conflict_resolution_policy',
            options_list=['--conflict-resolution-policy', '-c'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Conflict Resolution Policy, you can enter it as a string or as a file, e.g., --conflict-resolution-policy @policy-file.json or '
            + SQL_GREMLIN_CONFLICT_RESOLUTION_POLICY_EXAMPLE)
        c.argument(
            'throughput',
            help='The throughput of SQL container (RU/s). Default value is 400'
        )

# SQL stored procedure
    with self.argument_context('cosmosdb sql stored-procedure') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name', container_name_type)
        c.argument('stored_procedure_name',
                   options_list=['--name', '-n'],
                   help="StoredProcedure name")
        c.argument(
            'stored_procedure_body',
            options_list=['--body', '-b'],
            completer=FilesCompleter(),
            help=
            "StoredProcedure body, you can enter it as a string or as a file, e.g., --body @sprocbody-file.json"
        )

# SQL trigger
    with self.argument_context('cosmosdb sql trigger') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name', container_name_type)
        c.argument('trigger_name',
                   options_list=['--name', '-n'],
                   help="Trigger name")
        c.argument(
            'trigger_body',
            options_list=['--body', '-b'],
            completer=FilesCompleter(),
            help=
            "Trigger body, you can enter it as a string or as a file, e.g., --body @triggerbody-file.json"
        )
        c.argument('trigger_type',
                   options_list=['--type', '-t'],
                   arg_type=get_enum_type(TriggerType),
                   help="Trigger type")
        c.argument('trigger_operation',
                   options_list=['--operation'],
                   arg_type=get_enum_type(TriggerOperation),
                   help="The operation of the trigger.")

# SQL user defined function
    with self.argument_context('cosmosdb sql user-defined-function') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name', container_name_type)
        c.argument('user_defined_function_name',
                   options_list=['--name', '-n'],
                   help="UserDefinedFunction name")
        c.argument(
            'user_defined_function_body',
            options_list=['--body', '-b'],
            completer=FilesCompleter(),
            help=
            "UserDefinedFunction body, you can enter it as a string or as a file, e.g., --body @udfbody-file.json"
        )

# MongoDB
    with self.argument_context('cosmosdb mongodb database') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument(
            'throughput',
            help=
            'The throughput of MongoDB database (RU/s). Default value is 400')

    with self.argument_context('cosmosdb mongodb collection') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('collection_name',
                   options_list=['--name', '-n'],
                   help="Collection name")
        c.argument('shard_key_path',
                   options_list=['--shard'],
                   help="Sharding key path.")
        c.argument(
            'indexes',
            options_list=['--idx'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexes, you can enter it as a string or as a file, e.g., --idx @indexes-file.json or '
            + MONGODB_INDEXES_EXAMPLE)
        c.argument(
            'throughput',
            help=
            'The throughput of MongoDB collection (RU/s). Default value is 400'
        )

# Cassandra
    with self.argument_context('cosmosdb cassandra keyspace') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('keyspace_name',
                   options_list=['--name', '-n'],
                   help="Keyspace name")
        c.argument(
            'throughput',
            help=
            'The throughput of Cassandra keyspace (RU/s). Default value is 400'
        )

    with self.argument_context('cosmosdb cassandra table') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('keyspace_name',
                   options_list=['--keyspace-name', '-k'],
                   help="Keyspace name")
        c.argument('table_name',
                   options_list=['--name', '-n'],
                   help="Table name")
        c.argument(
            'default_ttl',
            options_list=['--ttl'],
            type=int,
            help=
            'Default TTL. If the value is missing or set to "-1", items don’t expire. If the value is set to "n", items will expire "n" seconds after last modified time.'
        )
        c.argument(
            'schema',
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Schema, you can enter it as a string or as a file, e.g., --schema @schema-file.json or '
            + CASSANDRA_SCHEMA_EXAMPLE)
        c.argument(
            'throughput',
            help=
            'The throughput of Cassandra table (RU/s). Default value is 400')

# Gremlin
    with self.argument_context('cosmosdb gremlin database') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument(
            'throughput',
            help='The throughput Gremlin database (RU/s). Default value is 400'
        )

    with self.argument_context('cosmosdb gremlin graph') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('graph_name',
                   options_list=['--name', '-n'],
                   help="Graph name")
        c.argument('partition_key_path',
                   options_list=['--partition-key-path', '-p'],
                   help='Partition Key Path, e.g., \'/address/zipcode\'')
        c.argument(
            'default_ttl',
            options_list=['--ttl'],
            type=int,
            help=
            'Default TTL. If the value is missing or set to "-1", items don’t expire. If the value is set to "n", items will expire "n" seconds after last modified time.'
        )
        c.argument(
            'indexing_policy',
            options_list=['--idx'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexing Policy, you can enter it as a string or as a file, e.g., --idx @policy-file.json or '
            + SQL_GREMLIN_INDEXING_POLICY_EXAMPLE)
        c.argument(
            'conflict_resolution_policy',
            options_list=['--conflict-resolution-policy', '-c'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Conflict Resolution Policy, you can enter it as a string or as a file, e.g., --conflict-resolution-policy @policy-file.json or '
            + SQL_GREMLIN_CONFLICT_RESOLUTION_POLICY_EXAMPLE)
        c.argument(
            'throughput',
            help='The throughput of Gremlin graph (RU/s). Default value is 400'
        )

# Table
    with self.argument_context('cosmosdb table') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('table_name',
                   options_list=['--name', '-n'],
                   help="Table name")
        c.argument('throughput',
                   help='The throughput of Table (RU/s). Default value is 400')

# Throughput
    with self.argument_context('cosmosdb sql database throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of SQL database (RU/s).')

    with self.argument_context('cosmosdb sql container throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name',
                   options_list=['--name', '-n'],
                   help="Container name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of SQL container (RU/s).')

    with self.argument_context('cosmosdb mongodb database throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of MongoDB database (RU/s).')

    with self.argument_context('cosmosdb mongodb collection throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('collection_name',
                   options_list=['--name', '-n'],
                   help="Collection name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of MongoDB collection (RU/s).')

    with self.argument_context('cosmosdb cassandra keyspace throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('keyspace_name',
                   options_list=['--name', '-n'],
                   help="Keyspace name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of Cassandra keyspace (RU/s).')

    with self.argument_context('cosmosdb cassandra table throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('keyspace_name',
                   options_list=['--keyspace-name', '-k'],
                   help="Keyspace name")
        c.argument('table_name',
                   options_list=['--name', '-n'],
                   help="Table name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of Cassandra table (RU/s).')

    with self.argument_context('cosmosdb gremlin database throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of Gremlin database (RU/s).')

    with self.argument_context('cosmosdb gremlin graph throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('graph_name',
                   options_list=['--name', '-n'],
                   help="Grapth name")
        c.argument('throughput',
                   type=int,
                   help='The throughput Gremlin graph (RU/s).')

    with self.argument_context('cosmosdb table throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('table_name',
                   options_list=['--name', '-n'],
                   help="Table name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of Table (RU/s).')
Example #19
0
from azure.cli.command_modules.backup._validators import \
    (datetime_type)


# ARGUMENT DEFINITIONS

allowed_container_types = ['AzureIaasVM']
allowed_workload_types = ['VM', 'AzureFileShare']
allowed_backup_management_types = ['AzureIaasVM', 'AzureStorage']

backup_management_type_help = """Specifiy the backup management type. Define how Azure Backup manages the backup of entities within the ARM resource. For eg: AzureWorkloads refers to workloads installed within Azure VMs, AzureStorage refers to entities within Storage account. Required only if friendly name is used as Container name."""
container_name_help = """Name of the backup container. Accepts 'Name' or 'FriendlyName' from the output of az backup container list command. If 'FriendlyName' is passed then BackupManagementType is required."""
workload_type_help = """Specifiy the type of applications within the Resource which should be discovered and protected by Azure Backup. """
restore_mode_help = """Accepts OriginalLocation or AlternateLocation"""
resolve_conflict_help = "Instruction if there's a conflict with the restored data."
vault_name_type = CLIArgumentType(help='Name of the Recovery services vault.', options_list=['--vault-name', '-v'], completer=get_resource_name_completion_list('Microsoft.RecoveryServices/vaults'))
container_name_type = CLIArgumentType(help=container_name_help, options_list=['--container-name', '-c'])
item_name_type = CLIArgumentType(help='Name of the backed up item.', options_list=['--item-name', '-i'])
policy_name_type = CLIArgumentType(help='Name of the backup policy.', options_list=['--policy-name', '-p'])
job_name_type = CLIArgumentType(help='Name of the job.', options_list=['--name', '-n'])
rp_name_type = CLIArgumentType(help='Name of the recovery point.', options_list=['--rp-name', '-r'])
backup_management_type = CLIArgumentType(help=backup_management_type_help, arg_type=get_enum_type(allowed_backup_management_types), options_list=['--backup-management-type'])
workload_type = CLIArgumentType(help=workload_type_help, arg_type=get_enum_type(allowed_workload_types), options_list=['--workload-type'])
restore_mode_type = CLIArgumentType(help=restore_mode_help, arg_type=get_enum_type(['OriginalLocation', 'AlternateLocation']), options_list=['--restore-mode'])
resolve_conflict_type = CLIArgumentType(help=resolve_conflict_help, arg_type=get_enum_type(['Overwrite', 'Skip']), options_list=['--resolve-conflict'])


# pylint: disable=too-many-statements
def load_arguments(self, _):

    with self.argument_context('backup') as c:
Example #20
0
def load_arguments(self, _):

    # special case for `network nic scale-set list` command alias
    with self.argument_context('network nic scale-set list') as c:
        c.argument('virtual_machine_scale_set_name',
                   options_list=['--vmss-name'],
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/virtualMachineScaleSets'),
                   id_part='name')

    # region MixedScopes
    for scope in ['vm', 'disk', 'snapshot', 'image']:
        with self.argument_context(scope) as c:
            c.argument('tags', tags_type)

    for scope in ['disk', 'snapshot']:
        with self.argument_context(scope) as c:
            c.ignore('source_blob_uri', 'source_disk', 'source_snapshot')
            c.argument(
                'source_storage_account_id',
                help='used when source blob is in a different subscription')
            c.argument('size_gb',
                       options_list=['--size-gb', '-z'],
                       help='size in GB.')
            c.argument(
                'duration_in_seconds',
                help='Time duration in seconds until the SAS access expires',
                type=int)

    for scope in ['disk create', 'snapshot create']:
        with self.argument_context(scope) as c:
            c.argument(
                'source',
                help=
                'source to create the disk/snapshot from, including unmanaged blob uri, managed disk id or name, or snapshot id or name'
            )
    # endregion

    # region Disks
    with self.argument_context('disk') as c:
        c.argument(
            'zone', zone_type, min_api='2017-03-30', options_list=['--zone']
        )  # TODO: --size-gb currently has claimed -z. We can do a breaking change later if we want to.
        c.argument('disk_name',
                   existing_disk_name,
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/disks'))
        c.argument('name', arg_type=name_arg_type)
        c.argument('sku', arg_type=disk_sku)
    # endregion

    # region Identity
    # TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105
    with self.argument_context('identity') as c:
        c.argument('resource_name', arg_type=name_arg_type, id_part='name')

    with self.argument_context('identity create') as c:
        c.argument('location', get_location_type(self.cli_ctx))
    # endregion

    # region Snapshots
    with self.argument_context('snapshot') as c:
        c.argument('snapshot_name',
                   existing_snapshot_name,
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/snapshots'))
        c.argument('name', arg_type=name_arg_type)
        c.argument('sku', arg_type=disk_sku)
    # endregion

    # region Images
    with self.argument_context('image') as c:
        c.argument('os_type', arg_type=get_enum_type(['Windows', 'Linux']))
        c.argument('image_name',
                   arg_type=name_arg_type,
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/images'))

    with self.argument_context('image create') as c:
        # here we collpase all difference image sources to under 2 common arguments --os-disk-source --data-disk-sources
        c.argument('name', arg_type=name_arg_type, help='new image name')
        c.argument(
            'source',
            help=
            'OS disk source from the same region, including a virtual machine ID or name, OS disk blob URI, managed OS disk ID or name, or OS snapshot ID or name'
        )
        c.argument(
            'data_disk_sources',
            nargs='+',
            help=
            'Space separated list of data disk sources, including unmanaged blob URI, managed disk ID or name, or snapshot ID or name'
        )
        c.ignore('source_virtual_machine', 'os_blob_uri', 'os_disk',
                 'os_snapshot', 'data_blob_uris', 'data_disks',
                 'data_snapshots')
    # endregion

    # region AvailabilitySets
    with self.argument_context('vm availability-set') as c:
        c.argument('availability_set_name',
                   name_arg_type,
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/availabilitySets'),
                   help='Name of the availability set')

    with self.argument_context('vm availability-set create') as c:
        c.argument('availability_set_name',
                   name_arg_type,
                   validator=get_default_location_from_resource_group,
                   help='Name of the availability set')
        c.argument(
            'platform_update_domain_count',
            type=int,
            help=
            'Update Domain count. If unspecified, server picks the most optimal number like 5. For the latest defaults see https://docs.microsoft.com/en-us/rest/api/compute/availabilitysets/availabilitysets-create'
        )
        c.argument('platform_fault_domain_count',
                   type=int,
                   help='Fault Domain count.')
        c.argument(
            'validate',
            help=
            'Generate and validate the ARM template without creating any resources.',
            action='store_true')
        c.argument('unmanaged',
                   action='store_true',
                   min_api='2016-04-30-preview',
                   help='contained VMs should use unmanaged disks')

    with self.argument_context('vm availability-set update') as c:
        if self.supported_api_version(max_api='2016-04-30-preview',
                                      operation_group='virtual_machines'):
            c.argument('name',
                       name_arg_type,
                       id_part='name',
                       completer=get_resource_name_completion_list(
                           'Microsoft.Compute/availabilitySets'),
                       help='Name of the availability set')
            c.argument('availability_set_name',
                       options_list=['--availability-set-name'])
    # endregion

    # region VirtualMachines
    with self.argument_context('vm') as c:
        c.argument('vm_name', existing_vm_name)
        c.argument('size', completer=get_vm_size_completion_list)
        c.argument('name', arg_type=name_arg_type)
        c.argument('zone', zone_type, min_api='2017-03-30')
        c.argument('caching',
                   help='Disk caching policy',
                   arg_type=get_enum_type(CachingTypes))
        c.argument(
            'nsg',
            help=
            'The name to use when creating a new Network Security Group (default) or referencing an existing one. Can also reference an existing NSG by ID or specify "" for none.',
            arg_group='Network')
        c.argument(
            'nsg_rule',
            help=
            'NSG rule to create when creating a new NSG. Defaults to open ports for allowing RDP on Windows and allowing SSH on Linux.',
            arg_group='Network',
            arg_type=get_enum_type(['RDP', 'SSH']))
        c.argument(
            'application_security_groups',
            min_api='2017-09-01',
            nargs='+',
            options_list=['--asgs'],
            help=
            'Space separated list of existing application security groups to associate with the VM.',
            arg_group='Network')

    with self.argument_context('vm capture') as c:
        c.argument('overwrite', action='store_true')

    with self.argument_context('vm update') as c:
        c.argument(
            'os_disk',
            min_api='2017-12-01',
            help=
            "Managed OS disk ID or name to swap to. Feature registration for 'Microsoft.Compute/AllowManagedDisksReplaceOSDisk' is needed"
        )

    with self.argument_context('vm create') as c:
        c.argument('name',
                   name_arg_type,
                   validator=_resource_not_exists(
                       self.cli_ctx, 'Microsoft.Compute/virtualMachines'))
        c.argument('vm_name',
                   name_arg_type,
                   id_part=None,
                   help='Name of the virtual machine.',
                   completer=None)
        c.argument('os_disk_size_gb',
                   type=int,
                   help='the size of the os disk in GB',
                   arg_group='Storage')
        c.argument(
            'attach_os_disk',
            help=
            'Attach an existing OS disk to the VM. Can use the name or ID of a managed disk or the URI to an unmanaged disk VHD.'
        )
        c.argument(
            'attach_data_disks',
            nargs='+',
            help=
            'Attach existing data disks to the VM. Can use the name or ID of a managed disk or the URI to an unmanaged disk VHD.'
        )
        c.argument(
            'availability_set',
            help=
            'Name or ID of an existing availability set to add the VM to. None by default.'
        )
        c.argument(
            'nsg',
            help=
            'The name to use when creating a new Network Security Group (default) or referencing an existing one. Can also reference an existing NSG by ID or specify "" for none.',
            arg_group='Network')
        c.argument(
            'nsg_rule',
            help=
            'NSG rule to create when creating a new NSG. Defaults to open ports for allowing RDP on Windows and allowing SSH on Linux.',
            arg_group='Network',
            arg_type=get_enum_type(['RDP', 'SSH']))
        c.argument(
            'application_security_groups',
            resource_type=ResourceType.MGMT_NETWORK,
            min_api='2017-09-01',
            nargs='+',
            options_list=['--asgs'],
            help=
            'Space separated list of existing application security groups to associate with the VM.',
            arg_group='Network',
            validator=validate_asg_names_or_ids)

    with self.argument_context('vm open-port') as c:
        c.argument(
            'vm_name',
            name_arg_type,
            help='The name of the virtual machine to open inbound traffic on.')
        c.argument(
            'network_security_group_name',
            options_list=('--nsg-name', ),
            help=
            'The name of the network security group to create if one does not exist. Ignored if an NSG already exists.',
            validator=validate_nsg_name)
        c.argument(
            'apply_to_subnet',
            help='Allow inbound traffic on the subnet instead of the NIC',
            action='store_true')
        c.argument(
            'port',
            help=
            "The port or port range (ex: 80-100) to open inbound traffic to. Use '*' to allow traffic to all ports."
        )
        c.argument(
            'priority',
            help=
            'Rule priority, between 100 (highest priority) and 4096 (lowest priority). Must be unique for each rule in the collection.',
            type=int)

    for scope in ['vm show', 'vm list']:
        with self.argument_context(scope) as c:
            c.argument(
                'show_details',
                action='store_true',
                options_list=['--show-details', '-d'],
                help=
                'show public ip address, FQDN, and power states. command will run slow'
            )

    with self.argument_context('vm diagnostics') as c:
        c.argument('vm_name',
                   arg_type=existing_vm_name,
                   options_list=['--vm-name'])

    with self.argument_context('vm diagnostics set') as c:
        c.argument('storage_account',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Storage/storageAccounts'))

    with self.argument_context('vm disk') as c:
        c.argument('vm_name',
                   options_list=['--vm-name'],
                   id_part=None,
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/virtualMachines'))
        c.argument('disk',
                   validator=validate_vm_disk,
                   help='disk name or ID',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/disks'))
        c.argument('new', action='store_true', help='create a new disk')
        c.argument('sku', arg_type=disk_sku)
        c.argument('size_gb',
                   options_list=['--size-gb', '-z'],
                   help='size in GB.')
        c.argument(
            'lun',
            type=int,
            help=
            '0-based logical unit number (LUN). Max value depends on the Virtual Machine size.'
        )

    with self.argument_context('vm disk detach') as c:
        c.argument('disk_name',
                   options_list=['--name', '-n'],
                   help='The data disk name.')

    with self.argument_context('vm encryption enable') as c:
        c.argument(
            'encrypt_format_all',
            action='store_true',
            help=
            'Encrypts-formats data disks instead of encrypting them. Encrypt-formatting is a lot faster than in-place encryption but wipes out the partition getting encrypt-formatted.'
        )

    with self.argument_context('vm extension') as c:
        c.argument('vm_extension_name',
                   name_arg_type,
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/virtualMachines/extensions'),
                   id_part='child_name_1')
        c.argument('vm_name',
                   arg_type=existing_vm_name,
                   options_list=['--vm-name'],
                   id_part='name')

    for scope in ['vm format-secret', 'vm secret']:
        with self.argument_context(scope) as c:
            c.argument(
                'secrets',
                multi_ids_type,
                options_list=['--secrets', '-s'],
                help=
                'Space separated list of key vault secret URIs. Perhaps, produced by \'az keyvault secret list-versions --vault-name vaultname -n cert1 --query "[?attributes.enabled].id" -o tsv\''
            )
            c.argument('keyvault', help='Name or ID of the key vault.')
            c.argument(
                'certificate',
                help='key vault certificate name or its full secret URL')
            c.argument('certificate_store',
                       help='Windows certificate store names. Default: My')

    with self.argument_context('vm image') as c:
        c.argument('publisher_name', options_list=['--publisher', '-p'])
        c.argument('offer', options_list=['--offer', '-f'])
        c.argument('sku', options_list=['--sku', '-s'])

    with self.argument_context('vm image list') as c:
        c.argument('image_location', get_location_type(self.cli_ctx))

    with self.argument_context('vm image show') as c:
        c.argument('skus', options_list=['--sku', '-s'])

    with self.argument_context('vm nic') as c:
        c.argument('vm_name',
                   existing_vm_name,
                   options_list=['--vm-name'],
                   id_part=None)
        c.argument('nics',
                   nargs='+',
                   help='Names or IDs of NICs.',
                   validator=validate_vm_nics)
        c.argument(
            'primary_nic',
            help=
            'Name or ID of the primary NIC. If missing, the first NIC in the list will be the primary.'
        )

    with self.argument_context('vm nic show') as c:
        c.argument('nic', help='NIC name or ID.', validator=validate_vm_nic)

    with self.argument_context('vm run-command') as c:
        c.argument('command_id',
                   completer=get_vm_run_command_completion_list,
                   help="The run command ID")

    with self.argument_context('vm run-command invoke') as c:
        c.argument(
            'parameters',
            nargs='+',
            help="space separated parameters in the format of '[name=]value'")
        c.argument(
            'scripts',
            nargs='+',
            help=
            "script lines separated by whites spaces. Use @{file} to load from a file"
        )

    with self.argument_context('vm unmanaged-disk') as c:
        c.argument('vm_name', arg_type=existing_vm_name)
        c.argument('disk_size',
                   help='Size of disk (GiB)',
                   default=1023,
                   type=int)
        c.argument('new', action='store_true', help='Create a new disk.')
        c.argument(
            'lun',
            type=int,
            help=
            '0-based logical unit number (LUN). Max value depends on the Virtual Machine size.'
        )
        c.argument(
            'vhd_uri',
            help=
            "Virtual hard disk URI. For example: https://mystorage.blob.core.windows.net/vhds/d1.vhd"
        )

    with self.argument_context('vm unmanaged-disk attach') as c:
        c.argument('disk_name',
                   options_list=['--name', '-n'],
                   help='The data disk name(optional when create a new disk)')

    with self.argument_context('vm unmanaged-disk detach') as c:
        c.argument('disk_name',
                   options_list=['--name', '-n'],
                   help='The data disk name.')

    for scope in ['vm unmanaged-disk attach', 'vm unmanaged-disk detach']:
        with self.argument_context(scope) as c:
            c.argument('vm_name',
                       arg_type=existing_vm_name,
                       options_list=['--vm-name'],
                       id_part=None)

    with self.argument_context('vm user') as c:
        c.argument('username',
                   options_list=['--username', '-u'],
                   help='The user name')
        c.argument('password',
                   options_list=['--password', '-p'],
                   help='The user password')
    # endregion

    # region VMSS
    scaleset_name_aliases = [
        'vm_scale_set_name', 'virtual_machine_scale_set_name', 'name'
    ]

    with self.argument_context('vmss') as c:
        c.argument('zones', zones_type, min_api='2017-03-30')
        c.argument('instance_id', id_part='child_name_1')
        c.argument(
            'instance_ids',
            multi_ids_type,
            help=
            'Space separated list of IDs (ex: 1 2 3 ...) or * for all instances. If not provided, the action will be applied on the scaleset itself'
        )
        c.argument('tags', tags_type)
        c.argument('caching',
                   help='Disk caching policy',
                   arg_type=get_enum_type(CachingTypes))
        for dest in scaleset_name_aliases:
            c.argument(dest, vmss_name_type)

    for scope in [
            'vmss deallocate', 'vmss delete-instances', 'vmss restart',
            'vmss start', 'vmss stop', 'vmss show', 'vmss update-instances'
    ]:
        with self.argument_context(scope) as c:
            for dest in scaleset_name_aliases:
                c.argument(dest, vmss_name_type,
                           id_part=None)  # due to instance-ids parameter

    with self.argument_context('vmss create') as c:
        c.argument('name', name_arg_type)
        c.argument(
            'nat_backend_port',
            default=None,
            help=
            'Backend port to open with NAT rules.  Defaults to 22 on Linux and 3389 on Windows.'
        )
        c.argument(
            'single_placement_group',
            default=None,
            help=
            "Enable single placement group. This flag will default to True if instance count <=100, and default to False for instance count >100.",
            arg_type=get_enum_type(['true', 'false']))
        c.argument('vmss_name',
                   name_arg_type,
                   id_part=None,
                   help='Name of the virtual machine scale set.')
        c.argument('instance_count',
                   help='Number of VMs in the scale set.',
                   type=int)
        c.argument(
            'disable_overprovision',
            help=
            'Overprovision option (see https://azure.microsoft.com/en-us/documentation/articles/virtual-machine-scale-sets-overview/ for details).',
            action='store_true')
        c.argument('upgrade_policy_mode',
                   help=None,
                   arg_type=get_enum_type(UpgradeMode))
        c.argument(
            'health_probe',
            help=
            '(Preview) probe name from the existing load balancer, mainly used for rolling upgrade'
        )
        c.argument(
            'vm_sku',
            help=
            'Size of VMs in the scale set.  See https://azure.microsoft.com/en-us/pricing/details/virtual-machines/ for size info.'
        )
        c.argument('nsg',
                   help='Name or ID of an existing Network Security Group.',
                   arg_group='Network')

    with self.argument_context('vmss create',
                               arg_group='Network Balancer') as c:
        LoadBalancerSkuName = self.get_models(
            'LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK)
        c.argument(
            'application_gateway',
            help=
            'Name to use when creating a new application gateway (default) or referencing an existing one. Can also reference an existing application gateway by ID or specify "" for none.',
            options_list=['--app-gateway'])
        c.argument(
            'app_gateway_capacity',
            help=
            'The number of instances to use when creating a new application gateway.'
        )
        c.argument('app_gateway_sku',
                   help='SKU when creating a new application gateway.')
        c.argument(
            'app_gateway_subnet_address_prefix',
            help=
            'The subnet IP address prefix to use when creating a new application gateway in CIDR format.'
        )
        c.argument(
            'backend_pool_name',
            help=
            'Name to use for the backend pool when creating a new load balancer or application gateway.'
        )
        c.argument(
            'backend_port',
            help=
            'When creating a new load balancer, backend port to open with NAT rules (Defaults to 22 on Linux and 3389 on Windows). When creating an application gateway, the backend port to use for the backend HTTP settings.',
            type=int)
        c.argument(
            'load_balancer',
            help=
            'Name to use when creating a new load balancer (default) or referencing an existing one. Can also reference an existing load balancer by ID or specify "" for none.',
            options_list=['--load-balancer', '--lb'])
        c.argument(
            'load_balancer_sku',
            resource_type=ResourceType.MGMT_NETWORK,
            min_api='2017-08-01',
            help=
            "SKU when creating a new Load Balancer. Default to 'Basic' for any non-zonal scaleset and 'Standard' otherwise",
            options_list=['--lb-sku'],
            arg_type=get_enum_type(LoadBalancerSkuName))
        c.argument(
            'nat_pool_name',
            help=
            'Name to use for the NAT pool when creating a new load balancer.',
            options_list=['--lb-nat-pool-name', '--nat-pool-name'])

    with self.argument_context('vmss create',
                               min_api='2017-03-30',
                               arg_group='Network') as c:
        c.argument(
            'public_ip_per_vm',
            action='store_true',
            help=
            "Each VM instance will have a public ip. For security, you can use '--nsg' to apply appropriate rules"
        )
        c.argument(
            'vm_domain_name',
            help=
            "domain name of VM instances, once configured, the FQDN is 'vm<vm-index>.<vm-domain-name>.<..rest..>'"
        )
        c.argument(
            'dns_servers',
            nargs='+',
            help=
            "space separated IP addresses of DNS servers, e.g. 10.0.0.5 10.0.0.6"
        )
        c.argument('accelerated_networking',
                   action='store_true',
                   help="enable accelerated networking")

    for scope in ['vmss update-instances', 'vmss delete-instances']:
        with self.argument_context(scope) as c:
            c.argument(
                'instance_ids',
                multi_ids_type,
                help=
                'Space separated list of IDs (ex: 1 2 3 ...) or * for all instances.'
            )

    with self.argument_context('vmss diagnostics') as c:
        c.argument('vmss_name', id_part=None, help='Scale set name')

    with self.argument_context('vmss disk') as c:
        c.argument(
            'lun',
            type=int,
            help=
            '0-based logical unit number (LUN). Max value depends on the Virtual Machine instance size.'
        )
        c.argument('size_gb',
                   options_list=['--size-gb', '-z'],
                   help='size in GB.')
        c.argument('vmss_name',
                   vmss_name_type,
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/virtualMachineScaleSets'))

    with self.argument_context('vmss encryption') as c:
        c.argument('vmss_name',
                   vmss_name_type,
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/virtualMachineScaleSets'))

    with self.argument_context('vmss extension') as c:
        c.argument('extension_name',
                   name_arg_type,
                   help='Name of the extension.')
        c.argument('vmss_name',
                   vmss_name_type,
                   options_list=['--vmss-name'],
                   id_part=None)

    with self.argument_context('vmss nic') as c:
        c.argument('virtual_machine_scale_set_name',
                   options_list=['--vmss-name'],
                   help='Scale set name.',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Compute/virtualMachineScaleSets'),
                   id_part='name')
        c.argument('virtualmachine_index',
                   options_list=['--instance-id'],
                   id_part='child_name_1')
        c.argument('network_interface_name',
                   options_list=['--name', '-n'],
                   metavar='NIC_NAME',
                   help='The network interface (NIC).',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Network/networkInterfaces'),
                   id_part='child_name_2')
    # endregion

    # region VM & VMSS Shared
    for scope in ['vm', 'vmss']:
        with self.argument_context(scope) as c:
            c.argument(
                'no_auto_upgrade',
                action='store_true',
                help=
                'by doing this, extension system will not pick the highest minor version for the specified version number, and will not auto update to the latest build/revision number on any scale set updates in future.'
            )

    for scope in ['vm assign-identity', 'vmss assign-identity']:
        with self.argument_context(scope) as c:
            c.argument('assign_identity',
                       options_list=['--identities'],
                       nargs='*',
                       help="the identities to assign")
            c.argument('port',
                       type=int,
                       help="The port to fetch AAD token. Default: 50342")
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

    for scope in ['vm remove-identity', 'vmss remove-identity']:
        with self.argument_context(scope) as c:
            c.argument(
                'identities',
                nargs='+',
                help="space separated user assigned identities to remove")
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

    for scope in ['vm create', 'vmss create']:
        with self.argument_context(scope) as c:
            c.argument(
                'location',
                get_location_type(self.cli_ctx),
                help=
                'Location in which to create VM and related resources. If default location is not configured, will default to the resource group\'s location'
            )
            c.argument('tags', tags_type)
            c.argument(
                'no_wait',
                help='Do not wait for the long-running operation to finish.')
            c.argument(
                'validate',
                options_list=['--validate'],
                help=
                'Generate and validate the ARM template without creating any resources.',
                action='store_true')
            c.argument(
                'size',
                help=
                'The VM size to be created. See https://azure.microsoft.com/en-us/pricing/details/virtual-machines/ for size info.'
            )
            c.argument('image', completer=get_urn_aliases_completion_list)
            c.argument(
                'custom_data',
                help=
                'Custom init script file or text (cloud-init, cloud-config, etc..)',
                completer=FilesCompleter(),
                type=file_type)
            c.argument(
                'secrets',
                multi_ids_type,
                help=
                'One or many Key Vault secrets as JSON strings or files via `@<file path>` containing `[{ "sourceVault": { "id": "value" }, "vaultCertificates": [{ "certificateUrl": "value", "certificateStore": "cert store name (only on windows)"}] }]`',
                type=file_type,
                completer=FilesCompleter())
            c.argument(
                'license_type',
                help=
                "license type if the Windows image or disk used was licensed on-premises",
                arg_type=get_enum_type(['Windows_Server', 'Windows_Client']))
            c.argument(
                'assign_identity',
                nargs='*',
                arg_group='Managed Service Identity',
                help=
                "accept system or user assigned identities with space separated. Use '[system]' to refer system assigned identity, or a resource id to refer user assigned identity. Check out help for more examples"
            )

        with self.argument_context(scope, arg_group='Authentication') as c:
            c.argument(
                'generate_ssh_keys',
                action='store_true',
                help=
                'Generate SSH public and private key files if missing. The keys will be stored in the ~/.ssh directory'
            )
            c.argument('admin_username', help='Username for the VM.')
            c.argument(
                'admin_password',
                help="Password for the VM if authentication type is 'Password'."
            )
            c.argument('ssh_key_value',
                       help='SSH public key or public key file path.',
                       completer=FilesCompleter(),
                       type=file_type)
            c.argument('ssh_dest_key_path',
                       help='Destination file path on the VM for the SSH key.')
            c.argument(
                'authentication_type',
                help=
                'Type of authentication to use with the VM. Defaults to password for Windows and SSH public key for Linux.',
                arg_type=get_enum_type(['ssh', 'password']))

        with self.argument_context(scope, arg_group='Storage') as c:
            c.argument('os_disk_name', help='The name of the new VM OS disk.')
            c.argument(
                'os_type',
                help=
                'Type of OS installed on a custom VHD. Do not use when specifying an URN or URN alias.',
                arg_type=get_enum_type(['windows', 'linux']))
            c.argument(
                'storage_account',
                help=
                "Only applicable when used with `--use-unmanaged-disk`. The name to use when creating a new storage account or referencing an existing one. If omitted, an appropriate storage account in the same resource group and location will be used, or a new one will be created."
            )
            c.argument(
                'storage_sku',
                help=
                'The SKU of the storage account with which to persist VM. By default, only Standard_LRS and Premium_LRS are allowed. With `--use-unmanaged-disk`, all are available.',
                arg_type=get_enum_type(SkuName))
            c.argument(
                'storage_container_name',
                help=
                "Only applicable when used with `--use-unmanaged-disk`. Name of the storage container for the VM OS disk. Default: vhds"
            )
            c.ignore('os_publisher', 'os_offer', 'os_sku', 'os_version',
                     'storage_profile')
            c.argument('use_unmanaged_disk',
                       action='store_true',
                       help='Do not use managed disk to persist VM')
            c.argument(
                'data_disk_sizes_gb',
                nargs='+',
                type=int,
                help=
                'space separated empty managed data disk sizes in GB to create'
            )
            c.ignore('image_data_disks', 'storage_account_type',
                     'public_ip_type', 'nsg_type', 'nic_type', 'vnet_type',
                     'load_balancer_type', 'app_gateway_type')
            c.argument(
                'os_caching',
                options_list=['--storage-caching', '--os-disk-caching'],
                help='Storage caching type for the VM OS disk.',
                arg_type=get_enum_type([
                    CachingTypes.read_only.value, CachingTypes.read_write.value
                ],
                                       default='ReadWrite'))
            c.argument('data_caching',
                       options_list=['--data-disk-caching'],
                       help='Storage caching type for the VM data disk(s).',
                       arg_type=get_enum_type(CachingTypes))

        with self.argument_context(scope, arg_group='Network') as c:
            c.argument(
                'vnet_name',
                help=
                'Name of the virtual network when creating a new one or referencing an existing one.'
            )
            c.argument(
                'vnet_address_prefix',
                help=
                'The IP address prefix to use when creating a new VNet in CIDR format.'
            )
            c.argument(
                'subnet',
                help=
                'The name of the subnet when creating a new VNet or referencing an existing one. Can also reference an existing subnet by ID. If omitted, an appropriate VNet and subnet will be selected automatically, or a new one will be created.'
            )
            c.argument(
                'subnet_address_prefix',
                help=
                'The subnet IP address prefix to use when creating a new VNet in CIDR format.'
            )
            c.argument(
                'nics',
                nargs='+',
                help=
                'Names or IDs of existing NICs to attach to the VM. The first NIC will be designated as primary. If omitted, a new NIC will be created. If an existing NIC is specified, do not specify subnet, VNet, public IP or NSG.'
            )
            c.argument('private_ip_address',
                       help='Static private IP address (e.g. 10.0.0.5).')
            c.argument(
                'public_ip_address',
                help=
                'Name of the public IP address when creating one (default) or referencing an existing one. Can also reference an existing public IP by ID or specify "" for None.'
            )
            c.argument('public_ip_address_allocation',
                       help=None,
                       arg_type=get_enum_type(['dynamic', 'static']))
            c.argument(
                'public_ip_address_dns_name',
                help='Globally unique DNS name for a newly created public IP.')

        with self.argument_context(scope,
                                   arg_group='Marketplace Image Plan') as c:
            c.argument('plan_name', help='plan name')
            c.argument('plan_product', help='plan product')
            c.argument('plan_publisher', help='plan publisher')
            c.argument('plan_promotion_code', help='plan promotion code')

    for scope in [
            'vm create', 'vmss create', 'vm assign-identity',
            'vmss assign-identity'
    ]:
        with self.argument_context(scope) as c:
            arg_group = 'Managed Service Identity' if scope.split(
            )[-1] == 'create' else None
            c.argument(
                'identity_scope',
                options_list=['--scope'],
                arg_group=arg_group,
                help="Scope that the system assigned identity can access")
            c.argument(
                'identity_role',
                options_list=['--role'],
                arg_group=arg_group,
                help="Role name or id the system assigned identity will have")
            c.ignore('identity_role_id')

    for scope in ['vm diagnostics', 'vmss diagnostics']:
        with self.argument_context(scope) as c:
            c.argument(
                'version',
                help=
                'version of the diagnostics extension. Will use the latest if not specfied'
            )
            c.argument(
                'settings',
                help=
                'json string or a file path, which defines data to be collected.',
                type=validate_file_or_dict,
                completer=FilesCompleter())
            c.argument(
                'protected_settings',
                help=
                'json string or a file path containing private configurations such as storage account keys, etc.',
                type=validate_file_or_dict,
                completer=FilesCompleter())

    for scope in ['vm encryption', 'vmss encryption']:
        with self.argument_context(scope) as c:
            c.argument(
                'volume_type',
                help=
                'Type of volume that the encryption operation is performed on',
                arg_type=get_enum_type(['DATA', 'OS', 'ALL']))
            c.argument(
                'force',
                action='store_true',
                help='continue by ignoring client side validation errors')
            c.argument(
                'disk_encryption_keyvault',
                help=
                'The key vault where the generated encryption key will be placed.'
            )
            c.argument(
                'key_encryption_key',
                help=
                'Key vault key name or URL used to encrypt the disk encryption key.'
            )
            c.argument(
                'key_encryption_keyvault',
                help=
                'The key vault containing the key encryption key used to encrypt the disk encryption key. If missing, CLI will use `--disk-encryption-keyvault`.'
            )

    for scope in ['vm extension', 'vmss extension']:
        with self.argument_context(scope) as c:
            c.argument('publisher',
                       help='The name of the extension publisher.')
            c.argument(
                'settings',
                type=validate_file_or_dict,
                help=
                'Extension settings in JSON format. A JSON file path is also accepted.'
            )
            c.argument(
                'protected_settings',
                type=validate_file_or_dict,
                help=
                'Protected settings in JSON format for sensitive information like credentials. A JSON file path is also accepted.'
            )
            c.argument('version', help='The version of the extension')

    for scope in ['vm extension image', 'vmss extension image']:
        with self.argument_context(scope) as c:
            c.argument('image_location',
                       options_list=['--location', '-l'],
                       help='Image location.')
            c.argument('name', help='Image name', id_part=None)
            c.argument('publisher_name',
                       options_list=['--publisher', '-p'],
                       help='Image publisher name')
            c.argument('type',
                       options_list=['--name', '-n'],
                       help='Name of the extension')
            c.argument('latest',
                       action='store_true',
                       help='Show the latest version only.')
            c.argument('version', help='Extension version')
Example #21
0
def load_arguments(self, _):    # pylint: disable=too-many-statements

    server_completers = {
        'mysql': get_resource_name_completion_list('Microsoft.DBForMySQL/servers'),
        'postgres': get_resource_name_completion_list('Microsoft.DBForPostgreSQL/servers')
    }

    def _complex_params(command_group):
        with self.argument_context('{} server create'.format(command_group)) as c:
            c.argument('sku_name', options_list=['--sku-name'], required=True, help='The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8.')

            c.argument('backup_retention', type=int, options_list=['--backup-retention'], help='The number of days a backup is retained.')
            c.argument('geo_redundant_backup', options_list=['--geo-redundant-backup'], help='Enable Geo-redundant or not for server backup.')
            c.argument('storage_mb', options_list=['--storage-size'], type=int, help='The max storage size of the server. Unit is megabytes.')

            c.argument('administrator_login', required=True, arg_group='Authentication')
            c.argument('administrator_login_password', arg_group='Authentication')

            c.argument('location', arg_type=get_location_type(self.cli_ctx), required=False)
            c.argument('version', help='Server version')

        with self.argument_context('{} server update'.format(command_group)) as c:
            c.ignore('family', 'capacity', 'tier')
            c.argument('sku_name', options_list=['--sku-name'], help='The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8.')

        with self.argument_context('{} server restore'. format(command_group)) as c:
            c.argument('source_server', options_list=['--source-server', '-s'], help='The name or ID of the source server to restore from.')
            c.argument('restore_point_in_time', help='The point in time to restore from (ISO8601 format), e.g., 2017-04-26T02:10:00+08:00')

        with self.argument_context('{} server georestore'. format(command_group)) as c:
            c.argument('location', arg_type=get_location_type(self.cli_ctx), required=True)
            c.argument('sku_name', options_list=['--sku-name'], required=False, help='The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8.')
            c.argument('source_server', options_list=['--source-server', '-s'], required=True, help='The name or ID of the source server to restore from.')
            c.argument('backup_retention', options_list=['--backup-retention'], type=int, help='The max days of retention, unit is days.')
            c.argument('geo_redundant_backup', options_list=['--geo-redundant-backup'], help='Enable Geo-redundant or not for server backup.')

        with self.argument_context('{} server configuration set'.format(command_group)) as c:
            c.argument('value', help='Value of the configuration. If not provided, configuration value will be set to default.', validator=configuration_value_validator)
            c.ignore('source')

        with self.argument_context('{} server wait'.format(command_group)) as c:
            c.ignore('created', 'deleted', 'updated')

    _complex_params('mysql')
    _complex_params('postgres')

    for scope in ['mysql', 'postgres']:
        with self.argument_context(scope) as c:
            c.argument('name', options_list=['--sku-name'], required=True)
            c.argument('server_name', completer=server_completers[scope], options_list=['--server-name', '-s'], help='Name of the server.')

    for scope in ['mysql server', 'postgres server']:
        with self.argument_context(scope) as c:
            c.ignore('family', 'capacity', 'tier')

            c.argument('server_name', options_list=['--name', '-n'], id_part='name', help='Name of the server.')
            c.argument('administrator_login', options_list=['--admin-user', '-u'])
            c.argument('administrator_login_password', options_list=['--admin-password', '-p'], help='The password of the administrator login.')
            c.argument('ssl_enforcement', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--ssl-enforcement'], help='Enable ssl enforcement or not when connect to server.')
            c.argument('tier', arg_type=get_enum_type(['Basic', 'GeneralPurpose', 'MemoryOptimized']), options_list=['--performance-tier'], help='The performance tier of the server.')
            c.argument('capacity', options_list=['--vcore'], type=int, help='Number of vcore.')
            c.argument('family', options_list=['--family'], arg_type=get_enum_type(['Gen4', 'Gen5']), help='Hardware generation.')
            c.argument('storage_mb', options_list=['--storage-size'], type=int, help='The max storage size of the server. Unit is megabytes.')
            c.argument('backup_retention_days', options_list=['--backup-retention'], type=int, help='The number of days a backup is retained.')
            c.argument('tags', tags_type)

    for scope in ['mysql server-logs', 'postgres server-logs']:
        with self.argument_context(scope) as c:
            c.argument('file_name', options_list=['--name', '-n'], nargs='+', help='Space-separated list of log filenames on the server to download.')
            c.argument('max_file_size', type=int, help='The file size limitation to filter files.')
            c.argument('file_last_written', type=int, help='Integer in hours to indicate file last modify time, default value is 72.')
            c.argument('filename_contains', help='The pattern that file name should match.')

    for scope in ['mysql db', 'postgres db']:
        with self.argument_context(scope) as c:
            c.argument('database_name', options_list=['--name', '-n'])

    for scope in ['mysql server firewall-rule', 'postgres server firewall-rule']:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('firewall_rule_name', options_list=['--name', '-n'], id_part='child_name_1', help='The name of the firewall rule.')
            c.argument('start_ip_address', options_list=['--start-ip-address'], help='The start IP address of the firewall rule. Must be IPv4 format. Use value \'0.0.0.0\' to represent all Azure-internal IP addresses.')
            c.argument('end_ip_address', options_list=['--end-ip-address'], help='The end IP address of the firewall rule. Must be IPv4 format. Use value \'0.0.0.0\' to represent all Azure-internal IP addresses.')

    for scope in ['mysql server vnet-rule', 'postgres server vnet-rule']:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('virtual_network_rule_name', options_list=['--name', '-n'], id_part='child_name_1', help='The name of the vnet rule.')
            c.argument('virtual_network_subnet_id', options_list=['--subnet'], help='Name or ID of the subnet that allows access to an Azure Postgres Server. If subnet name is provided, --vnet-name must be provided.')
            c.argument('ignore_missing_vnet_service_endpoint', options_list=['--ignore-missing-endpoint', '-i'], help='Create vnet rule before virtual network has vnet service endpoint enabled', arg_type=get_three_state_flag())

    for scope in ['postgres server vnet-rule create', 'postgres server vnet-rule update', 'mysql server vnet-rule create', 'mysql server vnet-rule update']:
        with self.argument_context(scope) as c:
            c.extra('vnet_name', options_list=['--vnet-name'], help='The virtual network name', validator=validate_subnet)

    for scope in ['mysql server configuration', 'postgres server configuration']:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('configuration_name', id_part='child_name_1', options_list=['--name', '-n'])
Example #22
0
def load_arguments(self, _):
    from ..vendored_sdks.azure_attestation.models import TeeKind

    attestation_name_type = CLIArgumentType(
        help='Name of the attestation.',
        options_list=['--name', '-n'],
        metavar='NAME',
        id_part=None,
        completer=get_resource_name_completion_list(
            'Microsoft.Attestation/attestationProviders'))

    with self.argument_context('attestation list') as c:
        c.argument('resource_group_name', resource_group_name_type)

    with self.argument_context('attestation show') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('provider_name',
                   options_list=['--name', '-n'],
                   help='Name of the attestation service instance',
                   id_part='name')

    with self.argument_context('attestation create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('provider_name',
                   options_list=['--name', '-n'],
                   help='Name of the attestation service')
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('tags', tags_type)
        c.argument('attestation_policy', help='Name of attestation policy.')
        c.argument(
            'certs_input_path',
            type=file_type,
            help='The path to the policy signing certificates PEM file.',
            completer=FilesCompleter())

    with self.argument_context('attestation delete') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('provider_name',
                   options_list=['--name', '-n'],
                   help='Name of the attestation service',
                   id_part='name')

    for item in ['list', 'add', 'remove']:
        with self.argument_context('attestation signer {}'.format(item)) as c:
            c.extra('resource_group_name',
                    resource_group_name_type,
                    required=False)
            c.extra('attestation_name', attestation_name_type, required=False)
            c.argument(
                'tenant_base_url',
                options_list=['--attestation-base-url', '-u'],
                required=False,
                help=
                'URL of the attestation, for example: https://myatt.eus2.attest.azure.net. '
                'You can ignore --name and --resource-group if you specified the URL.'
            )
            if item in ['add', 'remove']:
                c.argument(
                    'policy_certificate_to_{}'.format(item),
                    options_list=['--signer'],
                    help=
                    'The policy certificate to {}. An RFC7519 JSON Web Token containing a claim named '
                    '"aas-policyCertificate" whose value is an RFC7517 JSON Web Key which specifies a '
                    'new key to update. The RFC7519 JWT must be signed with one of the existing signing '
                    'certificates'.format(item))

    for item in ['set', 'reset', 'show']:
        with self.argument_context('attestation policy {}'.format(item)) as c:
            c.extra('resource_group_name',
                    resource_group_name_type,
                    required=False)
            c.extra('attestation_name', attestation_name_type, required=False)
            c.argument(
                'tenant_base_url',
                options_list=['--attestation-base-url', '-u'],
                required=False,
                help=
                'URL of the attestation, for example: https://myatt.eus2.attest.azure.net. '
                'You can ignore --name and --resource-group if you specified the URL.'
            )
            c.argument('tee', arg_type=get_enum_type(TeeKind))

    with self.argument_context('attestation policy set') as c:
        c.argument('new_attestation_policy',
                   options_list=['--new-attestation-policy', '-p'])
input_mapping_default_values_type = CLIArgumentType(
    help="When input-schema is specified as customeventschema, this parameter can be used to specify input mappings based on default values. You can use this parameter when your custom schema does not include a field that corresponds to one of the three fields supported by this parameter. Specify space separated mappings in 'key=value' format. Allowed key names are 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the default values to be used for the mapping and they will be used only when the published event doesn't have a valid mapping for a particular field.",
    arg_type=tags_type
)

odata_query_type = CLIArgumentType(
    help="The query used to filter the results using OData syntax.",
    options_list=['--odata-query']
)

domain_name_type = CLIArgumentType(
    help='Name of the domain.',
    arg_type=name_type,
    options_list=['--domain-name'],
    completer=get_resource_name_completion_list('Microsoft.EventGrid/domains'))

domain_topic_name_type = CLIArgumentType(
    help='Name of the domain topic.',
    arg_type=name_type,
    options_list=['--domain-topic-name'],
    completer=get_resource_name_completion_list('Microsoft.EventGrid/domains/topic'))


def load_arguments(self, _):    # pylint: disable=too-many-statements
    with self.argument_context('eventgrid') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location', arg_type=get_location_type(self.cli_ctx))
        c.argument('tags', arg_type=tags_type)
        c.argument('included_event_types', arg_type=included_event_types_type)
        c.argument('labels', arg_type=labels_type)
Example #24
0
backup_management_type_help = """Specifiy the backup management type. Define how Azure Backup manages the backup of entities within the ARM resource. For eg: AzureWorkloads refers to workloads installed within Azure VMs, AzureStorage refers to entities within Storage account. Required only if friendly name is used as Container name."""
container_name_help = """Name of the backup container. Accepts 'Name' or 'FriendlyName' from the output of az backup container list command. If 'FriendlyName' is passed then BackupManagementType is required."""
workload_type_help = """Specifiy the type of applications within the Resource which should be discovered and protected by Azure Backup. """
restore_mode_help = """Specify the restore mode."""
resolve_conflict_help = "Instruction if there's a conflict with the restored data."
resource_id_help = """ID of the Azure Resource containing items to be protected by Azure Backup service. Currently, only Azure VM resource IDs are supported."""
policy_help = """JSON encoded policy definition. Use the show command with JSON output to obtain a policy object. Modify the values using a file editor and pass the object."""
target_server_type_help = """Specify the type of the server which should be discovered."""
protectable_item_name_type_help = """Specify the resource name to be protected by Azure Backup service."""
backup_type_help = """'Full, Differential, Log, Copy-only-full' for backup Item type 'MSSQL'. 'Full, Differential' for backup item type 'SAPHANA'."""
retain_until_help = """The date until which this backed up copy will be available for retrieval, in UTC (d-m-Y). For SAPHANA and SQL workload, retain-until parameter value will be overridden by the underlying policy."""

vault_name_type = CLIArgumentType(help='Name of the Recovery services vault.',
                                  options_list=['--vault-name', '-v'],
                                  completer=get_resource_name_completion_list(
                                      'Microsoft.RecoveryServices/vaults'))
container_name_type = CLIArgumentType(help=container_name_help,
                                      options_list=['--container-name', '-c'])
item_name_type = CLIArgumentType(help='Name of the backed up item.',
                                 options_list=['--item-name', '-i'])
policy_name_type = CLIArgumentType(help='Name of the backup policy.',
                                   options_list=['--policy-name', '-p'])
job_name_type = CLIArgumentType(help='Name of the job.',
                                options_list=['--name', '-n'])
rp_name_type = CLIArgumentType(help='Name of the recovery point.',
                               options_list=['--rp-name', '-r'])
backup_management_type = CLIArgumentType(
    help=backup_management_type_help,
    arg_type=get_enum_type(allowed_backup_management_types),
    options_list=['--backup-management-type'])
workload_type = CLIArgumentType(help=workload_type_help,
Example #25
0

class ScheduleEntryList(list):
    def __init__(self, value):
        super(ScheduleEntryList, self).__init__()
        if value[0] in ("'", '"') and value[-1] == value[0]:
            # Remove leading and trailing quotes for dos/cmd.exe users
            value = value[1:-1]
        dictval = shell_safe_json_parse(value)
        self.extend([ScheduleEntry(row['dayOfWeek'],
                                   int(row['startHourUtc']),
                                   row.get('maintenanceWindow', None)) for row in dictval])


register_cli_argument('redis', 'name', arg_type=name_type, help='Name of the redis cache.',
                      completer=get_resource_name_completion_list('Microsoft.Cache/redis'),
                      id_part='name')
register_cli_argument('redis', 'redis_configuration', type=JsonString)
register_cli_argument('redis', 'reboot_type', **enum_choice_list(RebootType))
register_cli_argument('redis', 'key_type', **enum_choice_list(RedisKeyType))
register_cli_argument('redis', 'shard_id', type=int)
register_cli_argument('redis', 'sku', **enum_choice_list(SkuName))
register_cli_argument('redis', 'vm_size',
                      help='Size of redis cache to deploy. '
                           'Example : values for C family (C0, C1, C2, C3, C4, C5, C6). '
                           'For P family (P1, P2, P3, P4)')
register_cli_argument('redis', 'enable_non_ssl_port', action='store_true')
register_cli_argument('redis', 'shard_count', type=int)
register_cli_argument('redis', 'subnet_id')

register_cli_argument('redis import-method', 'files', nargs='+')
Example #26
0
def load_arguments(self, _):

    with self.argument_context('sql') as c:
        c.argument('location_name', arg_type=get_location_type(self.cli_ctx))
        c.argument('usage_name', options_list=['--usage', '-u'])

    with self.argument_context('sql db') as c:
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help='Name of the Azure SQL Database.')
        c.argument('server_name', arg_type=server_param_type)
        c.argument('elastic_pool_name', options_list=['--elastic-pool'])
        c.argument('requested_service_objective_name',
                   options_list=['--service-objective'])
        c.argument(
            'max_size_bytes',
            options_list=['--max-size'],
            type=SizeWithUnitConverter('B', result_type=int),
            help='The max storage size of the database. Only the following'
            ' sizes are supported (in addition to limitations being placed on'
            ' each edition): 100MB, 500MB, 1GB, 5GB, 10GB, 20GB,'
            ' 30GB, 150GB, 200GB, 500GB. If no unit is specified, defaults to bytes (B).'
        )

        # Adjust help text.
        c.argument('edition',
                   options_list=['--edition'],
                   help='The edition of the database.')

    with self.argument_context('sql db create') as c:
        _configure_db_create_params(c, Engine.db, CreateMode.default)

    with self.argument_context('sql db copy') as c:
        _configure_db_create_params(c, Engine.db, CreateMode.copy)

        c.argument(
            'elastic_pool_name',
            help='Name of the elastic pool to create the new database in.')

        c.argument(
            'dest_name',
            help=
            'Name of the database that will be created as the copy destination.'
        )

        c.argument('dest_resource_group_name',
                   options_list=['--dest-resource-group'],
                   help='Name of the resouce group to create the copy in.'
                   ' If unspecified, defaults to the origin resource group.')

        c.argument('dest_server_name',
                   options_list=['--dest-server'],
                   help='Name of the server to create the copy in.'
                   ' If unspecified, defaults to the origin server.')

        c.argument('requested_service_objective_name',
                   options_list=['--service-objective'],
                   help='Name of the service objective for the new database.')

    with self.argument_context('sql db restore') as c:
        _configure_db_create_params(c, Engine.db,
                                    CreateMode.point_in_time_restore)

        c.argument(
            'dest_name',
            help=
            'Name of the database that will be created as the restore destination.'
        )

        restore_point_arg_group = 'Restore Point'

        c.argument(
            'restore_point_in_time',
            options_list=['--time', '-t'],
            arg_group=restore_point_arg_group,
            help=
            'The point in time of the source database that will be restored to create the'
            ' new database. Must be greater than or equal to the source database\'s'
            ' earliestRestoreDate value. Either --time or --deleted-time (or both) must be specified.'
        )

        c.argument(
            'source_database_deletion_date',
            options_list=['--deleted-time'],
            arg_group=restore_point_arg_group,
            help=
            'If specified, restore from a deleted database instead of from an existing database.'
            ' Must match the deleted time of a deleted database in the same server.'
            ' Either --time or --deleted-time (or both) must be specified.')

        c.argument('edition', help='The edition for the new database.')
        c.argument(
            'elastic_pool_name',
            help='Name of the elastic pool to create the new database in.')
        c.argument('requested_service_objective_name',
                   help='Name of service objective for the new database.')

    with self.argument_context('sql db show') as c:
        # Service tier advisors and transparent data encryption are not included in the first batch
        # of GA commands.
        c.ignore('expand')

    with self.argument_context('sql db list') as c:
        c.argument(
            'elastic_pool_name',
            help='If specified, lists only the databases in this elastic pool')

    with self.argument_context('sql db list-editions') as c:
        c.argument(
            'show_details',
            options_list=['--show-details', '-d'],
            help='List of additional details to include in output.',
            nargs='+',
            arg_type=get_enum_type(DatabaseCapabilitiesAdditionalDetails))

        search_arg_group = 'Search'

        # We could used get_enum_type here, but that will validate the inputs which means there
        # will be no way to query for new editions/service objectives that are made available after
        # this version of CLI is released.
        c.argument(
            'edition',
            arg_group=search_arg_group,
            help=
            'Edition to search for. If unspecified, all editions are shown.')
        c.argument(
            'service_objective',
            arg_group=search_arg_group,
            help=
            'Service objective to search for. If unspecified, all editions are shown.'
        )

    with self.argument_context('sql db update') as c:
        c.argument(
            'requested_service_objective_name',
            help=
            'The name of the new service objective. If this is a standalone db service'
            ' objective and the db is currently in an elastic pool, then the db is removed from'
            ' the pool.')
        c.argument(
            'elastic_pool_name',
            help='The name of the elastic pool to move the database into.')
        c.argument(
            'max_size_bytes',
            help='The new maximum size of the database expressed in bytes.')

    with self.argument_context('sql db export') as c:
        c.expand('parameters', ExportRequest)
        c.argument('administrator_login', options_list=['--admin-user', '-u'])
        c.argument('administrator_login_password',
                   options_list=['--admin-password', '-p'])
        c.argument('authentication_type',
                   options_list=['--auth-type', '-a'],
                   arg_type=get_enum_type(AuthenticationType))
        c.argument('storage_key_type', arg_type=get_enum_type(StorageKeyType))

    with self.argument_context('sql db import') as c:
        c.expand('parameters', ImportExtensionRequest)
        c.argument('administrator_login', options_list=['--admin-user', '-u'])
        c.argument('administrator_login_password',
                   options_list=['--admin-password', '-p'])
        c.argument('authentication_type',
                   options_list=['--auth-type', '-a'],
                   arg_type=get_enum_type(AuthenticationType))
        c.argument('storage_key_type', arg_type=get_enum_type(StorageKeyType))

        c.ignore('type')

        # The parameter name '--name' is used for 'database_name', so we need to give a different name
        # for the import extension 'name' parameter to avoid conflicts. This parameter is actually not
        # needed, but we still need to avoid this conflict.
        c.argument('name', options_list=['--not-name'], arg_type=ignore_type)

    with self.argument_context('sql db show-connection-string') as c:
        c.argument('client_provider',
                   options_list=['--client', '-c'],
                   help='Type of client connection provider.',
                   arg_type=get_enum_type(ClientType))

        auth_group = 'Authentication'

        c.argument('auth_type',
                   options_list=['--auth-type', '-a'],
                   arg_group=auth_group,
                   help='Type of authentication.',
                   arg_type=get_enum_type(ClientAuthenticationType))

    #####
    #           sql db op
    #####
    with self.argument_context('sql db op') as c:
        c.argument('database_name',
                   options_list=['--database', '-d'],
                   required=True,
                   help='Name of the Azure SQL Database.')

        c.argument('operation_id',
                   options_list=['--name', '-n'],
                   required=True,
                   help='The unique name of the operation to cancel.')

    #####
    #           sql db replica
    #####
    with self.argument_context('sql db replica create') as c:
        _configure_db_create_params(c, Engine.db, CreateMode.online_secondary)

        c.argument('elastic_pool_name',
                   options_list=['--elastic-pool'],
                   help='Name of elastic pool to create the new replica in.')

        c.argument('requested_service_objective_name',
                   options_list=['--service-objective'],
                   help='Name of service objective for the new replica.')

        c.argument(
            'partner_resource_group_name',
            options_list=['--partner-resource-group'],
            help='Name of the resource group to create the new replica in.'
            ' If unspecified, defaults to the origin resource group.')

        c.argument('partner_server_name',
                   options_list=['--partner-server'],
                   help='Name of the server to create the new replica in.')

    with self.argument_context('sql db replica set-primary') as c:
        c.argument('database_name', help='Name of the database to fail over.')
        c.argument(
            'server_name',
            help=
            'Name of the server containing the secondary replica that will become'
            ' the new primary.')
        c.argument(
            'resource_group_name',
            help=
            'Name of the resource group containing the secondary replica that'
            ' will become the new primary.')
        c.argument(
            'allow_data_loss',
            help='If specified, the failover operation will allow data loss.')

    with self.argument_context('sql db replica delete-link') as c:
        c.argument('partner_server_name',
                   options_list=['--partner-server'],
                   help='Name of the server that the other replica is in.')
        c.argument(
            'partner_resource_group_name',
            options_list=['--partner-resource-group'],
            help=
            'Name of the resource group that the other replica is in. If unspecified,'
            ' defaults to the first database\'s resource group.')

    #####
    #           sql db audit-policy & threat-policy
    #####
    def _configure_security_policy_storage_params(arg_ctx):
        storage_arg_group = 'Storage'

        arg_ctx.argument('storage_account',
                         options_list=['--storage-account'],
                         arg_group=storage_arg_group,
                         help='Name of the storage account.')

        arg_ctx.argument('storage_account_access_key',
                         options_list=['--storage-key'],
                         arg_group=storage_arg_group,
                         help='Access key for the storage account.')

        arg_ctx.argument('storage_endpoint',
                         arg_group=storage_arg_group,
                         help='The storage account endpoint.')

    with self.argument_context('sql db audit-policy update') as c:
        _configure_security_policy_storage_params(c)

        policy_arg_group = 'Policy'

        c.argument('state',
                   arg_group=policy_arg_group,
                   help='Auditing policy state',
                   arg_type=get_enum_type(BlobAuditingPolicyState))

        c.argument('audit_actions_and_groups',
                   options_list=['--actions'],
                   arg_group=policy_arg_group,
                   help='List of actions and action groups to audit.',
                   nargs='+')

        c.argument('retention_days',
                   arg_group=policy_arg_group,
                   help='The number of days to retain audit logs.')

    with self.argument_context('sql db threat-policy update') as c:
        _configure_security_policy_storage_params(c)

        policy_arg_group = 'Policy'
        notification_arg_group = 'Notification'

        c.argument('state',
                   arg_group=policy_arg_group,
                   help='Threat detection policy state',
                   arg_type=get_enum_type(SecurityAlertPolicyState))

        c.argument('retention_days',
                   arg_group=policy_arg_group,
                   help='The number of days to retain threat detection logs.')

        c.argument('disabled_alerts',
                   arg_group=policy_arg_group,
                   options_list=['--disabled-alerts'],
                   help='List of disabled alerts.',
                   nargs='+')

        c.argument('email_addresses',
                   arg_group=notification_arg_group,
                   options_list=['--email-addresses'],
                   help='List of email addresses that alerts are sent to.',
                   nargs='+')

        c.argument(
            'email_account_admins',
            arg_group=notification_arg_group,
            options_list=['--email-account-admins'],
            help='Whether the alert is sent to the account administrators.',
            arg_type=get_enum_type(SecurityAlertPolicyEmailAccountAdmins))

        # TODO: use server default

    #####
    #           sql db transparent-data-encryption
    #####
    with self.argument_context('sql db tde') as c:
        c.argument('database_name',
                   options_list=['--database', '-d'],
                   required=True,
                   help='Name of the Azure SQL Database.')

    with self.argument_context('sql db tde set') as c:
        c.argument('status',
                   options_list=['--status'],
                   required=True,
                   help='Status of the transparent data encryption.',
                   arg_type=get_enum_type(TransparentDataEncryptionStatus))

    ###############################################
    #                sql dw                       #
    ###############################################
    with self.argument_context('sql dw') as c:
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help='Name of the data warehouse.')

        c.argument('server_name', arg_type=server_param_type)

        c.argument(
            'max_size_bytes',
            options_list=['--max-size'],
            type=SizeWithUnitConverter('B', result_type=int),
            help=
            'The max storage size of the data warehouse. If no unit is specified, defaults'
            'to bytes (B).')

        c.argument('requested_service_objective_name',
                   options_list=['--service-objective'],
                   help='The service objective of the data warehouse.')

        c.argument('collation',
                   options_list=['--collation'],
                   help='The collation of the data warehouse.')

    with self.argument_context('sql dw create') as c:
        _configure_db_create_params(c, Engine.dw, CreateMode.default)

    with self.argument_context('sql dw show') as c:
        # Service tier advisors and transparent data encryption are not included in the first batch
        # of GA commands.
        c.ignore('expand')

    # Data Warehouse restore will not be included in the first batch of GA commands
    # (list_restore_points also applies to db, but it's not very useful. It's
    # mainly useful for dw.)
    # with ParametersContext(command='sql dw restore-point') as c:
    #     c.register_alias('database_name', ('--database', '-d'))

    ###############################################
    #                sql elastic-pool             #
    ###############################################
    with self.argument_context('sql elastic-pool') as c:
        # This line to be removed when zone redundancy is fully supported in production.
        c.ignore('zone_redundant')

        c.argument('elastic_pool_name',
                   options_list=['--name', '-n'],
                   help='The name of the elastic pool.')
        c.argument('server_name', arg_type=server_param_type)

        # --db-dtu-max and --db-dtu-min were the original param names, which is consistent with the
        # underlying REST API.
        # --db-max-dtu and --db-min-dtu are aliases which are consistent with the `sql elastic-pool
        # list-editions --show-details db-max-dtu db-min-dtu` parameter values. These are more
        # consistent with other az sql commands, but the original can't be removed due to
        # compatibility.
        c.argument('database_dtu_max',
                   options_list=['--db-dtu-max', '--db-max-dtu'])
        c.argument('database_dtu_min',
                   options_list=['--db-dtu-min', '--db-min-dtu'])

        # --storage was the original param name, which is consistent with the underlying REST API.
        # --max-size is an alias which is consistent with the `sql elastic-pool list-editions
        # --show-details max-size` parameter value and also matches `sql db --max-size` parameter name.
        c.argument(
            'storage_mb',
            options_list=['--storage', '--max-size'],
            type=SizeWithUnitConverter('MB', result_type=int),
            help=
            'The max storage size of the elastic pool. If no unit is specified, defaults'
            ' to megabytes (MB).')

    with self.argument_context('sql elastic-pool create') as c:
        c.expand('parameters', ElasticPool)
        # We have a wrapper function that determines server location so user doesn't need to specify
        # it as param.
        c.ignore('location')

    with self.argument_context('sql elastic-pool list-editions') as c:
        # Note that `ElasticPoolCapabilitiesAdditionalDetails` intentionally match param names to
        # other commands, such as `sql elastic-pool create --db-max-dtu --db-min-dtu --max-size`.
        c.argument(
            'show_details',
            options_list=['--show-details', '-d'],
            help='List of additional details to include in output.',
            nargs='+',
            arg_type=get_enum_type(ElasticPoolCapabilitiesAdditionalDetails))

        search_arg_group = 'Search'

        # We could used 'arg_type=get_enum_type' here, but that will validate the inputs which means there
        # will be no way to query for new editions that are made available after
        # this version of CLI is released.
        c.argument(
            'edition',
            arg_group=search_arg_group,
            help=
            'Edition to search for. If unspecified, all editions are shown.')
        c.argument(
            'dtu',
            arg_group=search_arg_group,
            help=
            'Elastic pool DTU limit to search for. If unspecified, all DTU limits are shown.'
        )

    with self.argument_context('sql elastic-pool update') as c:
        c.argument('database_dtu_max',
                   help='The maximum DTU any one database can consume.')
        c.argument('database_dtu_min',
                   help='The minimum DTU all databases are guaranteed.')
        c.argument('dtu', help='TThe total shared DTU for the elastic eool.')
        c.argument('storage_mb',
                   help='Storage limit for the elastic pool in MB.')

    ###############################################
    #                sql server                   #
    ###############################################
    with self.argument_context('sql server') as c:
        c.argument('server_name', options_list=['--name', '-n'])
        c.argument('administrator_login', options_list=['--admin-user', '-u'])
        c.argument('administrator_login_password',
                   options_list=['--admin-password', '-p'])

    with self.argument_context('sql server create') as c:
        # Both administrator_login and administrator_login_password are required for server creation.
        # However these two parameters are given default value in the create_or_update function
        # signature, therefore, they can't be automatically converted to requirement arguments.
        c.expand('parameters',
                 Server,
                 patches={
                     'administrator_login': patch_arg_make_required,
                     'administrator_login_password': patch_arg_make_required
                 })

        c.argument(
            'assign_identity',
            options_list=['--assign-identity', '-i'],
            help=
            'Generate and assign an Azure Active Directory Identity for this server'
            'for use with key management services like Azure KeyVault.')

        # 12.0 is the only server version allowed and it's already the default.
        c.ignore('version')

        # Identity will be handled with its own parameter.
        c.ignore('identity')

    with self.argument_context('sql server update') as c:
        c.argument('administrator_login_password',
                   help='The administrator login password.')
        c.argument(
            'assign_identity',
            options_list=['--assign_identity', '-i'],
            help=
            'Generate and assign an Azure Active Directory Identity for this server'
            'for use with key management services like Azure KeyVault.')

    #####
    #           sql server ad-admin
    ######
    with self.argument_context('sql server ad-admin') as c:
        c.argument('server_name',
                   options_list=['--server-name', '-s'],
                   help='The name of the SQL Server')
        c.argument(
            'login',
            options_list=['--display-name', '-u'],
            help='Display name of the Azure AD administrator user or group.')
        c.argument('sid',
                   options_list=['--object-id', '-i'],
                   help='The unique ID of the Azure AD administrator ')
        c.ignore('tenant_id')

    with self.argument_context('sql server ad-admin create') as c:
        c.expand('properties',
                 ServerAzureADAdministrator,
                 patches={'tenant_id': patch_arg_make_optional})

    #####
    #           sql server conn-policy
    #####
    with self.argument_context('sql server conn-policy') as c:
        c.argument('server_name', arg_type=server_param_type)
        c.argument('connection_type',
                   options_list=['--connection-type', '-t'],
                   arg_type=get_enum_type(ServerConnectionType))

    #####
    #           sql server firewall-rule
    #####
    with self.argument_context('sql server firewall-rule') as c:
        # Help text needs to be specified because 'sql server firewall-rule update' is a custom
        # command.
        c.argument('server_name', arg_type=server_param_type)

        c.argument('firewall_rule_name',
                   options_list=['--name', '-n'],
                   help='The name of the firewall rule.')

        c.argument(
            'start_ip_address',
            options_list=['--start-ip-address'],
            help=
            'The start IP address of the firewall rule. Must be IPv4 format. Use value'
            ' \'0.0.0.0\' to represent all Azure-internal IP addresses.')

        c.argument(
            'end_ip_address',
            options_list=['--end-ip-address'],
            help=
            'The end IP address of the firewall rule. Must be IPv4 format. Use value'
            ' \'0.0.0.0\' to represent all Azure-internal IP addresses.')

    #####
    #           sql server key
    #####
    with self.argument_context('sql server key') as c:
        c.argument('server_name', arg_type=server_param_type)
        c.argument('key_name', options_list=['--name', '-n'])
        c.argument(
            'kid',
            options_list=['--kid', '-k'],
            required=True,
            help=
            'The Azure Key Vault key identifier of the server key. An example key identifier is '
            '"https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901"'
        )

    #####
    #           sql server tde-key
    #####
    with self.argument_context('sql server tde-key') as c:
        c.argument('server_name', arg_type=server_param_type)

    with self.argument_context('sql server tde-key set') as c:
        c.argument(
            'kid',
            options_list=['--kid', '-k'],
            help=
            'The Azure Key Vault key identifier of the server key to be made encryption protector.'
            'An example key identifier is '
            '"https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901"'
        )
        c.argument('server_key_type',
                   options_list=['--server-key-type', '-t'],
                   help='The type of the server key',
                   arg_type=get_enum_type(ServerKeyType))

    #####
    #           sql server vnet-rule
    #####
    with self.argument_context('sql server vnet-rule') as c:
        # Help text needs to be specified because 'sql server vnet-rule create' is a custom
        # command.
        c.argument('server_name',
                   options_list=['--server', '-s'],
                   completer=get_resource_name_completion_list(
                       'Microsoft.SQL/servers'))

        c.argument('virtual_network_rule_name', options_list=['--name', '-n'])

        c.argument(
            'virtual_network_subnet_id',
            options_list=['--subnet'],
            help=
            'Name or ID of the subnet that allows access to an Azure Sql Server. '
            'If subnet name is provided, --vnet-name must be provided.')

        c.argument(
            'ignore_missing_vnet_service_endpoint',
            options_list=['--ignore-missing-endpoint', '-i'],
            help=
            'Create firewall rule before the virtual network has vnet service endpoint enabled',
            arg_type=get_three_state_flag())

    with self.argument_context('sql server vnet-rule create') as c:
        c.extra('vnet_name',
                options_list=['--vnet-name'],
                help='The virtual network name')
Example #27
0
#####
#           Reusable param type definitions
#####


sku_arg_group = 'Performance Level'

sku_component_arg_group = 'Performance Level (components)'

server_configure_help = 'You can configure the default using `az configure --defaults sql-server=<name>`'

server_param_type = CLIArgumentType(
    options_list=['--server', '-s'],
    configured_default='sql-server',
    help='Name of the Azure SQL server. ' + server_configure_help,
    completer=get_resource_name_completion_list('Microsoft.SQL/servers'),
    # Allow --ids command line argument. id_part=name is 1st name in uri
    id_part='name')

available_param_type = CLIArgumentType(
    options_list=['--available', '-a'],
    help='If specified, show only results that are available in the specified region.')

tier_param_type = CLIArgumentType(
    arg_group=sku_component_arg_group,
    options_list=['--tier', '--edition', '-e'])

capacity_param_type = CLIArgumentType(
    arg_group=sku_component_arg_group,
    options_list=['--capacity', '-c'])
Example #28
0
certificate_file_encoding_values = ['binary', 'string']

# KEY ATTRIBUTE PARAMETER REGISTRATION

def register_attributes_argument(scope, name, attr_class, create=False):
    register_cli_argument(scope, '{}_attributes'.format(name), ignore_type, validator=get_attribute_validator(name, attr_class, create))
    if create:
        register_extra_cli_argument(scope, 'disabled', action='store_true', help='Create {} in disabled state.'.format(name))
    else:
        register_extra_cli_argument(scope, 'enabled', default=None, choices=['true', 'false'], help='Enable the {}.'.format(name))
    register_extra_cli_argument(scope, 'expires', default=None, help='Expiration UTC datetime  (Y-m-d\'T\'H:M:S\'Z\').', type=datetime_type)
    register_extra_cli_argument(scope, 'not_before', default=None, help='Key not usable before the provided UTC datetime  (Y-m-d\'T\'H:M:S\'Z\').', type=datetime_type)

# ARGUMENT DEFINITIONS

vault_name_type = CliArgumentType(help='Name of the key vault.', options_list=('--vault-name',), completer=get_resource_name_completion_list('Microsoft.KeyVault/vaults'), id_part=None)

# PARAMETER REGISTRATIONS

register_cli_argument('keyvault', 'resource_group_name', resource_group_name_type, id_part=None, required=False, help='Proceed only if Key Vault belongs to the specified resource group.', validator=validate_resource_group_name)
register_cli_argument('keyvault', 'vault_name', vault_name_type, options_list=('--name', '-n'))
register_cli_argument('keyvault', 'object_id', help='a GUID that identifies the principal that will receive permissions')
register_cli_argument('keyvault', 'spn', help='name of a service principal that will receive permissions')
register_cli_argument('keyvault', 'upn', help='name of a user principal that will receive permissions')
register_cli_argument('keyvault', 'tags', tags_type)

register_cli_argument('keyvault create', 'resource_group_name', resource_group_name_type, completer=None, validator=None)
register_cli_argument('keyvault create', 'vault_name', completer=None)
register_cli_argument('keyvault create', 'sku', **enum_choice_list(SkuName))
register_cli_argument('keyvault create', 'no_self_perms', action='store_true', help="If specified, don't add permissions for the current user in the new vault")
Example #29
0
    register_extra_cli_argument(scope, 'source_share', default=None, help='The share name for the source storage account.', arg_group='Copy Source')
    register_extra_cli_argument(scope, 'source_path', default=None, help='The file path for the source storage account.', arg_group='Copy Source')
    register_extra_cli_argument(scope, 'source_container', default=None, help='The container name for the source storage account.', arg_group='Copy Source')
    register_extra_cli_argument(scope, 'source_blob', default=None, help='The blob name for the source storage account.', arg_group='Copy Source')
    register_extra_cli_argument(scope, 'source_snapshot', default=None, help='The blob snapshot for the source storage account.', arg_group='Copy Source')


# CUSTOM CHOICE LISTS

blob_types = {'block': BlockBlobService, 'page': PageBlobService, 'append': AppendBlobService}
delete_snapshot_types = {'include': DeleteSnapshot.Include, 'only': DeleteSnapshot.Only}
table_payload_formats = {'none': TablePayloadFormat.JSON_NO_METADATA, 'minimal': TablePayloadFormat.JSON_MINIMAL_METADATA, 'full': TablePayloadFormat.JSON_FULL_METADATA}

# ARGUMENT TYPES

account_name_type = CliArgumentType(options_list=('--account-name', '-n'), help='The storage account name.', completer=get_resource_name_completion_list('Microsoft.Storage/storageAccounts'), id_part='name')
blob_name_type = CliArgumentType(options_list=('--blob-name', '-b'), help='The blob name.', completer=get_storage_name_completion_list(BaseBlobService, 'list_blobs', parent='container_name'))
container_name_type = CliArgumentType(options_list=('--container-name', '-c'), help='The container name.', completer=get_storage_name_completion_list(BaseBlobService, 'list_containers'))
directory_type = CliArgumentType(options_list=('--directory-name', '-d'), help='The directory name.', completer=get_storage_name_completion_list(FileService, 'list_directories_and_files', parent='share_name'))
file_name_type = CliArgumentType(options_list=('--file-name', '-f'), completer=get_storage_name_completion_list(FileService, 'list_directories_and_files', parent='share_name'))
share_name_type = CliArgumentType(options_list=('--share-name', '-s'), help='The file share name.', completer=get_storage_name_completion_list(FileService, 'list_shares'))
table_name_type = CliArgumentType(options_list=('--table-name', '-t'), completer=get_storage_name_completion_list(TableService, 'list_tables'))
queue_name_type = CliArgumentType(options_list=('--queue-name', '-q'), help='The queue name.', completer=get_storage_name_completion_list(QueueService, 'list_queues'))

# PARAMETER REGISTRATIONS

register_cli_argument('storage', 'directory_name', directory_type)
register_cli_argument('storage', 'share_name', share_name_type)
register_cli_argument('storage', 'table_name', table_name_type)
register_cli_argument('storage', 'retry_wait', options_list=('--retry-interval',))
register_cli_argument('storage', 'progress_callback', ignore_type)
def load_arguments(self, _):

    from azext_front_door.vendored_sdks.models import (
        Mode, FrontDoorProtocol, FrontDoorCertificateSource, FrontDoorQuery, RuleGroupOverride, Action, RuleType, Transform,
        FrontDoorRedirectType, FrontDoorRedirectProtocol
    )

    frontdoor_name_type = CLIArgumentType(options_list=['--front-door-name', '-f'], help='Name of the Front Door.', completer=get_resource_name_completion_list('Microsoft.Network/frontdoors'), id_part='name')
    waf_policy_name_type = CLIArgumentType(options_list='--policy-name', help='Name of the WAF policy.', completer=get_resource_name_completion_list('Microsoft.Network/frontDoorWebApplicationFirewallPolicies'), id_part='name')

    # region FrontDoors
    fd_subresources = [
        {'name': 'backend-pool', 'display': 'backend pool', 'ref': 'backend_pools'},
        {'name': 'frontend-endpoint', 'display': 'frontend endpoint', 'ref': 'frontend_endpoints'},
        {'name': 'load-balancing', 'display': 'load balancing settings', 'ref': 'load_balancing_settings'},
        {'name': 'probe', 'display': 'health probe', 'ref': 'health_probe_settings'},
        {'name': 'routing-rule', 'display': 'routing rule', 'ref': 'routing_rules'}
    ]
    for item in fd_subresources:
        with self.argument_context('network front-door {}'.format(item['name'])) as c:
            c.argument('item_name', options_list=['--name', '-n'], help='Name of the {}'.format(item['display']), completer=get_fd_subresource_completion_list(item['ref']), id_part='child_name_1')
            c.argument('front_door_name', frontdoor_name_type, id_part=None)
            c.argument('resource_name', frontdoor_name_type, id_part=None)

    with self.argument_context('network front-door') as c:
        c.argument('front_door_name', frontdoor_name_type, options_list=['--name', '-n'])
        c.argument('friendly_name', help='Friendly name of the Front Door.')
        c.argument('tags', tags_type)
        c.argument('disabled', arg_type=get_three_state_flag(), help='Create in a disabled state.')
        c.argument('enabled', arg_type=get_three_state_flag(positive_label='Enabled', negative_label='Disabled', return_label=True), help='Enabled status.')

    with self.argument_context('network front-door', arg_group='Frontend Endpoint') as c:
        c.argument('frontend_host_name', help='Domain name of the frontend endpoint.')

    with self.argument_context('network front-door', arg_group='HTTPS') as c:
        c.argument('certificate_source', arg_type=get_enum_type(FrontDoorCertificateSource), help='Certificate source to enable HTTPS.')
        c.argument('secret_name', help='The name of the Key Vault secret representing the full certificate PFX')
        c.argument('secret_version', help='The version of the Key Vault secret representing the full certificate PFX')
        c.argument('vault_id', help='The resource id of the Key Vault containing the SSL certificate')

    with self.argument_context('network front-door', arg_group='BackendPools Settings') as c:
        c.argument('enforce_certificate_name_check', arg_type=get_three_state_flag(positive_label='Enabled', negative_label='Disabled', return_label=True), help='Whether to disable certificate name check on HTTPS requests to all backend pools. No effect on non-HTTPS requests.')

    with self.argument_context('network front-door', arg_group='Backend') as c:
        c.argument('backend_address', help='FQDN of the backend endpoint.')
        c.argument('backend_host_header', help='Host header sent to the backend.')

    with self.argument_context('network front-door', arg_group='Probe Setting') as c:
        c.argument('probe_path', options_list='--path', help='Path to probe.')
        c.argument('probe_protocol', options_list='--protocol', arg_type=get_enum_type(FrontDoorProtocol), help='Protocol to use for sending probes.')
        c.argument('probe_interval', options_list='--interval', help='Interval in seconds between probes.')

    with self.argument_context('network front-door', arg_group='Routing Rule') as c:
        c.argument('accepted_protocols', nargs='+', help='Space-separated list of protocols to accept. Default: Http')
        c.argument('patterns_to_match', options_list='--patterns', nargs='+', help='Space-separated list of patterns to match. Default: \'/*\'.')
        c.argument('forwarding_protocol', help='Protocol to use for forwarding traffic.')
        c.argument('route_type', arg_type=get_enum_type(RouteType), help='Route type to define how Front Door should handle requests for this route i.e. forward them to a backend or redirect the users to a different URL.')

    with self.argument_context('network front-door purge-endpoint') as c:
        c.argument('content_paths', nargs='+')

    with self.argument_context('network front-door backend-pool') as c:
        c.argument('load_balancing_settings', options_list='--load-balancing', help='Name or ID of the load balancing settings.', validator=validate_load_balancing_settings)
        c.argument('probe_settings', options_list='--probe', help='Name or ID of the probe settings.', validator=validate_probe_settings)

    with self.argument_context('network front-door frontend-endpoint') as c:
        c.argument('host_name', help='Domain name of the frontend endpoint.')
        c.argument('session_affinity_enabled', arg_type=get_three_state_flag(), help='Whether to allow session affinity on this host.')
        c.argument('session_affinity_ttl', help='The TTL to use in seconds for session affinity.', type=int)
        c.argument('waf_policy', help='Name or ID of a web application firewall policy.', validator=validate_waf_policy)

    with self.argument_context('network front-door load-balancing') as c:
        c.argument('additional_latency', type=int, help='The additional latency in milliseconds for probes to fall in the lowest latency bucket.')
        c.argument('sample_size', type=int, help='The number of samples to consider for load balancing decisions.')
        c.argument('successful_samples_required', type=int, help='The number of samples within the sample period that must succeed.')

    with self.argument_context('network front-door probe') as c:
        c.argument('path', help='Path to probe.')
        c.argument('protocol', arg_type=get_enum_type(FrontDoorProtocol), help='Protocol to use for sending probes.')
        c.argument('interval', help='Interval in seconds between probes.')

    for scope in ['backend-pool', 'backend-pool backend']:
        arg_group = 'Backend' if scope == 'backend-pool' else None
        with self.argument_context('network front-door {}'.format(scope), arg_group=arg_group) as c:
            c.argument('address', help='FQDN of the backend endpoint.')
            c.argument('host_header', help='Host header sent to the backend.')
            c.argument('priority', type=int, help='Priority to use for load balancing. Higher priorities will not be used for load balancing if any lower priority backend is healthy.')
            c.argument('http_port', type=int, help='HTTP TCP port number.')
            c.argument('https_port', type=int, help='HTTPS TCP port number.')
            c.argument('weight', type=int, help='Weight of this endpoint for load balancing purposes.')
            c.argument('backend_host_header', help='Host header sent to the backend.')
            c.argument('backend_pool_name', options_list='--pool-name', help='Name of the backend pool.')
            c.argument('index', type=int, help='Index of the backend to remove (starting with 1).')

    with self.argument_context('network front-door routing-rule', arg_group=None) as c:
        c.argument('accepted_protocols', nargs='+', help='Space-separated list of protocols to accept. Default: Http')
        c.argument('patterns_to_match', options_list='--patterns', nargs='+', help='Space-separated list of patterns to match. Default: \'/*\'.')
        c.argument('forwarding_protocol', help='Protocol to use for forwarding traffic.')
        c.argument('backend_pool', help='Name or ID of a backend pool.', validator=validate_backend_pool)
        c.argument('frontend_endpoints', help='Space-separated list of frontend endpoint names or IDs.', nargs='+', validator=validate_frontend_endpoints)
        c.argument('custom_forwarding_path', help='Custom path used to rewrite resource paths matched by this rule. Leave empty to use incoming path.')
        c.argument('dynamic_compression', arg_type=get_three_state_flag(positive_label='Enabled', negative_label='Disabled', return_label=True), help='Use dynamic compression for cached content.')
        c.argument('query_parameter_strip_directive', arg_type=get_enum_type(FrontDoorQuery), help='Treatment of URL query terms when forming the cache key.')
        c.argument('redirect_type', arg_type=get_enum_type(FrontDoorRedirectType), help='The redirect type the rule will use when redirecting traffic.')
        c.argument('redirect_protocol', arg_type=get_enum_type(FrontDoorRedirectProtocol), help='The protocol of the destination to where the traffic is redirected.')
        c.argument('custom_host', help='Host to redirect. Leave empty to use use the incoming host as the destination host.')
        c.argument('custom_path', help='The full path to redirect. Path cannot be empty and must start with /. Leave empty to use the incoming path as destination path.')
        c.argument('custom_fragment', help='Fragment to add to the redirect URL. Fragment is the part of the URL that comes after #. Do not include the #.')
        c.argument('custom_query_string', help='The set of query strings to be placed in the redirect URL. Setting this value would replace any existing query string; leave empty to preserve the incoming query string. Query string must be in <key>=<value> format. The first ? and & will be added automatically so do not include them in the front, but do separate multiple query strings with &.')
    # endregion

    # region WafPolicy
    with self.argument_context('network waf-policy') as c:
        c.argument('tags', tags_type)
        c.argument('disabled', arg_type=get_three_state_flag(), help='Create in a disabled state.')
        c.argument('enabled', arg_type=get_three_state_flag(positive_label='Enabled', negative_label='Disabled', return_label=True), help='Enabled status.')
        c.argument('location', get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)
        c.argument('mode', arg_type=get_enum_type(Mode), help='Firewall policy mode.')
        c.argument('policy_name', waf_policy_name_type, options_list=['--name', '-n'])

    with self.argument_context('network waf-policy set-managed-ruleset') as c:
        c.argument('action', arg_type=get_enum_type(Action), help='Action for overriden rulesets.')
        c.argument('override', arg_type=get_enum_type(RuleGroupOverride), help='Name of the ruleset to override.')
        c.argument('priority', type=int, help='Rule priority.')
        c.argument('version', help='Rule set version.')
        c.argument('disable', help='Disable managed ruleset override.', action='store_true')

    with self.argument_context('network waf-policy custom-rule') as c:
        c.argument('rule_name', options_list=['--name', '-n'], help='Name of the custom rule.', id_part='child_name_1')
        c.argument('policy_name', waf_policy_name_type)
        c.argument('priority', type=int, help='Priority of the rule.')
        c.argument('rate_limit_duration', type=int, help='Rate limit duration in minutes.')
        c.argument('rate_limit_threshold', type=int, help='Rate limit threshold.')
        c.argument('rule_type', arg_type=get_enum_type(RuleType), help='Type of rule.')
        c.argument('action', arg_type=get_enum_type(Action), help='Rule action.')
        c.argument('transforms', nargs='+', arg_type=get_enum_type(Transform), help='Space-separated list of transforms to apply.')
        c.argument('match_conditions', nargs='+', options_list='--match-condition', action=MatchConditionAction)

    with self.argument_context('network waf-policy custom-rule list') as c:
        c.argument('policy_name', waf_policy_name_type, id_part=None)
Example #31
0
    arg_type=get_enum_type(AuthenticationTypeDataplane,
                           AuthenticationTypeDataplane.key.value),
    arg_group="Access Control",
    help=
    "Indicates whether the operation should auto-derive a policy key or use the current Azure AD session. "
    "You can configure the default using `az configure --defaults iothub-data-auth-type=<auth-type-value>`",
    configured_default="iothub-data-auth-type",
    local_context_attribute=LocalContextAttribute(
        name="iothub-data-auth-type",
        actions=[LocalContextAction.SET, LocalContextAction.GET],
        scopes=["iot"],
    ),
)

hub_name_type = CLIArgumentType(
    completer=get_resource_name_completion_list("Microsoft.Devices/IotHubs"),
    help="IoT Hub name.",
)

event_msg_prop_type = CLIArgumentType(
    options_list=["--properties", "--props", "-p"],
    nargs="*",
    choices=CaseInsensitiveList(["sys", "app", "anno", "all"]),
    help="Indicate key message properties to output. "
    "sys = system properties, app = application properties, anno = annotations",
)

children_list_prop_type = CLIArgumentType(
    options_list=["--child-list", "--cl"],
    nargs="*",
    help="Child device list (space separated).",
Example #32
0
def load_arguments_eh(self, _):
    from azure.cli.core.commands.parameters import tags_type, get_enum_type, resource_group_name_type, name_type, \
        get_location_type, get_three_state_flag, get_resource_name_completion_list
    from azure.cli.core.commands.validators import get_default_location_from_resource_group
    from azure.cli.command_modules.eventhubs._completers import get_consumergroup_command_completion_list, \
        get_eventhubs_command_completion_list
    from azure.cli.command_modules.eventhubs._validator import validate_storageaccount, validate_partner_namespace, validate_rights
    from knack.arguments import CLIArgumentType
    from azure.cli.core.profiles import ResourceType
    (KeyType, AccessRights, SkuName,
     KeySource) = self.get_models('KeyType',
                                  'AccessRights',
                                  'SkuName',
                                  'KeySource',
                                  resource_type=ResourceType.MGMT_EVENTHUB)

    rights_arg_type = CLIArgumentType(
        options_list=['--rights'],
        nargs='+',
        arg_type=get_enum_type(AccessRights),
        validator=validate_rights,
        help='Space-separated list of Authorization rule rights')
    key_arg_type = CLIArgumentType(
        options_list=['--key'],
        arg_type=get_enum_type(KeyType),
        help='specifies Primary or Secondary key needs to be reset')
    keyvalue_arg_type = CLIArgumentType(
        options_list=['--key-value'],
        help=
        'Optional, if the key value provided, is set for KeyType or autogenerated Key value set for keyType.'
    )
    event_hub_name_arg_type = CLIArgumentType(options_list=['--eventhub-name'],
                                              help='Name of EventHub')
    namespace_name_arg_type = CLIArgumentType(
        options_list=['--namespace-name'],
        help='Name of Namespace',
        id_part='name')

    with self.argument_context('eventhubs') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('namespace_name', id_part='name', help='name of Namespace')

    with self.argument_context('eventhubs namespace exists') as c:
        c.argument(
            'namespace_name',
            arg_type=name_type,
            help=
            'Namespace name. Name can contain only letters, numbers, and hyphens. The namespace must start with a letter, and it must end with a letter or number.'
        )

    with self.argument_context('eventhubs namespace') as c:
        c.argument('namespace_name',
                   arg_type=name_type,
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.ServiceBus/namespaces'),
                   help='Name of Namespace')
        c.argument(
            'is_kafka_enabled',
            options_list=['--enable-kafka'],
            arg_type=get_three_state_flag(),
            help=
            'A boolean value that indicates whether Kafka is enabled for eventhub namespace.'
        )
        c.argument('tags', arg_type=tags_type)
        c.argument('sku',
                   options_list=['--sku'],
                   arg_type=get_enum_type(SkuName),
                   help='Namespace SKU.')
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('capacity', type=int, help='Capacity for Sku')
        c.argument(
            'is_auto_inflate_enabled',
            options_list=['--enable-auto-inflate'],
            arg_type=get_three_state_flag(),
            help=
            'A boolean value that indicates whether AutoInflate is enabled for eventhub namespace.'
        )
        c.argument(
            'maximum_throughput_units',
            type=int,
            help=
            'Upper limit of throughput units when AutoInflate is enabled, vaule should be within 0 to 20 throughput units. ( 0 if AutoInflateEnabled = true)'
        )
        c.argument('default_action',
                   arg_group='networkrule',
                   options_list=['--default-action'],
                   arg_type=get_enum_type(['Allow', 'Deny']),
                   help='Default Action for Network Rule Set.')
        c.argument(
            'trusted_service_access_enabled',
            options_list=['--enable-trusted-service-access', '-t'],
            arg_type=get_three_state_flag(),
            help=
            'A boolean value that indicates whether Trusted Service Access is enabled for Network Rule Set.'
        )
        c.argument(
            'zone_redundant',
            options_list=['--zone-redundant'],
            is_preview=True,
            arg_type=get_three_state_flag(),
            help=
            'Enabling this property creates a Standard EventHubs Namespace in regions supported availability zones'
        )
        c.argument(
            'identity',
            arg_group='Managed Identity',
            options_list=['--assign-identity'],
            is_preview=True,
            arg_type=get_three_state_flag(),
            help=
            'A boolean value that indicates whether Managed Identity is enabled.'
        )

    with self.argument_context('eventhubs namespace create',
                               min_api='2018-01-01-preview') as c:
        c.argument('cluster_arm_id',
                   options_list=['--cluster-arm-id'],
                   is_preview=True,
                   help='luster ARM ID of the Namespace')

    with self.argument_context('eventhubs namespace update',
                               arg_group='Managed Identity',
                               min_api='2018-01-01-preview') as c:
        c.argument(
            'key_source',
            options_list=['--key-source'],
            is_preview=True,
            arg_type=get_enum_type(KeySource),
            help=
            'Encryption key source. Possible values include: \'Microsoft.KeyVault\'.'
        )
        c.argument(
            'key_name',
            is_preview=True,
            help='The name of the KeyVault key.',
        )
        c.argument('key_vault_uri',
                   is_preview=True,
                   help='The Uri of the KeyVault.')
        c.argument('key_version',
                   is_preview=True,
                   help='The version of the KeyVault key to use.')

# Cluster region
    for scope in ['eventhubs cluster', 'eventhubs cluster namespace list']:
        with self.argument_context(scope) as c:
            c.argument('cluster_name',
                       arg_type=name_type,
                       id_part=None,
                       help='Name of Cluster')

    with self.argument_context('eventhubs cluster create') as c:
        c.argument(
            'location',
            arg_type=get_location_type(self.cli_ctx),
            id_part=None,
            help=
            'Location of the Cluster, for locations of available pre-provision clusters, please check az evetnhubs '
        )
        c.argument('capacity',
                   type=int,
                   help='Capacity for Sku, allowed value : 1')

    for scope in ['eventhubs cluster create', 'eventhubs cluster update']:
        with self.argument_context(scope) as c:
            c.argument('tags', arg_type=tags_type)

    # region Namespace Authorizationrule
    with self.argument_context(
            'eventhubs namespace authorization-rule list') as c:
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')

    with self.argument_context(
            'eventhubs namespace authorization-rule keys list') as c:
        c.argument('authorization_rule_name',
                   arg_type=name_type,
                   id_part=None,
                   help='Name of Namespace AuthorizationRule')
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')

    for scope in [
            'eventhubs namespace authorization-rule',
            'eventhubs namespace authorization-rule keys renew'
    ]:
        with self.argument_context(scope) as c:
            c.argument('authorization_rule_name',
                       arg_type=name_type,
                       id_part='child_name_1',
                       help='Name of Namespace AuthorizationRule')
            c.argument('namespace_name', arg_type=namespace_name_arg_type)

    for scope in [
            'eventhubs namespace authorization-rule create',
            'eventhubs namespace authorization-rule update',
            'eventhubs eventhub authorization-rule create',
            'eventhubs eventhub authorization-rule update'
    ]:
        with self.argument_context(scope) as c:
            c.argument('rights', arg_type=rights_arg_type)

    with self.argument_context(
            'eventhubs namespace authorization-rule keys renew') as c:
        c.argument('key_type', arg_type=key_arg_type)
        c.argument('key', arg_type=keyvalue_arg_type)

# region - Eventhub Create
    with self.argument_context('eventhubs eventhub') as c:
        c.argument('event_hub_name',
                   arg_type=name_type,
                   id_part='child_name_1',
                   completer=get_eventhubs_command_completion_list,
                   help='Name of Eventhub')

    for scope in ['eventhubs eventhub update', 'eventhubs eventhub create']:
        with self.argument_context(scope) as c:
            c.argument(
                'message_retention_in_days',
                options_list=['--message-retention'],
                type=int,
                help=
                'Number of days to retain events for this Event Hub, value should be 1 to 7 days and depends on Namespace sku. if Namespace sku is Basic than value should be one and is Manadatory parameter. Namespace sku is standard value should be 1 to 7 days, default is 7 days and is optional parameter'
            )
            c.argument(
                'partition_count',
                type=int,
                help=
                'Number of partitions created for the Event Hub. By default, allowed values are 2-32. Lower value of 1 is supported with Kafka enabled namespaces. In presence of a custom quota, the upper limit will match the upper limit of the quota.'
            )
            c.argument('status',
                       arg_type=get_enum_type(
                           ['Active', 'Disabled', 'SendDisabled']),
                       help='Status of Eventhub')
            c.argument(
                'enabled',
                options_list=['--enable-capture'],
                arg_type=get_three_state_flag(),
                help=
                'A boolean value that indicates whether capture description is enabled.'
            )
            c.argument(
                'skip_empty_archives',
                options_list=['--skip-empty-archives'],
                arg_type=get_three_state_flag(),
                help='A boolean value that indicates whether to Skip Empty.')
            c.argument(
                'capture_interval_seconds',
                arg_group='Capture',
                options_list=['--capture-interval'],
                type=int,
                help=
                'Allows you to set the frequency with which the capture to Azure Blobs will happen, value should between 60 to 900 seconds'
            )
            c.argument(
                'capture_size_limit_bytes',
                arg_group='Capture',
                options_list=['--capture-size-limit'],
                type=int,
                help=
                'Defines the amount of data built up in your Event Hub before an capture operation, value should be between 10485760 to 524288000 bytes'
            )
            c.argument(
                'destination_name',
                arg_group='Capture-Destination',
                help=
                'Name for capture destination, should be EventHubArchive.AzureBlockBlob.'
            )
            c.argument(
                'storage_account_resource_id',
                arg_group='Capture-Destination',
                validator=validate_storageaccount,
                options_list=['--storage-account'],
                help=
                'Name (if within same resource group and not of type Classic Storage) or ARM id of the storage account to be used to create the blobs'
            )
            c.argument('blob_container',
                       arg_group='Capture-Destination',
                       help='Blob container Name')
            c.argument(
                'archive_name_format',
                arg_group='Capture-Destination',
                help=
                'Blob naming convention for archive, e.g. {Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}. Here all the parameters (Namespace,EventHub .. etc) are mandatory irrespective of order'
            )

    with self.argument_context('eventhubs eventhub list') as c:
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')

    # region EventHub Authorizationrule
    for scope in [
            'eventhubs eventhub authorization-rule',
            'eventhubs eventhub authorization-rule keys renew'
    ]:
        with self.argument_context(scope) as c:
            c.argument('authorization_rule_name',
                       arg_type=name_type,
                       id_part='child_name_2',
                       help='Name of EventHub AuthorizationRule')
            c.argument('event_hub_name',
                       id_part='child_name_1',
                       arg_type=event_hub_name_arg_type)

    for scope in [
            'eventhubs eventhub authorization-rule create',
            'eventhubs eventhub authorization-rule update'
    ]:
        with self.argument_context(scope) as c:
            c.argument('rights', arg_type=rights_arg_type)

    with self.argument_context(
            'eventhubs eventhub authorization-rule keys renew') as c:
        c.argument('key_type', arg_type=key_arg_type)
        c.argument('key', arg_type=keyvalue_arg_type)

    with self.argument_context(
            'eventhubs eventhub authorization-rule list') as c:
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')
        c.argument('event_hub_name',
                   id_part=None,
                   arg_type=event_hub_name_arg_type)

    with self.argument_context(
            'eventhubs eventhub authorization-rule keys list') as c:
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')
        c.argument('event_hub_name',
                   id_part=None,
                   arg_type=event_hub_name_arg_type)
        c.argument('authorization_rule_name',
                   arg_type=name_type,
                   id_part=None,
                   help='Name of EventHub AuthorizationRule')

# - ConsumerGroup Region
    with self.argument_context('eventhubs eventhub consumer-group') as c:
        c.argument('event_hub_name', arg_type=event_hub_name_arg_type)
        c.argument('consumer_group_name',
                   arg_type=name_type,
                   id_part='child_name_2',
                   completer=get_consumergroup_command_completion_list,
                   help='Name of ConsumerGroup')

    for scope in [
            'eventhubs eventhub consumer-group create',
            'eventhubs eventhub consumer-group update'
    ]:
        with self.argument_context(scope) as c:
            c.argument(
                'user_metadata',
                help=
                'Usermetadata is a placeholder to store user-defined string data with maximum length 1024. e.g. it can be used to store descriptive data, such as list of teams and their contact information also user-defined configuration settings can be stored.'
            )

    with self.argument_context('eventhubs eventhub consumer-group list') as c:
        c.argument('event_hub_name',
                   arg_type=event_hub_name_arg_type,
                   id_part=None)
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')

#   : Region Geo DR Configuration
    with self.argument_context('eventhubs georecovery-alias') as c:
        c.argument('alias',
                   options_list=['--alias', '-a'],
                   id_part='child_name_1',
                   help='Name of Geo-Disaster Recovery Configuration Alias')

    with self.argument_context('eventhubs georecovery-alias exists') as c:
        c.argument(
            'name',
            options_list=['--alias', '-a'],
            arg_type=name_type,
            help='Name of Geo Recovery Configs - Alias to check availability')
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')

    with self.argument_context('eventhubs georecovery-alias set') as c:
        c.argument(
            'partner_namespace',
            required=True,
            validator=validate_partner_namespace,
            help=
            'Name (if within the same resource group) or ARM Id of the Primary/Secondary eventhub namespace name, which is part of GEO DR pairing'
        )
        c.argument(
            'alternate_name',
            help=
            'Alternate Name for the Alias, when the Namespace name and Alias name are same'
        )

    for scope in ['eventhubs georecovery-alias authorization-rule show']:
        with self.argument_context(scope) as c:
            c.argument('authorization_rule_name',
                       arg_type=name_type,
                       id_part='child_name_2',
                       help='Name of Namespace AuthorizationRule')

    with self.argument_context('eventhubs georecovery-alias list') as c:
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')

    with self.argument_context(
            'eventhubs georecovery-alias authorization-rule list') as c:
        c.argument('alias',
                   options_list=['--alias', '-a'],
                   help='Name of Geo-Disaster Recovery Configuration Alias')
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')

    with self.argument_context(
            'eventhubs georecovery-alias authorization-rule keys list') as c:
        c.argument('alias',
                   options_list=['--alias', '-a'],
                   id_part=None,
                   help='Name of Geo-Disaster Recovery Configuration Alias')
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')
        c.argument('authorization_rule_name',
                   arg_type=name_type,
                   help='Name of Namespace AuthorizationRule')

# Region Namespace NetworkRuleSet
    with self.argument_context('eventhubs namespace network-rule',
                               resource_type=ResourceType.MGMT_EVENTHUB,
                               min_api='2017-04-01') as c:
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of the Namespace')

    for scope in [
            'eventhubs namespace network-rule add',
            'eventhubs namespace network-rule remove'
    ]:
        with self.argument_context(scope,
                                   resource_type=ResourceType.MGMT_EVENTHUB,
                                   min_api='2017-04-01') as c:
            c.argument(
                'subnet',
                arg_group='Virtual Network Rule',
                options_list=['--subnet'],
                help=
                'Name or ID of subnet. If name is supplied, `--vnet-name` must be supplied.'
            )
            c.argument('ip_mask',
                       arg_group='IP Address Rule',
                       options_list=['--ip-address'],
                       help='IPv4 address or CIDR range - 10.6.0.0/24')
            c.argument('namespace_name',
                       options_list=['--namespace-name'],
                       id_part=None,
                       help='Name of the Namespace')
            c.extra('vnet_name',
                    arg_group='Virtual Network Rule',
                    options_list=['--vnet-name'],
                    help='Name of the Virtual Network')

    with self.argument_context('eventhubs namespace network-rule add',
                               resource_type=ResourceType.MGMT_EVENTHUB,
                               min_api='2017-04-01') as c:
        c.argument(
            'ignore_missing_vnet_service_endpoint',
            arg_group='Virtual Network Rule',
            options_list=['--ignore-missing-endpoint'],
            arg_type=get_three_state_flag(),
            help=
            'A boolean value that indicates whether to ignore missing vnet Service Endpoint'
        )
        c.argument('action',
                   arg_group='IP Address Rule',
                   options_list=['--action'],
                   arg_type=get_enum_type(['Allow']),
                   help='Action of the IP rule')
def load_arguments(self, _):

    ExpressRoutePortsEncapsulation, ExpressRouteCircuitSkuFamily, ExpressRouteCircuitSkuTier = self.get_models(
        'ExpressRoutePortsEncapsulation', 'ExpressRouteCircuitSkuFamily', 'ExpressRouteCircuitSkuTier')

    er_circuit_name_type = CLIArgumentType(options_list=('--circuit-name',), metavar='NAME', help='ExpressRoute circuit name.', id_part='name', completer=get_resource_name_completion_list('Microsoft.Network/expressRouteCircuits'))
    er_gateway_name_type = CLIArgumentType(options_list=('--gateway-name',), metavar='NAME', help='ExpressRoute gateway name.', id_part='name', completer=get_resource_name_completion_list('Microsoft.Network/expressRouteGateways'))
    er_port_name_type = CLIArgumentType(options_list=('--port-name',), metavar='NAME', help='ExpressRoute port name.', id_part='name', completer=get_resource_name_completion_list('Microsoft.Network/expressRoutePorts'))
    er_bandwidth_type = CLIArgumentType(options_list='--bandwidth', nargs='+')

    with self.argument_context('network express-route') as c:
        c.argument('tags', tags_type)
        c.argument('location', arg_type=get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)

    with self.argument_context('network express-route gateway') as c:
        c.argument('express_route_gateway_name', er_gateway_name_type, options_list=['--name', '-n'])
        c.argument('min_val', help='Minimum number of scale units deployed for gateway.', type=int, arg_group='Autoscale')
        c.argument('max_val', help='Maximum number of scale units deployed for gateway.', type=int, arg_group='Autoscale')
        c.argument('virtual_hub', help='Name or ID of the virtual hub to associate with the gateway.', validator=validate_virtual_hub)

    with self.argument_context('network express-route gateway connection') as c:
        c.argument('express_route_gateway_name', er_gateway_name_type)
        c.argument('connection_name', options_list=['--name', '-n'], help='ExpressRoute connection name.', id_part='child_name_1')
        c.argument('routing_weight', help='Routing weight associated with the connection.', type=int)
        c.argument('authorization_key', help='Authorization key to establish the connection.')

    with self.argument_context('network express-route gateway connection', arg_group='Peering') as c:
        c.argument('peering', help='Name or ID of an ExpressRoute peering.', validator=validate_express_route_peering)
        c.argument('circuit_name', er_circuit_name_type, id_part=None)

    with self.argument_context('network express-route gateway connection list') as c:
        c.argument('express_route_gateway_name', er_gateway_name_type, id_part=None)

    with self.argument_context('network express-route port') as c:
        c.argument('express_route_port_name', er_port_name_type, options_list=['--name', '-n'])
        c.argument('encapsulation', arg_type=get_enum_type(ExpressRoutePortsEncapsulation), help='Encapsulation method on physical ports.')
        c.argument('bandwidth_in_gbps', er_bandwidth_type, validator=bandwidth_validator_factory(mbps=False),
                   help='Bandwidth of the circuit. Usage: INT {Mbps,Gbps}. Defaults to Gbps')
        c.argument('peering_location', help='The name of the peering location that the port is mapped to physically.')

    with self.argument_context('network express-route port link') as c:
        c.argument('express_route_port_name', er_port_name_type)
        c.argument('link_name', options_list=['--name', '-n'], id_part='child_name_1')

    with self.argument_context('network express-route port link list') as c:
        c.argument('express_route_port_name', er_port_name_type, id_part=None)

    with self.argument_context('network express-route port location') as c:
        c.argument('location_name', options_list=['--location', '-l'])

    # region ExpressRoutes
    device_path_values = ['primary', 'secondary']
    sku_family_type = CLIArgumentType(help='Chosen SKU family of ExpressRoute circuit.', arg_type=get_enum_type(ExpressRouteCircuitSkuFamily), default=ExpressRouteCircuitSkuFamily.metered_data.value)
    sku_tier_type = CLIArgumentType(help='SKU Tier of ExpressRoute circuit.', arg_type=get_enum_type(ExpressRouteCircuitSkuTier), default=ExpressRouteCircuitSkuTier.standard.value)
    with self.argument_context('network express-route') as c:
        c.argument('circuit_name', er_circuit_name_type, options_list=('--name', '-n'))
        c.argument('sku_family', sku_family_type)
        c.argument('sku_tier', sku_tier_type)
        c.argument('bandwidth_in_mbps', er_bandwidth_type, validator=bandwidth_validator_factory(mbps=True),
                   help='Bandwidth of the circuit. Usage: INT {Mbps,Gbps}. Defaults to Mbps')
        c.argument('service_provider_name', options_list=('--provider',), help="Name of the ExpressRoute Service Provider.")
        c.argument('peering_location', help="Name of the peering location.")
        c.argument('device_path', options_list=('--path',), arg_type=get_enum_type(device_path_values))
        c.argument('vlan_id', type=int)
        c.argument('allow_global_reach', arg_type=get_three_state_flag(), min_api='2018-07-01', help='Enable global reach on the circuit.')

    with self.argument_context('network express-route') as c:
        c.argument('express_route_port', help='Name or ID of an ExpressRoute port.', validator=validate_express_route_port)

    with self.argument_context('network express-route update') as c:
        c.argument('sku_family', sku_family_type, default=None)
        c.argument('sku_tier', sku_tier_type, default=None)
Example #34
0
                                                  AuthenticationType)
from .custom import KeyType, SimpleAccessRights
from ._validators import (validate_policy_permissions,
                          validate_retention_days,
                          validate_fileupload_notification_max_delivery_count,
                          validate_fileupload_notification_ttl,
                          validate_fileupload_sas_ttl,
                          validate_feedback_ttl,
                          validate_feedback_lock_duration,
                          validate_feedback_max_delivery_count,
                          validate_c2d_max_delivery_count,
                          validate_c2d_ttl)


hub_name_type = CLIArgumentType(
    completer=get_resource_name_completion_list('Microsoft.Devices/IotHubs'),
    help='IoT Hub name.')

dps_name_type = CLIArgumentType(
    options_list=['--dps-name'],
    completer=get_resource_name_completion_list('Microsoft.Devices/ProvisioningServices'),
    help='IoT Provisioning Service name')

app_name_type = CLIArgumentType(
    completer=get_resource_name_completion_list('Microsoft.IoTCentral/IoTApps'),
    help='IoT Central application name.')


def load_arguments(self, _):  # pylint: disable=too-many-statements
    # Arguments for IoT DPS
    with self.argument_context('iot dps') as c:
Example #35
0
def load_arguments(self, _):

    from azure.mgmt.datalake.analytics.account.models.data_lake_analytics_account_management_client_enums import (
        FirewallState, TierType, FirewallAllowAzureIpsState, AADObjectType)

    from azure.mgmt.datalake.analytics.job.models.data_lake_analytics_job_management_client_enums import (
        CompileMode, JobState, JobResult)

    datalake_analytics_name_type = CLIArgumentType(help='Name of the Data Lake Analytics account.', options_list=('--account_name',), completer=get_resource_name_completion_list('Microsoft.DataLakeAnalytics/accounts'), id_part='name')

    # PARAMETER REGISTRATIONS
    # common
    with self.argument_context('dla') as c:
        c.argument('resource_group_name', resource_group_name_type, id_part=None, required=False, help='If not specified, will attempt to discover the resource group for the specified Data Lake Analytics account.', validator=validate_resource_group_name)
        c.argument('top', help='Maximum number of items to return.', type=int)
        c.argument('skip', help='The number of items to skip over before returning elements.', type=int)
        c.argument('count', help='The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true.', type=bool)
        c.argument('account_name', datalake_analytics_name_type, options_list=['--account', '-n'])

    # account
    with self.argument_context('dla account') as c:
        c.argument('tags', tags_type)
        c.argument('tier', arg_type=get_enum_type(TierType), help='The desired commitment tier for this account to use.')

    with self.argument_context('dla account create') as c:
        c.argument('resource_group_name', resource_group_name_type, validator=None)
        c.argument('account_name', datalake_analytics_name_type, options_list=('--account', '-n'), completer=None)

    with self.argument_context('dla account update') as c:
        c.argument('firewall_state', help='Enable/disable existing firewall rules.', arg_type=get_enum_type(FirewallState))
        c.argument('allow_azure_ips', help='Allow/block Azure originating IPs through the firewall', arg_type=get_enum_type(FirewallAllowAzureIpsState))
        c.argument('max_job_count', help='The maximum supported jobs running under the account at the same time.', type=int)
        c.argument('max_degree_of_parallelism', help='The maximum supported degree of parallelism for this account.', type=int)
        c.argument('query_store_retention', help='The number of days that job metadata is retained.', type=int)

    with self.argument_context('dla account list') as c:
        c.argument('resource_group_name', resource_group_name_type, validator=None)

    # storage
    with self.argument_context('dla account blob-storage') as c:
        c.argument('access_key', help='the access key associated with this Azure Storage account that will be used to connect to it')
        c.argument('suffix', help='the optional suffix for the storage account')

    # job
    with self.argument_context('dla job submit') as c:
        c.argument('compile_mode', arg_type=get_enum_type(CompileMode), help='Indicates the type of compilation to be done on this job. Valid values are: \'Semantic\' (Only performs semantic checks and necessary sanity checks), \'Full\' (full compilation) and \'SingleBox\' (Full compilation performed locally)')
        c.argument('compile_only', help='Indicates that the submission should only build the job and not execute if set to true.', action='store_true')
        c.argument('script', completer=FilesCompleter(), help="The script to submit. This is either the script contents or use `@<file path>` to load the script from a file")

    with self.argument_context('dla job wait') as c:
        c.argument('max_wait_time_sec', help='The maximum amount of time to wait before erroring out. Default value is to never timeout. Any value <= 0 means never timeout', type=int)
        c.argument('wait_interval_sec', help='The polling interval between checks for the job status, in seconds.', type=int)

    with self.argument_context('dla job list') as c:
        c.argument('submitted_after', help='A filter which returns jobs only submitted after the specified time, in ISO-8601 format.', type=datetime_format)
        c.argument('submitted_before', help='A filter which returns jobs only submitted before the specified time, in ISO-8601 format.', type=datetime_format)
        c.argument('state', arg_type=get_enum_type(JobState), help='A filter which returns jobs with only the specified state(s).', nargs='*')
        c.argument('result', arg_type=get_enum_type(JobResult), help='A filter which returns jobs with only the specified result(s).', nargs='*')
        c.argument('submitter', help='A filter which returns jobs only by the specified submitter.')
        c.argument('name', help='A filter which returns jobs only by the specified friendly name.')
        c.argument('pipeline_id', help='A filter which returns jobs only containing the specified pipeline_id.')
        c.argument('recurrence_id', help='A filter which returns jobs only containing the specified recurrence_id.')

    # credential
    with self.argument_context('dla catalog credential create') as c:
        c.argument('credential_user_password', options_list=['--password', '-p'], help='Password for the credential user. Will prompt if not given.')
        c.argument('credential_user_name', options_list=['--user-name'])

    with self.argument_context('dla catalog credential update') as c:
        c.argument('credential_user_name', options_list=['--user-name'])
        c.argument('credential_user_password', options_list=['--password', '-p'], help='Current password for the credential user. Will prompt if not given.')
        c.argument('new_credential_user_password', options_list=['--new-password'], help='New password for the credential user. Will prompt if not given.')

    # compute policy
    with self.argument_context('dla account compute_policy') as c:
        c.argument('max_dop_per_job', help='The maximum degree of parallelism allowed per job for this policy. At least one of --min-priority-per-job and --max-dop-per-job must be specified.', type=int)
        c.argument('min_priority_per_job', help='The minimum priority allowed per job for this policy. At least one of --min-priority-per-job and --max-dop-per-job must be specified.', type=int)

    with self.argument_context('dla account compute_policy create') as c:
        c.argument('object_id', help='The Azure Active Directory object ID of the user, group or service principal to apply the policy to.')
        c.argument('object_type', arg_type=get_enum_type(AADObjectType), help='The Azure Active Directory object type associated with the supplied object id.')
Example #36
0
def load_arguments(self, _):    # pylint: disable=too-many-statements

    server_completers = {
        'mariadb': get_resource_name_completion_list('Microsoft.DBForMariaDB/servers'),
        'mysql': get_resource_name_completion_list('Microsoft.DBForMySQL/servers'),
        'postgres': get_resource_name_completion_list('Microsoft.DBForPostgreSQL/servers')
    }

    def _complex_params(command_group):
        server_name_help = "Name of the server. The name can contain only lowercase letters, numbers, and the hyphen (-) character. " + \
                           "Minimum 3 characters and maximum 63 characters."
        server_name_scope = ['{}'.format(command_group)]
        server_name_setter_arg_type = CLIArgumentType(metavar='NAME', help=server_name_help, id_part='name',
                                                      local_context_attribute=LocalContextAttribute(name='server_name', actions=[LocalContextAction.SET], scopes=server_name_scope))
        server_name_getter_arg_type = CLIArgumentType(metavar='NAME', help=server_name_help, id_part='name',
                                                      local_context_attribute=LocalContextAttribute(name='server_name', actions=[LocalContextAction.GET], scopes=server_name_scope))
        server_name_arg_type = CLIArgumentType(metavar='NAME', help=server_name_help, id_part='name',
                                               local_context_attribute=LocalContextAttribute(name='server_name', actions=[LocalContextAction.SET, LocalContextAction.GET], scopes=server_name_scope))
        administrator_login_arg_type = CLIArgumentType(metavar='NAME',
                                                       local_context_attribute=LocalContextAttribute(name='administrator_login', actions=[LocalContextAction.GET, LocalContextAction.SET], scopes=server_name_scope))

        overriding_none_arg_type = CLIArgumentType(local_context_attribute=LocalContextAttribute(name='context_name', actions=[LocalContextAction.GET]))

        with self.argument_context(command_group) as c:
            c.argument('name', options_list=['--sku-name'], required=True)
            c.argument('server_name', arg_type=server_name_arg_type, completer=server_completers[command_group], options_list=['--server-name', '-s'])

        with self.argument_context('{} server'.format(command_group)) as c:
            c.ignore('family', 'capacity', 'tier')

            c.argument('server_name', arg_type=server_name_arg_type, options_list=['--name', '-n'], id_part='name', help='Name of the server. The name can contain only lowercase letters, numbers, and the hyphen (-) character. Minimum 3 characters and maximum 63 characters.')
            c.argument('administrator_login', options_list=['--admin-user', '-u'], help='Administrator username for the server. Once set, it cannot be changed.')
            c.argument('administrator_login_password', options_list=['--admin-password', '-p'], help='The password of the administrator. Minimum 8 characters and maximum 128 characters. Password must contain characters from three of the following categories: English uppercase letters, English lowercase letters, numbers, and non-alphanumeric characters.')
            c.argument('ssl_enforcement', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--ssl-enforcement'], help='Enable or disable ssl enforcement for connections to server. Default is Enabled.')
            c.argument('minimal_tls_version', arg_type=get_enum_type(['TLS1_0', 'TLS1_1', 'TLS1_2', 'TLSEnforcementDisabled']), options_list=['--minimal-tls-version'], help='Set the minimal TLS version for connections to server when SSL is enabled. Default is TLSEnforcementDisabled.', validator=tls_validator)
            c.argument('public_network_access', options_list=['--public-network-access', '--public'], help='Enable or disable public network access to server. When disabled, only connections made through Private Links can reach this server. Allowed values are : Enabled, Disabled, all, 0.0.0.0, <SingleIP>, <StartIP-DestinationIP>. Default is Enabled.')
            c.argument('tier', arg_type=get_enum_type(['Basic', 'GeneralPurpose', 'MemoryOptimized']), options_list=['--performance-tier'], help='The performance tier of the server.')
            c.argument('capacity', options_list=['--vcore'], type=int, help='Number of vcore.')
            c.argument('family', options_list=['--family'], arg_type=get_enum_type(['Gen4', 'Gen5']), help='Hardware generation.')
            c.argument('storage_mb', options_list=['--storage-size'], type=int, help='The storage capacity of the server (unit is megabytes). Minimum 5120 and increases in 1024 increments. Default is 51200.')
            c.argument('backup_retention', options_list=['--backup-retention'], type=int, help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.', validator=retention_validator)
            c.argument('auto_grow', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--auto-grow'], help='Enable or disable autogrow of the storage. Default value is Enabled.')
            c.argument('infrastructure_encryption', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--infrastructure-encryption', '-i'], help='Add an optional second layer of encryption for data using new encryption algorithm. Default value is Disabled.')
            c.argument('assign_identity', options_list=['--assign-identity'], help='Generate and assign an Azure Active Directory Identity for this server for use with key management services like Azure KeyVault.')
            c.argument('tags', tags_type)

            if command_group == 'mariadb':
                c.ignore('minimal_tls_version')
                c.ignore('assign_identity')
                c.ignore('infrastructure_encryption')

        with self.argument_context('{} server create'.format(command_group)) as c:
            c.argument('server_name', options_list=['--name', '-n'], arg_type=server_name_setter_arg_type)
            c.argument('sku_name', default='GP_Gen5_2', options_list=['--sku-name'],
                       help='The name of the sku. Follows the convention {pricing tier}_{compute generation}_{vCores} in shorthand. Examples: B_Gen5_1, GP_Gen5_4, MO_Gen5_16. ')
            c.argument('administrator_login', default=generate_username(), arg_group='Authentication')
            c.argument('administrator_login_password', arg_group='Authentication')

            c.argument('backup_retention', type=int, options_list=['--backup-retention'], help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.', validator=retention_validator)
            c.argument('geo_redundant_backup', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--geo-redundant-backup'], help='Enable or disable geo-redundant backups. Default value is Disabled. Not supported in Basic pricing tier.')
            c.argument('storage_mb', default=51200, options_list=['--storage-size'], type=int, help='The storage capacity of the server (unit is megabytes). Minimum 5120 and increases in 1024 increments. Default is 51200.')
            c.argument('auto_grow', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--auto-grow'], help='Enable or disable autogrow of the storage. Default value is Enabled.')
            c.argument('infrastructure_encryption', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--infrastructure-encryption', '-i'], help='Add an optional second layer of encryption for data using new encryption algorithm. Default value is Disabled.')
            c.argument('assign_identity', options_list=['--assign-identity'], help='Generate and assign an Azure Active Directory Identity for this server for use with key management services like Azure KeyVault.')

            c.argument('location', arg_type=get_location_type(self.cli_ctx))
            c.argument('version', help='Server major version.')

        with self.argument_context('{} server update'.format(command_group)) as c:
            c.ignore('family', 'capacity', 'tier')
            c.argument('sku_name', options_list=['--sku-name'], help='The name of the sku. Follows the convention {pricing tier}_{compute generation}_{vCores} in shorthand. Examples: B_Gen5_1, GP_Gen5_4, MO_Gen5_16.')
            c.argument('assign_identity', options_list=['--assign-identity'], help='Generate and assign an Azure Active Directory Identity for this server for use with key management services like Azure KeyVault.')

        with self.argument_context('{} server restore'. format(command_group)) as c:
            c.argument('server_name', options_list=['--name', '-n'], arg_type=overriding_none_arg_type)
            c.argument('source_server', options_list=['--source-server', '-s'], help='The name or resource ID of the source server to restore from.')
            c.argument('restore_point_in_time', options_list=['--restore-point-in-time', '--pitr-time'], help='The point in time to restore from (ISO8601 format), e.g., 2017-04-26T02:10:00+08:00')

        with self.argument_context('{} server georestore'. format(command_group)) as c:
            c.argument('location', arg_type=get_location_type(self.cli_ctx), required=True)
            c.argument('sku_name', options_list=['--sku-name'], required=False, help='The name of the sku. Defaults to sku of the source server. Follows the convention {pricing tier}_{compute generation}_{vCores} in shorthand. Examples: B_Gen5_1, GP_Gen5_4, MO_Gen5_16.')
            c.argument('source_server', options_list=['--source-server', '-s'], required=True, help='The name or ID of the source server to restore from.')
            c.argument('backup_retention', options_list=['--backup-retention'], type=int, help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.', validator=retention_validator)
            c.argument('geo_redundant_backup', options_list=['--geo-redundant-backup'], help='Enable or disable geo-redundant backups. Default value is Disabled. Not supported in Basic pricing tier.')

        with self.argument_context('{} server replica'.format(command_group)) as c:
            c.argument('server_name', options_list=['--name', '-n'], arg_type=overriding_none_arg_type)
            c.argument('source_server', options_list=['--source-server', '-s'], help='The name or resource ID of the master server to the create replica for.')
            c.argument('location', options_list=['--location', '-l'], help='Location. Values from: `az account list-locations`. If not provided, the create replica will be in the same location as the master server')
            c.argument('sku_name', options_list=['--sku-name'], help='The name of the sku. Follows the convention {pricing tier}_{compute generation}_{vCores} in shorthand. Examples: B_Gen5_1, GP_Gen5_4, MO_Gen5_16.')

        with self.argument_context('{} server configuration set'.format(command_group)) as c:
            c.argument('value', help='Value of the configuration. If not provided, configuration value will be set to default.', validator=configuration_value_validator)
            c.ignore('source')

        with self.argument_context('{} server wait'.format(command_group)) as c:
            c.ignore('created', 'deleted', 'updated')

        with self.argument_context('{} server delete'.format(command_group)) as c:
            c.argument('server_name', options_list=['--name', '-n'], arg_type=server_name_getter_arg_type)

        with self.argument_context('{} server-logs'.format(command_group)) as c:
            c.argument('file_name', options_list=['--name', '-n'], nargs='+', help='Space-separated list of log filenames on the server to download.')
            c.argument('max_file_size', type=int, help='The file size limitation to filter files.')
            c.argument('file_last_written', type=int, help='Integer in hours to indicate file last modify time, default value is 72.')
            c.argument('filename_contains', help='The pattern that file name should match.')

        with self.argument_context('{} server-logs list'.format(command_group)) as c:
            c.argument('server_name', id_part=None, help='Name of the Server.')

        with self.argument_context('{} db'.format(command_group)) as c:
            c.argument('database_name', options_list=['--name', '-n'])

        with self.argument_context('{} db list'.format(command_group)) as c:
            c.argument('server_name', id_part=None, help='Name of the Server.')

        with self.argument_context('{} server firewall-rule'.format(command_group)) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('firewall_rule_name', options_list=['--name', '-n'], id_part='child_name_1', help='The name of the firewall rule. The firewall rule name cannot be empty. The firewall rule name can only contain 0-9, a-z, A-Z, \'-\' and \'_\'. Additionally, the firewall rule name cannot exceed 128 characters.')
            c.argument('start_ip_address', options_list=['--start-ip-address'], help='The start IP address of the firewall rule. Must be IPv4 format. Use value \'0.0.0.0\' to represent all Azure-internal IP addresses.')
            c.argument('end_ip_address', options_list=['--end-ip-address'], help='The end IP address of the firewall rule. Must be IPv4 format. Use value \'0.0.0.0\' to represent all Azure-internal IP addresses.')

        with self.argument_context('{} server vnet-rule'.format(command_group)) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('virtual_network_rule_name', options_list=['--name', '-n'], id_part='child_name_1', help='The name of the vnet rule.')
            c.argument('virtual_network_subnet_id', options_list=['--subnet'], help='Name or ID of the subnet that allows access to an Azure Postgres Server. If subnet name is provided, --vnet-name must be provided.')
            c.argument('ignore_missing_vnet_service_endpoint', options_list=['--ignore-missing-endpoint', '-i'], help='Create vnet rule before virtual network has vnet service endpoint enabled', arg_type=get_three_state_flag())

        with self.argument_context('{} server vnet-rule create'.format(command_group)) as c:
            c.extra('vnet_name', options_list=['--vnet-name'], help='The virtual network name', validator=validate_subnet)

        with self.argument_context('{} server vnet-rule update'.format(command_group)) as c:
            c.extra('vnet_name', options_list=['--vnet-name'], help='The virtual network name',
                    validator=validate_subnet)

        with self.argument_context('{} server configuration'.format(command_group)) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('configuration_name', id_part='child_name_1', options_list=['--name', '-n'])

        with self.argument_context('{} server replica list'.format(command_group)) as c:
            c.argument('server_name', options_list=['--server-name', '-s'], help='Name of the master server.')

        for item in ['approve', 'reject', 'delete', 'show']:
            with self.argument_context('{} server private-endpoint-connection {}'.format(command_group, item)) as c:
                c.argument('private_endpoint_connection_name', options_list=['--name', '-n'], required=False,
                           help='The name of the private endpoint connection associated with the Server. '
                                'Required if --id is not specified')
                c.extra('connection_id', options_list=['--id'], required=False,
                        help='The ID of the private endpoint connection associated with the Server. '
                             'If specified --server-name/-s and --name/-n, this should be omitted.')
                c.argument('server_name', options_list=['--server-name', '-s'], required=False,
                           help='Name of the Server. Required if --id is not specified')
                c.argument('resource_group_name', help='The resource group name of specified server.',
                           required=False)
                c.argument('description', help='Comments for {} operation.'.format(item))

        with self.argument_context('{} server private-link-resource'.format(command_group)) as c:
            c.argument('server_name', options_list=['--server-name', '-s'], required=True, help='Name of the Server.')

        with self.argument_context('{} server list-skus'.format(command_group)) as c:
            c.argument('location_name', options_list=['--location', '-l'])

        with self.argument_context('{} server show-connection-string'.format(command_group)) as c:
            c.argument('server_name', options_list=['--server-name', '-s'], arg_type=server_name_arg_type, help='Name of the server.')
            c.argument('administrator_login', options_list=['--admin-user', '-u'], arg_type=administrator_login_arg_type,
                       help='The login username of the administrator.')
            c.argument('administrator_login_password', options_list=['--admin-password', '-p'],
                       help='The login password of the administrator.')
            c.argument('database_name', options_list=['--database-name', '-d'], help='The name of a database.')

        if command_group != 'mariadb':
            with self.argument_context('{} server key'.format(command_group)) as c:
                c.argument('server_name', options_list=['--name', '-s'])
                c.argument('kid', options_list=['--kid', '-k'], help='The Azure Key Vault key identifier of the server key. An example key identifier is "https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901"')

            with self.argument_context('{} server ad-admin'.format(command_group)) as c:
                c.argument('server_name', options_list=['--server-name', '-s'])
                c.argument('login', options_list=['--display-name', '-u'], help='Display name of the Azure AD administrator user or group.')
                c.argument('sid', options_list=['--object-id', '-i'], help='The unique ID of the Azure AD administrator.')

        if command_group == 'mysql':
            with self.argument_context('{} server upgrade'.format(command_group)) as c:
                c.argument('target_server_version', options_list=['--target-server-version', '-t'], required=True, help='The server version you want to upgrade your mysql server to, currently only support 5.7.')

    _complex_params('mariadb')
    _complex_params('mysql')
    _complex_params('postgres')

    # Flexible-server
    def _flexible_server_params(command_group):

        server_name_setter_arg_type = CLIArgumentType(metavar='NAME',
                                                      help="Name of the server. The name can contain only lowercase letters, numbers, and the hyphen (-) character. Minimum 3 characters and maximum 63 characters.",
                                                      local_context_attribute=LocalContextAttribute(name='server_name', actions=[LocalContextAction.SET], scopes=['{} flexible-server'.format(command_group)]))

        server_name_getter_arg_type = CLIArgumentType(metavar='NAME',
                                                      help="Name of the server. The name can contain only lowercase letters, numbers, and the hyphen (-) character. Minimum 3 characters and maximum 63 characters.",
                                                      local_context_attribute=LocalContextAttribute(name='server_name', actions=[LocalContextAction.GET], scopes=['{} flexible-server'.format(command_group)]))

        server_name_arg_type = CLIArgumentType(metavar='NAME',
                                               help="Name of the server. The name can contain only lowercase letters, numbers, and the hyphen (-) character. Minimum 3 characters and maximum 63 characters.",
                                               local_context_attribute=LocalContextAttribute(name='server_name', actions=[LocalContextAction.SET, LocalContextAction.GET], scopes=['{} flexible-server'.format(command_group)]))

        administrator_login_setter_arg_type = CLIArgumentType(metavar='NAME',
                                                              local_context_attribute=LocalContextAttribute(name='administrator_login', actions=[LocalContextAction.SET], scopes=['{} flexible-server'.format(command_group)]))

        administrator_login_arg_type = CLIArgumentType(metavar='NAME',
                                                       local_context_attribute=LocalContextAttribute(name='administrator_login', actions=[LocalContextAction.GET, LocalContextAction.SET], scopes=['{} flexible-server'.format(command_group)]))

        database_name_setter_arg_type = CLIArgumentType(metavar='NAME',
                                                        local_context_attribute=LocalContextAttribute(name='database_name', actions=[LocalContextAction.SET], scopes=['{} flexible-server'.format(command_group)]))

        database_name_getter_arg_type = CLIArgumentType(metavar='NAME',
                                                        local_context_attribute=LocalContextAttribute(name='database_name', actions=[LocalContextAction.GET], scopes=['{} flexible-server'.format(command_group)]))

        database_name_arg_type = CLIArgumentType(metavar='NAME',
                                                 local_context_attribute=LocalContextAttribute(name='database_name', actions=[LocalContextAction.GET, LocalContextAction.SET], scopes=['{} flexible-server'.format(command_group)]))

        overriding_none_arg_type = CLIArgumentType(local_context_attribute=LocalContextAttribute(name='context_name', actions=[LocalContextAction.GET]))

        with self.argument_context('{} flexible-server'.format(command_group)) as c:
            c.argument('server_name', id_part='name', options_list=['--name', '-n'], arg_type=server_name_arg_type)

        with self.argument_context('{} flexible-server create'.format(command_group)) as c:
            # Add create mode as a parameter
            if command_group == 'postgres':
                c.argument('tier', default='GeneralPurpose', options_list=['--tier'],
                           help='Compute tier of the server. Accepted values: Burstable, GeneralPurpose, Memory Optimized ')
                c.argument('sku_name', default='Standard_D2s_v3', options_list=['--sku-name'],
                           help='The name of the compute SKU. Follows the convention Standard_{VM name}. Examples: Standard_D4s_v3 ')
                c.argument('storage_mb', default='128', options_list=['--storage-size'], type=int,
                           help='The storage capacity of the server. Minimum is 32 GiB and max is 16 TiB.')
                c.argument('backup_retention', default=7, type=int, options_list=['--backup-retention'],
                           help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.',
                           validator=retention_validator)
                c.argument('version', default='12', options_list=['--version'],
                           help='Server major version.')
                c.argument('zone', options_list=['--zone, -z'],
                           help='Availability zone into which to provision the resource.')
            elif command_group == 'mysql':
                c.argument('tier', default='Burstable',
                           help='Compute tier of the server. Accepted values: Burstable, GeneralPurpose, Memory Optimized ')
                c.argument('sku_name', default='Standard_B1ms', options_list=['--sku-name'],
                           help='The name of the compute SKU. Follows the convention Standard_{VM name}. Examples: Standard_B1ms, Standard_E16ds_v4 ')
                c.argument('storage_mb', default='10', options_list=['--storage-size'], type=int,
                           help='The storage capacity of the server. Minimum is 5 GiB and increases in 1 GiB increments. Max is 16 TiB.')
                c.argument('backup_retention', default=7, type=int, options_list=['--backup-retention'],
                           help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.')
                c.argument('version', default='5.7', options_list=['--version'],
                           help='Server major version.')
                c.argument('zone', options_list=['--zone, -z'],
                           help='Availability zone into which to provision the resource.')

            c.argument('vnet_resource_id', options_list=['--vnet'], help='Name of an existing virtual network or name of a new one to create. The name must be between 2 to 64 characters. The name must begin with a letter or number, end with a letter, number or underscore, and may contain only letters, numbers, underscores, periods, or hyphens.')
            c.argument('vnet_address_prefix', options_list=['--address-prefixes'], help='The IP address prefix to use when creating a new virtual network in CIDR format. Default value is 10.0.0.0/16.')
            c.argument('subnet_address_prefix', options_list=['--subnet-prefixes'], help='The subnet IP address prefix to use when creating a new VNet in CIDR format. Default value is 10.0.0.0/24.')
            c.argument('subnet_arm_resource_id', options_list=['--subnet'],
                       help='Resource ID of an existing subnet. Please note that the subnet will be delegated to Microsoft.DBforPostgreSQL/flexibleServers/Microsoft.DBforMySQL/flexibleServers.After delegation, this subnet cannot be used for any other type of Azure resources.')
            c.argument('server_name', options_list=['--name', '-n'], arg_type=server_name_setter_arg_type)
            c.argument('location', arg_type=get_location_type(self.cli_ctx))
            c.argument('administrator_login', default=generate_username(), options_list=['--admin-user, -u'], arg_group='Authentication', arg_type=administrator_login_setter_arg_type,
                       help='Administrator username for the server. Once set, it cannot be changed. ')
            c.argument('administrator_login_password', options_list=['--admin-password', '-p'],
                       help='The password of the administrator. Minimum 8 characters and maximum 128 characters. Password must contain characters from three of the following categories: English uppercase letters, English lowercase letters, numbers, and non-alphanumeric characters.',
                       arg_group='Authentication')
            c.argument('tags', tags_type)
            c.argument('public_access', options_list=['--public-access'],
                       help='Determines the public access. Enter single or range of IP addresses to be included in the allowed list of IPs. IP address ranges must be dash-separated and not contain any spaces. Specifying 0.0.0.0 allows public access from any resources deployed within Azure to access your server. Specifying no IP address sets the server in public access mode but does not create a firewall rule. ',
                       validator=public_access_validator)
            c.argument('high_availability', default="Disabled", options_list=['--high-availability'], help='Enable or disable high availability feature.  Default value is Disabled.')
            c.argument('assign_identity', options_list=['--assign-identity'],
                       help='Generate and assign an Azure Active Directory Identity for this server for use with key management services like Azure KeyVault. No need to enter extra argument.')
            c.ignore('database_name')

        with self.argument_context('{} flexible-server delete'.format(command_group)) as c:
            c.argument('server_name', id_part='name', options_list=['--name', '-n'], arg_type=server_name_getter_arg_type)
            c.argument('yes', options_list=['--yes', '-y'], action='store_true',
                       help='Do not prompt for confirmation.')

        with self.argument_context('{} flexible-server restore'.format(command_group)) as c:
            c.argument('server_name', options_list=['--name', '-n'], arg_type=overriding_none_arg_type,
                       help='The name of the new server that is created by the restore command.')
            c.argument('restore_point_in_time', options_list=['--restore-time'],
                       help='The point in time to restore from (ISO8601 format), e.g., 2017-04-26T02:10:00+08:00')
            if command_group == 'postgres':
                c.argument('source_server', options_list=['--source-server'],
                           help='The name of the source server to restore from.')
            elif command_group == 'mysql':
                c.argument('source_server', options_list=['--source-server'],
                           help='The name or resource ID of the source server to restore from.')

        with self.argument_context('{} flexible-server update'.format(command_group)) as c:
            c.ignore('assign_identity')
            c.argument('administrator_login_password', options_list=['--admin-password', '-p'],
                       help='The password of the administrator. Minimum 8 characters and maximum 128 characters. Password must contain characters from three of the following categories: English uppercase letters, English lowercase letters, numbers, and non-alphanumeric characters.',)
            c.argument('ha_enabled', options_list=['--high-availability'], arg_type=get_enum_type(['Enabled', 'Disabled']),
                       help='Enable or disable high availability feature.  Default value is Disabled.')
            c.argument('maintenance_window', options_list=['--maintenance-window'], validator=maintenance_window_validator,
                       help='Period of time (UTC) designated for maintenance. Examples: "Sun:23:30" to schedule on Sunday, 11:30pm UTC. To set back to default pass in "Disabled".')
            c.argument('tags', tags_type)
            if command_group == 'mysql':
                c.argument('tier', options_list=['--tier'],
                           help='Compute tier of the server. Accepted values: Burstable, GeneralPurpose, Memory Optimized')
                c.argument('sku_name', options_list=['--sku-name'],
                           help='The name of the compute SKU. Follows the convention Standard_{VM name}. Examples: Standard_B1ms, Standard_E16ds_v4 ')
                c.argument('storage_mb', options_list=['--storage-size'], type=int,
                           help='The storage capacity of the server. Minimum is 5 GiB and increases in 1 GiB increments. Max is 16 TiB.')
                c.argument('backup_retention', type=int, options_list=['--backup-retention'],
                           help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.')
                c.argument('auto_grow', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--storage-auto-grow'],
                           help='Enable or disable autogrow of the storage. Default value is Enabled.')
                c.argument('ssl_enforcement', arg_type=get_enum_type(['Enabled', 'Disabled']),
                           options_list=['--ssl-enforcement'],
                           help='Enable or disable ssl enforcement for connections to server. Default is Enabled.')
                c.argument('subnet_arm_resource_id', options_list=['--subnet'],
                           help='Name or ID of the subnet that allows access to an Azure Flexible Server MySQL Server. ')
                c.argument('replication_role', options_list=['--replication-role'],
                           help='The replication role of the server.')
            elif command_group == 'postgres':
                c.argument('tier', options_list=['--tier'],
                           help='Compute tier of the server. Accepted values: Burstable, GeneralPurpose, Memory Optimized')
                c.argument('sku_name', options_list=['--sku-name'],
                           help='The name of the compute SKU. Follows the convention Standard_{VM name}. Examples: Standard_D4s_v3 ')
                c.argument('storage_mb', options_list=['--storage-size'], type=int,
                           help='The storage capacity of the server. Minimum is 32 GiB and max is 16 TiB.')
                c.argument('backup_retention', type=int, options_list=['--backup-retention'],
                           help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.', validator=retention_validator)

        with self.argument_context('{} flexible-server list-skus'.format(command_group)) as c:
            c.argument('location', arg_type=get_location_type(self.cli_ctx))

        # flexible-server parameter
        for scope in ['list', 'set', 'show']:
            argument_context_string = '{} flexible-server parameter {}'.format(command_group, scope)
            with self.argument_context(argument_context_string) as c:
                if scope == "list":
                    c.argument('server_name', id_part=None, options_list=['--server-name', '-s'], arg_type=server_name_arg_type)
                else:
                    c.argument('server_name', id_part='name', options_list=['--server-name', '-s'],
                               arg_type=server_name_arg_type)

        for scope in ['show', 'set']:
            argument_context_string = '{} flexible-server parameter {}'.format(command_group, scope)
            with self.argument_context(argument_context_string) as c:
                c.argument('configuration_name', id_part='child_name_1', options_list=['--name', '-n'], required=True,
                           help='The name of the server configuration')

        with self.argument_context('{} flexible-server parameter set'.format(command_group)) as c:
            c.argument('value', options_list=['--value', '-v'],
                       help='Value of the configuration.')
            c.argument('source', options_list=['--source'],
                       help='Source of the configuration.')

        # firewall-rule
        for scope in ['create', 'delete', 'list', 'show', 'update']:
            argument_context_string = '{} flexible-server firewall-rule {}'.format(command_group, scope)
            with self.argument_context(argument_context_string) as c:
                c.argument('resource_group_name', arg_type=resource_group_name_type)
                if scope == "list":
                    c.argument('server_name', id_part=None, options_list=['--name', '-n'], arg_type=server_name_arg_type)
                else:
                    c.argument('server_name', id_part='name', options_list=['--name', '-n'], arg_type=server_name_arg_type)

        for scope in ['create', 'delete', 'show', 'update']:
            argument_context_string = '{} flexible-server firewall-rule {}'.format(command_group, scope)
            with self.argument_context(argument_context_string) as c:
                c.argument('firewall_rule_name', id_part='child_name_1', options_list=['--rule-name', '-r'],
                           help='The name of the firewall rule. If name is omitted, default name will be chosen for firewall name. The firewall rule name can only contain 0-9, a-z, A-Z, \'-\' and \'_\'. Additionally, the firewall rule name cannot exceed 128 characters. ')

        with self.argument_context('{} flexible-server firewall-rule create'.format(command_group)) as c:
            c.argument('end_ip_address', options_list=['--end-ip-address'], validator=ip_address_validator,
                       help='The end IP address of the firewall rule. Must be IPv4 format. Use value \'0.0.0.0\' to represent all Azure-internal IP addresses. ')
            c.argument('start_ip_address', options_list=['--start-ip-address'], validator=ip_address_validator,
                       help='The start IP address of the firewall rule. Must be IPv4 format. Use value \'0.0.0.0\' to represent all Azure-internal IP addresses. ')

        with self.argument_context('{} flexible-server firewall-rule delete'.format(command_group)) as c:
            c.argument('yes', options_list=['--yes', '-y'], action='store_true', help='Do not prompt for confirmation.')

        with self.argument_context('{} flexible-server firewall-rule update'.format(command_group)) as c:
            c.argument('end_ip_address', options_list=['--end-ip-address'], validator=ip_address_validator,
                       help='When using \'set\' or \'add\', preserve string literals instead of attempting to convert to JSON.')
            c.argument('start_ip_address', options_list=['--start-ip-address'], validator=ip_address_validator,
                       help='The start IP address of the firewall rule. Must be IPv4 format. Use value \'0.0.0.0\' to represent all Azure-internal IP addresses. ')

        # db
        if command_group == "mysql":
            with self.argument_context('{} flexible-server db'.format(command_group)) as c:
                c.argument('server_name', options_list=['--server-name', '-s'], help='Name of the server.')
                c.argument('database_name', arg_type=database_name_arg_type, options_list=['--database-name', '-d'], help='The name of a database.')

            with self.argument_context('{} flexible-server db create'.format(command_group)) as c:
                c.argument('database_name', arg_type=database_name_setter_arg_type, options_list=['--database-name', '-d'], help='The name of a database.')

            with self.argument_context('{} flexible-server db list'.format(command_group)) as c:
                c.argument('server_name', id_part=None, options_list=['--server-name', '-s'], arg_type=server_name_arg_type)
                c.argument('database_name', id_part=None, arg_type=database_name_setter_arg_type, options_list=['--database-name', '-d'], help='The name of a database.')

            with self.argument_context('{} flexible-server db delete'.format(command_group)) as c:
                c.argument('database_name', arg_type=database_name_getter_arg_type, options_list=['--database-name', '-d'], help='The name of a database.')
                c.argument('yes', options_list=['--yes', '-y'], action='store_true', help='Do not prompt for confirmation.')

        with self.argument_context('{} flexible-server show-connection-string'.format(command_group)) as c:
            c.argument('server_name', options_list=['--server-name', '-s'], arg_type=server_name_arg_type, help='Name of the server.')
            c.argument('administrator_login', arg_type=administrator_login_arg_type, options_list=['--admin-user', '-u'],
                       help='The login username of the administrator.')
            c.argument('administrator_login_password', options_list=['--admin-password', '-p'],
                       help='The login password of the administrator.')
            c.argument('database_name', arg_type=database_name_arg_type, options_list=['--database-name', '-d'], help='The name of a database.')

        with self.argument_context('{} flexible-server replica list'.format(command_group)) as c:
            c.argument('server_name', id_part=None, options_list=['--name', '-n'], help='Name of the source server.')

        with self.argument_context('{} flexible-server replica create'.format(command_group)) as c:
            c.argument('server_name', options_list=['--source-server'],
                       help='The name or resource ID of the source server to restore from.')
            c.argument('replica_name', options_list=['--replica-name'],
                       help='The name of the server to restore to.')
            c.ignore('location')
            c.ignore('sku_name')
            c.ignore('tier')

        with self.argument_context('{} flexible-server replica stop-replication'.format(command_group)) as c:
            c.argument('server_name', options_list=['--name', '-n'], help='Name of the replica server.')

    _flexible_server_params('postgres')
    _flexible_server_params('mysql')
Example #37
0
            return None
        install_location = '{}\\{}.exe'.format(program_files, exe_name)
    elif system == 'Linux' or system == 'Darwin':
        install_location = '/usr/local/bin/{}'.format(exe_name)
    else:
        install_location = None
    return install_location


name_arg_type = CliArgumentType(options_list=('--name', '-n'), metavar='NAME')

register_cli_argument('acs', 'tags', tags_type)

register_cli_argument('acs', 'name', arg_type=name_arg_type, configured_default='acs',
                      help="ACS cluster name. You can configure the default using `az configure --defaults acs=<name>`",
                      completer=get_resource_name_completion_list('Microsoft.ContainerService/ContainerServices'))

register_cli_argument('acs', 'resource_group', arg_type=resource_group_name_type)

register_cli_argument('acs', 'orchestrator_type', options_list=('--orchestrator-type', '-t'), **enum_choice_list(ContainerServiceOchestratorTypes))
# some admin names are prohibited in acs, such as root, admin, etc. Because we have no control on the orchestrators, so default to a safe name.
register_cli_argument('acs', 'admin_username', options_list=('--admin-username',), default='azureuser', required=False)
register_cli_argument('acs', 'dns_name_prefix', options_list=('--dns-prefix', '-d'))
register_cli_argument('acs', 'container_service_name', options_list=('--name', '-n'), help='The name of the container service', completer=get_resource_name_completion_list('Microsoft.ContainerService/ContainerServices'))

register_cli_argument('acs', 'ssh_key_value', required=False, help='SSH key file value or key file path.', type=file_type, default=os.path.join('~', '.ssh', 'id_rsa.pub'), completer=FilesCompleter())
register_cli_argument('acs create', 'name', arg_type=name_arg_type, validator=validate_ssh_key)

register_extra_cli_argument('acs create', 'generate_ssh_keys', action='store_true', help='Generate SSH public and private key files if missing')
register_cli_argument('acs create', 'agent_vm_size', completer=get_vm_size_completion_list)
Example #38
0
def load_arguments_sb(self, _):
    from azure.cli.command_modules.servicebus._completers import get_queue_command_completion_list, \
        get_rules_command_completion_list, get_subscriptions_command_completion_list, get_topic_command_completion_list
    from azure.cli.command_modules.servicebus._validators import _validate_auto_delete_on_idle, \
        _validate_duplicate_detection_history_time_window, \
        _validate_default_message_time_to_live, \
        _validate_lock_duration, validate_partner_namespace, validate_premiumsku_capacity, validate_target_namespace, validate_rights

    from knack.arguments import CLIArgumentType
    from azure.mgmt.servicebus.models import SkuName, AccessRights, KeyType, FilterType
    rights_arg_type = CLIArgumentType(options_list=['--rights'], nargs='+', arg_type=get_enum_type(AccessRights), validator=validate_rights, help='Space-separated list of Authorization rule rights')
    key_arg_type = CLIArgumentType(options_list=['--key'], arg_type=get_enum_type(KeyType), help='specifies Primary or Secondary key needs to be reset')
    keyvalue_arg_type = CLIArgumentType(options_list=['--key-value'], help='Optional, if the key value provided, is set for KeyType or autogenerated Key value set for keyType.')

    with self.argument_context('servicebus') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('namespace_name', options_list=['--namespace-name'], id_part='name', help='Name of Namespace')

    with self.argument_context('servicebus namespace') as c:
        c.argument('namespace_name', id_part='name', arg_type=name_type, completer=get_resource_name_completion_list('Microsoft.ServiceBus/namespaces'), help='Name of Namespace')
        c.argument('default_action', help='Default action for network rule set.')
        c.argument('tags', arg_type=tags_type)
        c.argument('sku', arg_type=get_enum_type(SkuName), help='Namespace SKU.')
        c.argument('capacity', type=int, choices=[1, 2, 4, 8, 16], help='Number of message units. This property is only applicable to namespaces of Premium SKU', validator=validate_premiumsku_capacity)
        c.argument('mi_system_assigned', arg_group='Managed Identity',
                   arg_type=get_three_state_flag(),
                   help='Enable System Assigned Identity')
        c.argument('mi_user_assigned', arg_group='Managed Identity', nargs='+', help='List of User Assigned Identity ids.')
        c.argument('encryption_config', action=AlertAddEncryption, nargs='+',
                   help='List of KeyVaultProperties objects.')

    with self.argument_context('servicebus namespace exists') as c:
        c.argument('name', arg_type=name_type, help='Namespace name. Name can contain only letters, numbers, and hyphens. The namespace must start with a letter, and it must end with a letter or number.')

    with self.argument_context('servicebus namespace create') as c:
        c.argument('location', arg_type=get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)

    # region Namespace Authorization Rule
    with self.argument_context('servicebus namespace authorization-rule list') as c:
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of the Namespace')

    with self.argument_context('servicebus namespace authorization-rule') as c:
        c.argument('authorization_rule_name', arg_type=name_type, id_part='child_name_1', help='Name of Namespace Authorization Rule')
        c.argument('namespace_name', id_part='name', options_list=['--namespace-name'], help='Name of Namespace')

    for scope in ['servicebus namespace authorization-rule create', 'servicebus namespace authorization-rule update', 'servicebus queue authorization-rule create', 'servicebus queue authorization-rule update', 'servicebus topic authorization-rule create', 'servicebus topic authorization-rule update']:
        with self.argument_context(scope) as c:
            c.argument('name', arg_type=name_type, help='Name of Authorization Rule')
            c.argument('rights', arg_type=rights_arg_type)

    with self.argument_context('servicebus namespace authorization-rule keys renew') as c:
        c.argument('name', arg_type=name_type, help='Name of Namespace Authorization Rule')
        c.argument('key_type', arg_type=key_arg_type)
        c.argument('key', arg_type=keyvalue_arg_type)

    with self.argument_context('servicebus namespace authorization-rule keys list') as c:
        c.argument('authorization_rule_name', arg_type=name_type, id_part=None, help='Name of Namespace Authorization Rule')
        c.argument('namespace_name', id_part=None, options_list=['--namespace-name'], help='Name of Namespace')

    # region Queue
    with self.argument_context('servicebus queue') as c:
        c.argument('queue_name', arg_type=name_type, id_part='child_name_1', completer=get_queue_command_completion_list, help='Name of Queue')

    # region - Queue Create
    for scope in ['create', 'update']:
        with self.argument_context('servicebus queue {}'.format(scope)) as c:
            c.argument('queue_name', arg_type=name_type, id_part='child_name_1', help='Name of Queue')
            c.argument('lock_duration', validator=_validate_lock_duration, help='String ISO 8601 timespan or duration format for duration of a peek-lock; that is, the amount of time that the message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1 minute.')
            c.argument('max_size_in_megabytes', options_list=['--max-size'], type=int, choices=[1024, 2048, 3072, 4096, 5120, 10240, 20480, 40960, 81920], help='Maximum size of queue in megabytes, which is the size of the memory allocated for the queue. Default is 1024. Max for Standard SKU is 5120 and for Premium SKU is 81920')
            c.argument('requires_duplicate_detection', options_list=['--enable-duplicate-detection'], arg_type=get_three_state_flag(), help='A boolean value indicating if this queue requires duplicate detection.')
            c.argument('requires_session', options_list=['--enable-session'], arg_type=get_three_state_flag(), help='A boolean value indicating whether the queue supports the concept of sessions.')
            c.argument('default_message_time_to_live', validator=_validate_default_message_time_to_live, help='ISO 8601 timespan or duration time format for default message to live value. This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself.')
            c.argument('dead_lettering_on_message_expiration', options_list=['--enable-dead-lettering-on-message-expiration'], arg_type=get_three_state_flag(), help='A boolean value that indicates whether this queue has dead letter support when a message expires.')
            c.argument('duplicate_detection_history_time_window', validator=_validate_duplicate_detection_history_time_window, help='ISO 8601 timeSpan structure that defines the duration of the duplicate detection history. The default value is 10 minutes.')
            c.argument('max_delivery_count', type=int, help='The maximum delivery count. A message is automatically deadlettered after this number of deliveries. default value is 10.')
            c.argument('status', arg_type=get_enum_type(['Active', 'Disabled', 'SendDisabled']), help='Enumerates the possible values for the status of a messaging entity.')
            c.argument('auto_delete_on_idle', validator=_validate_auto_delete_on_idle, help='ISO 8601 timeSpan or duration time format for idle interval after which the queue is automatically deleted. The minimum duration is 5 minutes.')
            c.argument('enable_partitioning', arg_type=get_three_state_flag(), help='A boolean value that indicates whether the queue is to be partitioned across multiple message brokers.')
            c.argument('enable_express', arg_type=get_three_state_flag(), help='A boolean value that indicates whether Express Entities are enabled. An express queue holds a message in memory temporarily before writing it to persistent storage.')
            c.argument('forward_to', help='Queue/Topic name to forward the messages')
            c.argument('forward_dead_lettered_messages_to', help='Queue/Topic name to forward the Dead Letter message')
            c.argument('enable_batched_operations', arg_type=get_three_state_flag(), help='Allow server-side batched operations.')

    with self.argument_context('servicebus queue list') as c:
        c.argument('namespace_name', id_part=None, options_list=['--namespace-name'], help='Name of Namespace')

    # region Queue Authorization Rule
    with self.argument_context('servicebus queue authorization-rule') as c:
        c.argument('authorization_rule_name', arg_type=name_type, id_part='child_name_2', help='Name of Queue Authorization Rule')
        c.argument('queue_name', id_part='child_name_1', options_list=['--queue-name'], help='Name of Queue')

    with self.argument_context('servicebus queue authorization-rule list') as c:
        c.argument('namespace_name', id_part=None, options_list=['--namespace-name'], help='Name of Namespace')
        c.argument('queue_name', id_part=None, options_list=['--queue-name'], help='Name of Queue')

    with self.argument_context('servicebus queue authorization-rule keys renew') as c:
        c.argument('name', arg_type=name_type, help='Name of Queue Authorization Rule')
        c.argument('key_type', arg_type=key_arg_type)
        c.argument('key', arg_type=keyvalue_arg_type)

    with self.argument_context('servicebus queue authorization-rule keys list') as c:
        c.argument('authorization_rule_name', arg_type=name_type, id_part=None, help='Name of Queue Authorization Rule')
        c.argument('queue_name', id_part=None, options_list=['--queue-name'], help='Name of Queue')
        c.argument('namespace_name', id_part=None, options_list=['--namespace-name'], help='Name of Namespace')

    # region - Topic
    for scope in ['servicebus topic show', 'servicebus topic delete']:
        with self.argument_context(scope) as c:
            c.argument('topic_name', arg_type=name_type, id_part='child_name_1', completer=get_topic_command_completion_list, help='Name of Topic')

    # region - Topic Create
    for scope in ['create', 'update']:
        with self.argument_context('servicebus topic {}'.format(scope)) as c:
            c.argument('topic_name', arg_type=name_type, id_part='child_name_1', completer=get_topic_command_completion_list, help='Name of Topic')
            c.argument('default_message_time_to_live', validator=_validate_default_message_time_to_live, help='ISO 8601 or duration time format for Default message timespan to live value. This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself.')
            c.argument('max_size_in_megabytes', options_list=['--max-size'], type=int, choices=[1024, 2048, 3072, 4096, 5120, 10240, 20480, 40960, 81920], help='Maximum size of topic in megabytes, which is the size of the memory allocated for the topic. Default is 1024. Max for Standard SKU is 5120 and for Premium SKU is 81920')
            c.argument('requires_duplicate_detection', options_list=['--enable-duplicate-detection'], arg_type=get_three_state_flag(), help='A boolean value indicating if this topic requires duplicate detection.')
            c.argument('duplicate_detection_history_time_window', validator=_validate_duplicate_detection_history_time_window, help='ISO 8601 timespan or duration time format for structure that defines the duration of the duplicate detection history. The default value is 10 minutes.')
            c.argument('enable_batched_operations', arg_type=get_three_state_flag(), help='Allow server-side batched operations.')
            c.argument('status', arg_type=get_enum_type(['Active', 'Disabled', 'SendDisabled']), help='Enumerates the possible values for the status of a messaging entity.')
            c.argument('support_ordering', options_list=['--enable-ordering'], arg_type=get_three_state_flag(), help='A boolean value that indicates whether the topic supports ordering.')
            c.argument('auto_delete_on_idle', validator=_validate_auto_delete_on_idle, help='ISO 8601 timespan or duration time format for idle interval after which the topic is automatically deleted. The minimum duration is 5 minutes.')
            c.argument('enable_partitioning', arg_type=get_three_state_flag(), help='A boolean value that indicates whether the topic to be partitioned across multiple message brokers is enabled.')
            c.argument('enable_express', arg_type=get_three_state_flag(), help='A boolean value that indicates whether Express Entities are enabled. An express topic holds a message in memory temporarily before writing it to persistent storage.')

    for scope in ['servicebus topic show', 'servicebus topic delete']:
        with self.argument_context(scope) as c:
            c.argument('topic_name', arg_type=name_type, id_part='child_name_1', completer=get_topic_command_completion_list, help='Name of Topic')

    with self.argument_context('servicebus topic list') as c:
        c.argument('namespace_name', id_part=None, options_list=['--namespace-name'], help='Name of Namespace')

    # region Topic Authorization Rule
    with self.argument_context('servicebus topic authorization-rule') as c:
        c.argument('authorization_rule_name', arg_type=name_type, id_part='child_name_2', help='name of Topic Authorization Rule')
        c.argument('topic_name', options_list=['--topic-name'], id_part='child_name_1', help='name of Topic')

    with self.argument_context('servicebus topic authorization-rule list') as c:
        c.argument('namespace_name', id_part=None, options_list=['--namespace-name'], help='Name of Namespace')
        c.argument('topic_name', options_list=['--topic-name'], id_part=None, help='name of Topic')

    with self.argument_context('servicebus topic authorization-rule keys renew') as c:
        c.argument('name', arg_type=name_type, help='Name of Topic Authorization Rule')
        c.argument('key_type', arg_type=key_arg_type)
        c.argument('key', arg_type=keyvalue_arg_type)

    with self.argument_context('servicebus topic authorization-rule keys list') as c:
        c.argument('namespace_name', id_part=None, options_list=['--namespace-name'], help='Name of Namespace')
        c.argument('authorization_rule_name', arg_type=name_type, id_part=None, help='name of Topic Authorization Rule')
        c.argument('topic_name', options_list=['--topic-name'], id_part=None, help='Name of Topic')

    with self.argument_context('servicebus topic subscription') as c:
        c.argument('subscription_name', arg_type=name_type, id_part='child_name_2', completer=get_subscriptions_command_completion_list, help='Name of Subscription')
        c.argument('topic_name', id_part='child_name_1', options_list=['--topic-name'], help='Name of Topic')

    # region - Subscription Create and update
    for scope in ['create', 'update']:
        with self.argument_context('servicebus topic subscription {}'.format(scope)) as c:
            c.argument('lock_duration', validator=_validate_lock_duration, help='ISO 8601 or duration format (day:minute:seconds) for lock duration timespan for the subscription. The default value is 1 minute.')
            c.argument('requires_session', options_list=['--enable-session'], arg_type=get_three_state_flag(), help='A boolean value indicating if a subscription supports the concept of sessions.')
            c.argument('default_message_time_to_live', validator=_validate_default_message_time_to_live, help='ISO 8601 or duration time format for Default message timespan to live value. This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself.')
            c.argument('dead_lettering_on_message_expiration', options_list=['--enable-dead-lettering-on-message-expiration'], arg_type=get_three_state_flag(), help='A boolean Value that indicates whether a subscription has dead letter support when a message expires.')
            c.argument('max_delivery_count', type=int, help='Number of maximum deliveries.')
            c.argument('status', arg_type=get_enum_type(['Active', 'Disabled', 'SendDisabled', 'ReceiveDisabled']), help='Enumerates the possible values for the status of a messaging entity.')
            c.argument('enable_batched_operations', arg_type=get_three_state_flag(), help='Allow server-side batched operations.')
            c.argument('auto_delete_on_idle', validator=_validate_auto_delete_on_idle, options_list=['--auto-delete-on-idle'], help='ISO 8601 timeSpan  or duration time format for idle interval after which the topic is automatically deleted. The minimum duration is 5 minutes.')
            c.argument('forward_to', help='Queue/Topic name to forward the messages')
            c.argument('forward_dead_lettered_messages_to', help='Queue/Topic name to forward the Dead Letter message')
            c.argument('dead_lettering_on_filter_evaluation_exceptions', options_list=['--dead-letter-on-filter-exceptions'], arg_type=get_three_state_flag(), help='Allow dead lettering when filter evaluation exceptions occur.')

    with self.argument_context('servicebus topic subscription list') as c:
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of Namespace')
        c.argument('topic_name', options_list=['--topic-name'], id_part=None, help='Name of Topic')

    # Region Subscription Rules
    # Region Rules Create

    with self.argument_context('servicebus topic subscription rule') as c:
        c.argument('rule_name', arg_type=name_type, id_part='child_name_3', completer=get_rules_command_completion_list, help='Name of Rule')
        c.argument('subscription_name', options_list=['--subscription-name'], id_part='child_name_2', help='Name of Subscription')
        c.argument('topic_name', options_list=['--topic-name'], id_part='child_name_1', help='Name of Topic')

    for scope in ['servicebus topic subscription rule create', 'servicebus topic subscription rule update']:
        with self.argument_context(scope, arg_group='Action') as c:
            c.argument('filter_type', arg_type=get_enum_type(FilterType), help='Rule Filter types')
            c.argument('action_sql_expression', help='Action SQL expression.')
            c.argument('action_compatibility_level', type=int, help='This property is reserved for future use. An integer value showing the compatibility level, currently hard-coded to 20.')
            c.argument('action_requires_preprocessing', options_list=['--enable-action-preprocessing'], arg_type=get_three_state_flag(), help='A boolean value that indicates whether the rule action requires preprocessing.')
        with self.argument_context(scope, arg_group='SQL Filter') as c:
            c.argument('filter_sql_expression', help='SQL expression. e.g. myproperty=test')
            c.argument('filter_requires_preprocessing', options_list=['--enable-sql-preprocessing'], arg_type=get_three_state_flag(), help='A boolean value that indicates whether the rule action requires preprocessing.')
        with self.argument_context(scope, arg_group='Correlation Filter') as c:
            c.argument('correlation_id', help='Identifier of correlation.')
            c.argument('message_id', help='Identifier of message.')
            c.argument('to', help='Address to send to.')
            c.argument('reply_to', help='Address of the queue to reply to.')
            c.argument('label', help='Application specific label.')
            c.argument('session_id', help='Session identifier')
            c.argument('reply_to_session_id', help='Session identifier to reply to.')
            c.argument('content_type', help='Content type of message.')
            c.argument('requires_preprocessing', options_list=['--enable-correlation-preprocessing'], arg_type=get_three_state_flag(), help='A boolean value that indicates whether the rule action requires preprocessing.')

    with self.argument_context('servicebus topic subscription rule list') as c:
        c.argument('subscription_name', options_list=['--subscription-name'], id_part=None, help='Name of Subscription')
        c.argument('topic_name', options_list=['--topic-name'], id_part=None, help='Name of Topic')
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of Namespace')

    # Geo DR - Disaster Recovery Configs - Alias  : Region
    with self.argument_context('servicebus georecovery-alias exists') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('namespace_name', options_list=['--namespace-name'], id_part='name', help='Name of Namespace')
        c.argument('name', options_list=['--alias', '-a'], arg_type=name_type, help='Name of Geo-Disaster Recovery Configuration Alias to check availability')

    with self.argument_context('servicebus georecovery-alias') as c:
        c.argument('alias', options_list=['--alias', '-a'], id_part='child_name_1', help='Name of the Geo-Disaster Recovery Configuration Alias')

    with self.argument_context('servicebus georecovery-alias set') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('namespace_name', options_list=['--namespace-name'], id_part='name', help='Name of Namespace')
        c.argument('alias', options_list=['--alias', '-a'], help='Name of the Geo-Disaster Recovery Configuration Alias')
        c.argument('partner_namespace', required=True, options_list=['--partner-namespace'], validator=validate_partner_namespace, help='Name (if within the same resource group) or ARM Id of Primary/Secondary Service Bus  namespace name, which is part of GEO DR pairing')
        c.argument('alternate_name', help='Alternate Name (Post failover) for Primary Namespace, when Namespace name and Alias name are same')

    for scope in ['servicebus georecovery-alias authorization-rule show', 'servicebus georecovery-alias authorization-rule keys list']:
        with self.argument_context(scope)as c:
            c.argument('authorization_rule_name', arg_type=name_type, id_part='child_name_2', help='name of Namespace Authorization Rule')

    with self.argument_context('servicebus georecovery-alias list') as c:
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of Namespace')

    with self.argument_context('servicebus georecovery-alias authorization-rule list') as c:
        c.argument('alias', options_list=['--alias', '-a'], help='Name of Geo-Disaster Recovery Configuration Alias')
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of Namespace')

    with self.argument_context('servicebus georecovery-alias authorization-rule keys list') as c:
        c.argument('alias', options_list=['--alias', '-a'], id_part=None, help='Name of Geo-Disaster Recovery Configuration Alias')
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of Namespace')
        c.argument('authorization_rule_name', arg_type=name_type, help='Name of Namespace AuthorizationRule')

    # Standard to Premium Migration: Region

    with self.argument_context('servicebus migration start') as c:
        c.ignore('config_name')
        c.argument('namespace_name', arg_type=name_type, help='Name of Standard Namespace used as source of the migration')
        # c.argument('config_name', options_list=['--config-name'], id_part=None, help='Name of configuration. Should always be "$default"')
        c.argument('target_namespace', options_list=['--target-namespace'], validator=validate_target_namespace, help='Name (if within the same resource group) or ARM Id of empty Premium Service Bus namespace name that will be target of the migration')
        c.argument('post_migration_name', options_list=['--post-migration-name'], help='Post migration name is the name that can be used to connect to standard namespace after migration is complete.')

    for scope in ['show', 'complete', 'abort']:
        with self.argument_context('servicebus migration {}'.format(scope)) as c:
            c.ignore('config_name')
            c.argument('namespace_name', arg_type=name_type, help='Name of Standard Namespace')

# Region Namespace NetworkRuleSet
    with self.argument_context('servicebus namespace network-rule') as c:
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of the Namespace')

    for scope in ['servicebus namespace network-rule add', 'servicebus namespace network-rule remove']:
        with self.argument_context(scope) as c:
            c.argument('subnet', arg_group='Virtual Network Rule', options_list=['--subnet'], help='Name or ID of subnet. If name is supplied, `--vnet-name` must be supplied.')
            c.argument('ip_mask', arg_group='IP Address Rule', options_list=['--ip-address'], help='IPv4 address or CIDR range.')
            c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of the Namespace')
            c.extra('vnet_name', arg_group='Virtual Network Rule', options_list=['--vnet-name'], help='Name of the Virtual Network')

    with self.argument_context('servicebus namespace network-rule add') as c:
        c.argument('ignore_missing_vnet_service_endpoint', arg_group='Virtual Network Rule', options_list=['--ignore-missing-endpoint'], arg_type=get_three_state_flag(), help='A boolean value that indicates whether to ignore missing vnet Service Endpoint')
        c.argument('action', arg_group='IP Address Rule', options_list=['--action'], arg_type=get_enum_type(['Allow']), help='Action of the IP rule')

# Identity
    with self.argument_context('servicebus namespace identity',
                               resource_type=ResourceType.MGMT_SERVICEBUS) as c:
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of the Namespace')

    for scope in ['servicebus namespace identity assign', 'servicebus namespace identity remove']:
        with self.argument_context(scope, resource_type=ResourceType.MGMT_SERVICEBUS) as c:
            c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of the Namespace')
            c.argument('system_assigned', arg_type=get_three_state_flag(), help='System Assigned Identity')
            c.argument('user_assigned', nargs='+', help='User Assigned Identity')

# Encryption
    with self.argument_context('servicebus namespace encryption', resource_type=ResourceType.MGMT_SERVICEBUS) as c:
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of the Namespace')

    for scope in ['servicebus namespace encryption add', 'servicebus namespace identity remove']:
        with self.argument_context(scope, resource_type=ResourceType.MGMT_SERVICEBUS) as c:
            c.argument('encryption_config', action=AlertAddEncryption, nargs='+', help='List of KeyVaultProperties objects.')
Example #39
0
def load_arguments(self, _):
    # ARGUMENT DEFINITIONS
    datalake_store_name_type = CLIArgumentType(help='Name of the Data Lake Store account.', options_list=['--account_name'], completer=get_resource_name_completion_list('Microsoft.DataLakeStore/accounts'), id_part='name')

    # PARAMETER REGISTRATIONS
    # global
    with self.argument_context('dls') as c:
        c.argument('account_name', datalake_store_name_type, options_list=['--account', '-n'])
        c.argument('top', help='Maximum number of items to return.', type=int)
        c.argument('skip', help='The number of items to skip over before returning elements.', type=int)
        c.argument('count', help='The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true.', type=bool)

    # global account
    with self.argument_context('dls account') as c:
        c.argument('tags', tags_type)
        c.argument('resource_group_name', resource_group_name_type, id_part=None, required=False, help='If not specified, will attempt to discover the resource group for the specified Data Lake Store account.', validator=validate_resource_group_name)
        c.argument('tier', arg_type=get_enum_type(TierType), help='The desired commitment tier for this account to use.')

    # account
    for scope in ['dls account show', 'dls account delete']:
        with self.argument_context(scope) as c:
            c.argument('name', datalake_store_name_type, options_list=['--account', '-n'])

    with self.argument_context('dls account create') as c:
        c.argument('resource_group_name', resource_group_name_type, validator=None)
        c.argument('account_name', datalake_store_name_type, options_list=['--account', '-n'], completer=None)
        c.argument('encryption_type', arg_type=get_enum_type(EncryptionConfigType), help='Indicates what type of encryption to provision the account with. By default, encryption is ServiceManaged. If no encryption is desired, it must be explicitly set with the --disable-encryption flag.')
        c.argument('disable_encryption', help='Indicates that the account will not have any form of encryption applied to it.', action='store_true')

    with self.argument_context('dls account update') as c:
        c.argument('trusted_id_provider_state', arg_type=get_enum_type(TrustedIdProviderState), help='Enable/disable the existing trusted ID providers.')
        c.argument('firewall_state', arg_type=get_enum_type(FirewallState), help='Enable/disable existing firewall rules.')
        c.argument('allow_azure_ips', arg_type=get_enum_type(FirewallAllowAzureIpsState), help='Allow/block Azure originating IPs through the firewall')

    with self.argument_context('dls account list') as c:
        c.argument('resource_group_name', resource_group_name_type, validator=None)

    # filesystem
    with self.argument_context('dls fs') as c:
        c.argument('path', help='The path in the specified Data Lake Store account where the action should take place. In the format \'/folder/file.txt\', where the first \'/\' after the DNS indicates the root of the file system.')

    with self.argument_context('dls fs create') as c:
        c.argument('force', help='Indicates that, if the file or folder exists, it should be overwritten', action='store_true')
        c.argument('folder', help='Indicates that this new item is a folder and not a file.', action='store_true')

    with self.argument_context('dls fs delete') as c:
        c.argument('recurse', help='Indicates this should be a recursive delete of the folder.', action='store_true')

    with self.argument_context('dls fs upload') as c:
        c.argument('overwrite', help='Indicates that, if the destination file or folder exists, it should be overwritten', action='store_true')
        c.argument('thread_count', help='Specify the parallelism of the upload. Default is the number of cores in the local machine.', type=int)
        c.argument('chunk_size', help='Number of bytes for a chunk. Large files are split into chunks. Files smaller than this number will always be transferred in a single thread.', type=int, default=268435456, required=False)
        c.argument('buffer_size', help='Number of bytes for internal buffer. This block cannot be bigger than a chunk and cannot be smaller than a block.', type=int, default=4194304, required=False)
        c.argument('block_size', help='Number of bytes for a block. Within each chunk, we write a smaller block for each API call. This block cannot be bigger than a chunk. ', type=int, default=4194304, required=False)

    with self.argument_context('dls fs download') as c:
        c.argument('overwrite', help='Indicates that, if the destination file or folder exists, it should be overwritten', action='store_true')
        c.argument('thread_count', help='Specify the parallelism of the download. Default is the number of cores in the local machine.', type=int)
        c.argument('chunk_size', help='Number of bytes for a chunk. Large files are split into chunks. Files smaller than this number will always be transferred in a single thread.', type=int, default=268435456, required=False)
        c.argument('buffer_size', help='Number of bytes for internal buffer. This block cannot be bigger than a chunk and cannot be smaller than a block.', type=int, default=4194304, required=False)
        c.argument('block_size', help='Number of bytes for a block. Within each chunk, we write a smaller block for each API call. This block cannot be bigger than a chunk.', type=int, default=4194304, required=False)

    with self.argument_context('dls fs preview') as c:
        c.argument('force', help='Indicates that, if the preview is larger than 1MB, still retrieve it. This can potentially be very slow, depending on how large the file is.', action='store_true')

    with self.argument_context('dls fs join') as c:
        c.argument('force', help='Indicates that, if the destination file already exists, it should be overwritten', action='store_true')
        c.argument('source_paths', help='The list of files in the specified Data Lake Store account to join.', nargs='+')

    with self.argument_context('dls fs move') as c:
        c.argument('force', help='Indicates that, if the destination file or folder already exists, it should be overwritten and replaced with the file or folder being moved.', action='store_true')

    with self.argument_context('dls fs set-expiry') as c:
        c.argument('expiration_time', help='The absolute value of the expiration time expressed as milliseconds since the epoch.')

    # filesystem access params
    with self.argument_context('dls fs access') as c:
        c.argument('acl_spec', help=" The ACL specification to set on the path in the format '[default:]user|group|other:[entity id or UPN]:r|-w|-x|-,[default:]user|group|other:[entity id or UPN]:r|-w|-x|-,...'.")

    with self.argument_context('dls fs access set-permission') as c:
        c.argument('permission', help='The octal representation of the permissions for user, group and mask (for example: 777 is full rwx for all entities)', type=int)

    with self.argument_context('dls fs access remove-all') as c:
        c.argument('default_acl', help='A switch that, if specified, indicates that the remove ACL operation should remove the default ACL of the folder. Otherwise the regular ACL is removed.', action='store_true')
Example #40
0
def load_arguments(self, _):

    acr_arg_type = CLIArgumentType(metavar='ACR_NAME_OR_RESOURCE_ID')

    # ACS command argument configuration
    with self.argument_context('acs') as c:
        c.argument(
            'resource_name',
            name_type,
            completer=get_resource_name_completion_list(
                'Microsoft.ContainerService/ContainerServices'),
            help=
            'Name of the container service. You can configure the default using `az configure --defaults acs=<name>`'
        )
        c.argument(
            'name',
            name_type,
            completer=get_resource_name_completion_list(
                'Microsoft.ContainerService/ContainerServices'),
            help=
            'Name of the container service. You can configure the default using `az configure --defaults acs=<name>`'
        )
        c.argument(
            'container_service_name',
            name_type,
            help=
            'Name of the container service. You can configure the default using `az configure --defaults acs=<name>`',
            completer=get_resource_name_completion_list(
                'Microsoft.ContainerService/ContainerServices'))
        c.argument('admin_username',
                   options_list=['--admin-username', '-u'],
                   default='azureuser')
        c.argument(
            'api_version',
            help=_get_feature_in_preview_message() +
            'Use API version of ACS to perform az acs operations. Available options: 2017-01-31, 2017-07-01. Default: the latest version for the location'
        )
        c.argument('dns_name_prefix', options_list=['--dns-prefix', '-d'])
        c.argument('orchestrator_type',
                   get_enum_type(orchestrator_types),
                   options_list=['--orchestrator-type', '-t'])
        c.argument('ssh_key_value',
                   required=False,
                   type=file_type,
                   default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(),
                   validator=validate_ssh_key)
        c.argument('tags', tags_type)
        c.argument(
            'disable_browser',
            help=
            'Do not open browser after opening a proxy to the cluster web user interface'
        )

    with self.argument_context('acs create') as c:
        c.argument('ssh_key_value',
                   required=False,
                   type=file_type,
                   default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(),
                   validator=validate_ssh_key)
        c.argument(
            'master_profile',
            options_list=['--master-profile', '-m'],
            type=validate_file_or_dict,
            help=_get_feature_in_preview_message() +
            'The file or dictionary representation of the master profile. Note it will override any master settings once set'
        )
        c.argument('master_vm_size',
                   completer=get_vm_size_completion_list,
                   help=_get_feature_in_preview_message())
        c.argument('agent_count', type=int)
        c.argument('generate_ssh_keys',
                   action='store_true',
                   validator=validate_create_parameters,
                   help='Generate SSH public and private key files if missing')
        c.argument(
            'master_osdisk_size',
            type=int,
            help=_get_feature_in_preview_message() +
            'The disk size for master pool vms. Unit in GB. Default: corresponding vmsize disk size'
        )
        c.argument(
            'master_vnet_subnet_id',
            type=str,
            help=_get_feature_in_preview_message() +
            'The custom vnet subnet id. Note agent need to used the same vnet if master set. Default: ""'
        )
        c.argument('master_first_consecutive_static_ip',
                   type=str,
                   help=_get_feature_in_preview_message() +
                   'The first consecutive ip used to specify static ip block.')
        c.argument('master_storage_profile',
                   get_enum_type(storage_profile_types),
                   help=_get_feature_in_preview_message() +
                   'Default: varies based on Orchestrator')
        c.argument(
            'agent_profiles',
            options_list=['--agent-profiles', '-a'],
            type=validate_file_or_dict,
            help=_get_feature_in_preview_message() +
            'The file or dictionary representation of the agent profiles. Note it will override any agent settings once set'
        )
        c.argument('agent_vm_size',
                   completer=get_vm_size_completion_list,
                   help='Set the default size for agent pools vms.')
        c.argument(
            'agent_osdisk_size',
            type=int,
            help=_get_feature_in_preview_message() +
            'Set the default disk size for agent pools vms. Unit in GB. Default: corresponding vmsize disk size'
        )
        c.argument(
            'agent_vnet_subnet_id',
            type=str,
            help=_get_feature_in_preview_message() +
            'Set the default custom vnet subnet id for agent pools. Note agent need to used the same vnet if master set. Default: ""'
        )
        c.argument(
            'agent_ports',
            type=validate_list_of_integers,
            help=_get_feature_in_preview_message() +
            'Set the default ports exposed on the agent pools. Only usable for non-Kubernetes. Default: 8080,4000,80'
        )
        c.argument(
            'agent_storage_profile',
            get_enum_type(storage_profile_types),
            help=_get_feature_in_preview_message() +
            'Set default storage profile for agent pools. Default: varies based on Orchestrator'
        )
        c.argument(
            'windows',
            action='store_true',
            help='If true, set the default osType of agent pools to be Windows.'
        )
        c.argument(
            'validate',
            action='store_true',
            help=
            'Generate and validate the ARM template without creating any resources'
        )
        c.argument(
            'orchestrator_version',
            help=_get_feature_in_preview_message() +
            'Use Orchestrator Version to specify the semantic version for your choice of orchestrator.'
        )

    with self.argument_context('acs scale') as c:
        c.argument('new_agent_count', type=int)

    for scope in ['dcos', 'kubernetes']:
        with self.argument_context('acs {} browse'.format(scope)) as c:
            c.argument('ssh_key_file',
                       required=False,
                       type=file_type,
                       default=os.path.join('~', '.ssh', 'id_rsa'),
                       completer=FilesCompleter(),
                       help='Path to an SSH key file to use.')

    with self.argument_context('acs dcos install-cli') as c:
        c.argument('install_location',
                   default=_get_default_install_location('dcos'))

    with self.argument_context('acs kubernetes get-credentials') as c:
        c.argument('path', options_list=['--file', '-f'])
        c.argument('overwrite_existing',
                   action='store_true',
                   help='If specified, overwrite any existing credentials.')

    with self.argument_context('acs kubernetes install-cli') as c:
        c.argument('install_location',
                   type=file_type,
                   completer=FilesCompleter(),
                   default=_get_default_install_location('kubectl'))
        c.argument('ssh_key_file',
                   required=False,
                   type=file_type,
                   default=os.path.join('~', '.ssh', 'id_rsa'),
                   completer=FilesCompleter(),
                   help='Path to an SSH key file to use.')

    # AKS command argument configuration
    with self.argument_context(
            'aks',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='managed_clusters') as c:
        c.argument('resource_name',
                   name_type,
                   help='Name of the managed cluster.',
                   completer=get_resource_name_completion_list(
                       'Microsoft.ContainerService/ManagedClusters'))
        c.argument('name',
                   name_type,
                   help='Name of the managed cluster.',
                   completer=get_resource_name_completion_list(
                       'Microsoft.ContainerService/ManagedClusters'))
        c.argument('kubernetes_version',
                   options_list=['--kubernetes-version', '-k'],
                   validator=validate_k8s_version)
        c.argument('node_count', options_list=['--node-count', '-c'], type=int)
        c.argument('tags', tags_type)

    with self.argument_context(
            'aks create',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='managed_clusters') as c:
        c.argument('name', validator=validate_linux_host_name)
        c.argument('kubernetes_version',
                   completer=get_k8s_versions_completion_list)
        c.argument('admin_username',
                   options_list=['--admin-username', '-u'],
                   default='azureuser')
        c.argument('dns_name_prefix', options_list=['--dns-name-prefix', '-p'])
        c.argument('generate_ssh_keys',
                   action='store_true',
                   validator=validate_create_parameters)
        c.argument('node_vm_size',
                   options_list=['--node-vm-size', '-s'],
                   completer=get_vm_size_completion_list)
        c.argument('nodepool_name',
                   type=str,
                   default='nodepool1',
                   help='Node pool name, up to 12 alphanumeric characters',
                   validator=validate_nodepool_name)
        c.argument('os_sku', completer=get_ossku_completion_list)
        c.argument('ssh_key_value',
                   required=False,
                   type=file_type,
                   default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(),
                   validator=validate_ssh_key)
        c.argument('aad_client_app_id')
        c.argument('aad_server_app_id')
        c.argument('aad_server_app_secret')
        c.argument('aad_tenant_id')
        c.argument('dns_service_ip')
        c.argument('docker_bridge_address')
        c.argument('edge_zone', edge_zone_type)
        c.argument('load_balancer_sku',
                   type=str,
                   validator=validate_load_balancer_sku)
        c.argument('load_balancer_managed_outbound_ip_count', type=int)
        c.argument('load_balancer_outbound_ips',
                   type=str,
                   validator=validate_load_balancer_outbound_ips)
        c.argument('load_balancer_outbound_ip_prefixes',
                   type=str,
                   validator=validate_load_balancer_outbound_ip_prefixes)
        c.argument('load_balancer_outbound_ports',
                   type=int,
                   validator=validate_load_balancer_outbound_ports)
        c.argument('load_balancer_idle_timeout',
                   type=int,
                   validator=validate_load_balancer_idle_timeout)
        c.argument('outbound_type', arg_type=get_enum_type(outbound_types))
        c.argument('auto_upgrade_channel',
                   arg_type=get_enum_type(auto_upgrade_channels))
        c.argument('enable_cluster_autoscaler', action='store_true')
        c.argument(
            'cluster_autoscaler_profile',
            nargs='+',
            options_list=["--cluster-autoscaler-profile", "--ca-profile"],
            help=
            "Space-separated list of key=value pairs for configuring cluster autoscaler. Pass an empty string to clear the profile."
        )
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('vm_set_type', type=str, validator=validate_vm_set_type)
        c.argument(
            'zones',
            zones_type,
            options_list=['--zones', '-z'],
            help=
            'Space-separated list of availability zones where agent nodes will be placed.'
        )
        c.argument('uptime_sla', action='store_true')
        c.argument('enable_addons', options_list=['--enable-addons', '-a'])
        c.argument('disable_rbac', action='store_true')
        c.argument('enable_rbac',
                   action='store_true',
                   options_list=['--enable-rbac', '-r'],
                   deprecate_info=c.deprecate(redirect="--disable-rbac",
                                              hide="2.0.45"))
        c.argument('max_pods', type=int, options_list=['--max-pods', '-m'])
        c.argument('network_plugin', arg_type=get_enum_type(network_plugins))
        c.argument('network_policy')
        c.argument('no_ssh_key', options_list=['--no-ssh-key', '-x'])
        c.argument('pod_cidr')
        c.argument('service_cidr')
        c.argument('ppg', type=str, validator=validate_ppg)
        c.argument('vnet_subnet_id',
                   type=str,
                   validator=validate_vnet_subnet_id)
        c.argument('workspace_resource_id')
        c.argument('skip_subnet_role_assignment', action='store_true')
        c.argument('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)
        c.argument('attach_acr', acr_arg_type)
        c.argument('enable_private_cluster', action='store_true')
        c.argument('private_dns_zone')
        c.argument('fqdn_subdomain')
        c.argument('disable_public_fqdn', action='store_true')
        c.argument(
            'nodepool_tags',
            nargs='*',
            validator=validate_nodepool_tags,
            help=
            'space-separated tags: key[=value] [key[=value] ...]. Use "" to clear existing tags.'
        )
        c.argument('enable_managed_identity', action='store_true')
        c.argument('assign_identity',
                   type=str,
                   validator=validate_assign_identity)
        c.argument(
            'nodepool_labels',
            nargs='*',
            validator=validate_nodepool_labels,
            help=
            'space-separated labels: key[=value] [key[=value] ...]. See https://aka.ms/node-labels for syntax of labels.'
        )
        c.argument('enable_node_public_ip', action='store_true')
        c.argument('node_public_ip_prefix_id', type=str)
        c.argument('windows_admin_username',
                   options_list=['--windows-admin-username'])
        c.argument('windows_admin_password',
                   options_list=['--windows-admin-password'])
        c.argument('enable_ahub',
                   options_list=['--enable-ahub'],
                   action='store_true')
        c.argument('node_osdisk_diskencryptionset_id',
                   type=str,
                   options_list=['--node-osdisk-diskencryptionset-id', '-d'])
        c.argument('aci_subnet_name')
        c.argument('enable_encryption_at_host',
                   options_list=['--enable-encryption-at-host'],
                   action='store_true')
        c.argument('enable_ultra_ssd',
                   options_list=['--enable-ultra-ssd'],
                   action='store_true')
        c.argument('appgw_name',
                   options_list=['--appgw-name'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_cidr',
                   options_list=['--appgw-subnet-cidr'],
                   arg_group='Application Gateway')
        c.argument('appgw_id',
                   options_list=['--appgw-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_id',
                   options_list=['--appgw-subnet-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_watch_namespace',
                   options_list=['--appgw-watch-namespace'],
                   arg_group='Application Gateway')
        c.argument('assign_kubelet_identity',
                   validator=validate_assign_kubelet_identity)
        c.argument('disable_local_accounts', action='store_true')
        c.argument('enable_secret_rotation', action='store_true')
        c.argument('rotation_poll_interval', type=str)
        c.argument('enable_windows_gmsa',
                   action='store_true',
                   options_list=['--enable-windows-gmsa'])
        c.argument('gmsa_dns_server', options_list=['--gmsa-dns-server'])
        c.argument('gmsa_root_domain_name',
                   options_list=['--gmsa-root-domain-name'])
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.',
                   action='store_true')
        c.argument('enable_sgxquotehelper', action='store_true')
        c.argument('enable_fips_image', action='store_true')
        c.argument('snapshot_id', validator=validate_snapshot_id)

    with self.argument_context(
            'aks update',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='managed_clusters') as c:
        c.argument('attach_acr', acr_arg_type, validator=validate_acr)
        c.argument('detach_acr', acr_arg_type, validator=validate_acr)

    with self.argument_context('aks update') as c:
        c.argument('enable_cluster_autoscaler',
                   options_list=["--enable-cluster-autoscaler", "-e"],
                   action='store_true')
        c.argument('disable_cluster_autoscaler',
                   options_list=["--disable-cluster-autoscaler", "-d"],
                   action='store_true')
        c.argument('update_cluster_autoscaler',
                   options_list=["--update-cluster-autoscaler", "-u"],
                   action='store_true')
        c.argument(
            'cluster_autoscaler_profile',
            nargs='+',
            options_list=["--cluster-autoscaler-profile", "--ca-profile"],
            help=
            "Space-separated list of key=value pairs for configuring cluster autoscaler. Pass an empty string to clear the profile."
        )
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('uptime_sla', action='store_true')
        c.argument('no_uptime_sla', action='store_true')
        c.argument('load_balancer_managed_outbound_ip_count', type=int)
        c.argument('load_balancer_outbound_ips',
                   type=str,
                   validator=validate_load_balancer_outbound_ips)
        c.argument('load_balancer_outbound_ip_prefixes',
                   type=str,
                   validator=validate_load_balancer_outbound_ip_prefixes)
        c.argument('load_balancer_outbound_ports',
                   type=int,
                   validator=validate_load_balancer_outbound_ports)
        c.argument('load_balancer_idle_timeout',
                   type=int,
                   validator=validate_load_balancer_idle_timeout)
        c.argument('auto_upgrade_channel',
                   arg_type=get_enum_type(auto_upgrade_channels))
        c.argument('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)
        c.argument('enable_ahub',
                   options_list=['--enable-ahub'],
                   action='store_true')
        c.argument('disable_ahub',
                   options_list=['--disable-ahub'],
                   action='store_true')
        c.argument('enable_public_fqdn', action='store_true')
        c.argument('disable_public_fqdn', action='store_true')
        c.argument('windows_admin_password',
                   options_list=['--windows-admin-password'])
        c.argument('enable_managed_identity', action='store_true')
        c.argument('assign_identity',
                   type=str,
                   validator=validate_assign_identity)
        c.argument('disable_local_accounts', action='store_true')
        c.argument('enable_local_accounts', action='store_true')
        c.argument('enable_secret_rotation', action='store_true')
        c.argument('disable_secret_rotation', action='store_true')
        c.argument('rotation_poll_interval', type=str)
        c.argument('enable_windows_gmsa',
                   action='store_true',
                   options_list=['--enable-windows-gmsa'])
        c.argument('gmsa_dns_server', options_list=['--gmsa-dns-server'])
        c.argument('gmsa_root_domain_name',
                   options_list=['--gmsa-root-domain-name'])
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.',
                   action='store_true')
        c.argument(
            'nodepool_labels',
            nargs='*',
            validator=validate_nodepool_labels,
            help=
            'space-separated labels: key[=value] [key[=value] ...]. See https://aka.ms/node-labels for syntax of labels.'
        )

    with self.argument_context(
            'aks disable-addons',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='managed_clusters') as c:
        c.argument('addons', options_list=['--addons', '-a'])

    with self.argument_context(
            'aks enable-addons',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='managed_clusters') as c:
        c.argument('addons', options_list=['--addons', '-a'])
        c.argument(
            'subnet_name',
            options_list=['--subnet-name', '-s'],
            help=
            'Name of an existing subnet to use with the virtual-node add-on.')
        c.argument('appgw_name',
                   options_list=['--appgw-name'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_cidr',
                   options_list=['--appgw-subnet-cidr'],
                   arg_group='Application Gateway')
        c.argument('appgw_id',
                   options_list=['--appgw-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_id',
                   options_list=['--appgw-subnet-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_watch_namespace',
                   options_list=['--appgw-watch-namespace'],
                   arg_group='Application Gateway')
        c.argument('enable_sgxquotehelper', action='store_true')
        c.argument('enable_secret_rotation', action='store_true')
        c.argument('rotation_poll_interval', type=str)

    with self.argument_context(
            'aks get-credentials',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='managed_clusters') as c:
        c.argument('admin', options_list=['--admin', '-a'], default=False)
        c.argument(
            'context_name',
            options_list=['--context'],
            help=
            'If specified, overwrite the default context name. The `--admin` parameter takes precedence over `--context`'
        )
        c.argument('path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   default=os.path.join(os.path.expanduser('~'), '.kube',
                                        'config'))
        c.argument('public_fqdn', default=False, action='store_true')
        c.argument('credential_format',
                   type=str,
                   options_list=['--format'],
                   validator=validate_credential_format)

    for scope in ['aks', 'acs kubernetes', 'acs dcos']:
        with self.argument_context('{} install-cli'.format(scope)) as c:
            c.argument('client_version',
                       validator=validate_kubectl_version,
                       help='Version of kubectl to install.')
            c.argument('install_location',
                       default=_get_default_install_location('kubectl'),
                       help='Path at which to install kubectl.')
            c.argument('base_src_url',
                       help='Base download source URL for kubectl releases.')
            c.argument('kubelogin_version',
                       validator=validate_kubelogin_version,
                       help='Version of kubelogin to install.')
            c.argument('kubelogin_install_location',
                       default=_get_default_install_location('kubelogin'),
                       help='Path at which to install kubelogin.')
            c.argument('kubelogin_base_src_url',
                       options_list=['--kubelogin-base-src-url', '-l'],
                       help='Base download source URL for kubelogin releases.')

    with self.argument_context('aks update-credentials',
                               arg_group='Service Principal') as c:
        c.argument('reset_service_principal', action='store_true')
        c.argument('service_principal')
        c.argument('client_secret')

    with self.argument_context('aks update-credentials', arg_group='AAD') as c:
        c.argument('reset_aad', action='store_true')
        c.argument('aad_client_app_id')
        c.argument('aad_server_app_id')
        c.argument('aad_server_app_secret')
        c.argument('aad_tenant_id')

    with self.argument_context(
            'aks upgrade',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='managed_clusters') as c:
        c.argument('kubernetes_version',
                   completer=get_k8s_upgrades_completion_list)
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.',
                   action='store_true')

    with self.argument_context(
            'aks scale',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='managed_clusters') as c:
        c.argument('nodepool_name',
                   type=str,
                   help='Node pool name, up to 12 alphanumeric characters',
                   validator=validate_nodepool_name)

    with self.argument_context(
            'aks nodepool',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='managed_clusters') as c:
        c.argument('cluster_name', type=str, help='The cluster name.')

    for scope in ['aks nodepool add']:
        with self.argument_context(scope) as c:
            c.argument('nodepool_name',
                       type=str,
                       options_list=['--name', '-n'],
                       validator=validate_nodepool_name,
                       help='The node pool name.')
            c.argument(
                'zones',
                zones_type,
                options_list=['--zones', '-z'],
                help=
                'Space-separated list of availability zones where agent nodes will be placed.'
            )
            c.argument('node_vm_size',
                       options_list=['--node-vm-size', '-s'],
                       completer=get_vm_size_completion_list)
            c.argument('max_pods', type=int, options_list=['--max-pods', '-m'])
            c.argument('os_type', type=str)
            c.argument('os_sku', completer=get_ossku_completion_list)
            c.argument('enable_cluster_autoscaler',
                       options_list=["--enable-cluster-autoscaler", "-e"],
                       action='store_true')
            c.argument('scale_down_mode',
                       arg_type=get_enum_type([
                           CONST_SCALE_DOWN_MODE_DELETE,
                           CONST_SCALE_DOWN_MODE_DEALLOCATE
                       ]))
            c.argument('node_taints', validator=validate_taints)
            c.argument('priority',
                       arg_type=get_enum_type(node_priorities),
                       validator=validate_priority)
            c.argument('eviction_policy',
                       arg_type=get_enum_type(node_eviction_policies),
                       validator=validate_eviction_policy)
            c.argument('spot_max_price',
                       type=float,
                       validator=validate_spot_max_price)
            c.argument('tags', tags_type)
            c.argument('labels', nargs='*', validator=validate_nodepool_labels)
            c.argument('mode', get_enum_type(node_mode_types))
            c.argument('enable_node_public_ip', action='store_true')
            c.argument('node_public_ip_prefix_id', type=str)
            c.argument('ppg', type=str, validator=validate_ppg)
            c.argument('max_surge', type=str, validator=validate_max_surge)
            c.argument('node_os_disk_type',
                       arg_type=get_enum_type(node_os_disk_types))
            c.argument('enable_encryption_at_host',
                       options_list=['--enable-encryption-at-host'],
                       action='store_true')
            c.argument('enable_ultra_ssd',
                       options_list=['--enable-ultra-ssd'],
                       action='store_true')
            c.argument('enable_fips_image', action='store_true')
            c.argument('snapshot_id', validator=validate_snapshot_id)

    for scope in [
            'aks nodepool show', 'aks nodepool delete', 'aks nodepool scale',
            'aks nodepool upgrade', 'aks nodepool update'
    ]:
        with self.argument_context(scope) as c:
            c.argument('nodepool_name',
                       type=str,
                       options_list=['--name', '-n'],
                       validator=validate_nodepool_name,
                       help='The node pool name.')

    with self.argument_context('aks nodepool upgrade') as c:
        c.argument('snapshot_id', validator=validate_snapshot_id)

    with self.argument_context(
            'aks nodepool update',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='agent_pools') as c:
        c.argument('enable_cluster_autoscaler',
                   options_list=["--enable-cluster-autoscaler", "-e"],
                   action='store_true')
        c.argument('disable_cluster_autoscaler',
                   options_list=["--disable-cluster-autoscaler", "-d"],
                   action='store_true')
        c.argument('update_cluster_autoscaler',
                   options_list=["--update-cluster-autoscaler", "-u"],
                   action='store_true')
        c.argument('scale_down_mode',
                   arg_type=get_enum_type([
                       CONST_SCALE_DOWN_MODE_DELETE,
                       CONST_SCALE_DOWN_MODE_DEALLOCATE
                   ]))
        c.argument('tags', tags_type)
        c.argument('mode', get_enum_type(node_mode_types))
        c.argument('max_surge', type=str, validator=validate_max_surge)
        c.argument('labels', nargs='*', validator=validate_nodepool_labels)
        c.argument('node_taints', validator=validate_taints)

    with self.argument_context('aks command invoke') as c:
        c.argument('command_string',
                   type=str,
                   options_list=["--command", "-c"],
                   help='the command to run')
        c.argument(
            'command_files',
            options_list=["--file", "-f"],
            required=False,
            action="append",
            help=
            'attach any files the command may use, or use \'.\' to upload the current folder.'
        )

    with self.argument_context('aks command result') as c:
        c.argument('command_id',
                   type=str,
                   options_list=["--command-id", "-i"],
                   help='the command ID from "aks command invoke"')

    with self.argument_context('aks use-dev-spaces') as c:
        c.argument('update', options_list=['--update'], action='store_true')
        c.argument('space_name', options_list=['--space', '-s'])
        c.argument('endpoint_type',
                   get_enum_type(dev_space_endpoint_types, default='Public'),
                   options_list=['--endpoint', '-e'])
        c.argument('prompt',
                   options_list=['--yes', '-y'],
                   action='store_true',
                   help='Do not prompt for confirmation. Requires --space.')

    with self.argument_context('aks remove-dev-spaces') as c:
        c.argument('prompt',
                   options_list=['--yes', '-y'],
                   action='store_true',
                   help='Do not prompt for confirmation')

    # OpenShift command argument configuration
    with self.argument_context(
            'openshift',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='open_shift_managed_clusters') as c:
        c.argument('resource_name',
                   name_type,
                   help='Name of the managed OpenShift cluster.',
                   completer=get_resource_name_completion_list(
                       'Microsoft.ContainerService/OpenShiftManagedClusters'))
        c.argument('name',
                   name_type,
                   help='Name of the managed OpenShift cluster.',
                   completer=get_resource_name_completion_list(
                       'Microsoft.ContainerService/OpenShiftManagedClusters'))
        c.argument('compute_count',
                   options_list=['--compute-count', '-c'],
                   type=int,
                   default=4)
        c.argument('tags', tags_type)

    with self.argument_context(
            'openshift create',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='open_shift_managed_clusters') as c:
        c.argument('name', validator=validate_linux_host_name)
        c.argument('compute_vm_size', options_list=['--compute-vm-size', '-s'])
        c.argument('customer_admin_group_id',
                   options_list=['--customer-admin-group-id'])
        c.argument('workspace_id')

    with self.argument_context(
            'openshift monitor enable',
            resource_type=ResourceType.MGMT_CONTAINERSERVICE,
            operation_group='open_shift_managed_clusters') as c:
        c.argument(
            'workspace_id',
            help=
            'The resource ID of an existing Log Analytics Workspace to use for storing monitoring data.'
        )

    for scope in ['aks snapshot create']:
        with self.argument_context(scope) as c:
            c.argument('snapshot_name',
                       options_list=['--name', '-n'],
                       required=True,
                       validator=validate_linux_host_name,
                       help='The snapshot name.')
            c.argument('tags', tags_type)
            c.argument('nodepool_id',
                       required=True,
                       validator=validate_nodepool_id,
                       help='The nodepool id.')
            c.argument('aks_custom_headers')

    for scope in ['aks snapshot show', 'aks snapshot delete']:
        with self.argument_context(scope) as c:
            c.argument('snapshot_name',
                       options_list=['--name', '-n'],
                       required=True,
                       validator=validate_linux_host_name,
                       help='The snapshot name.')
            c.argument('yes',
                       options_list=['--yes', '-y'],
                       help='Do not prompt for confirmation.',
                       action='store_true')
def load_arguments(self, _):

    # AKS command argument configuration
    with self.argument_context('aks') as c:
        c.argument('resource_name', name_type, help='Name of the managed cluster.',
                   completer=get_resource_name_completion_list('Microsoft.ContainerService/ManagedClusters'))
        c.argument('name', name_type, help='Name of the managed cluster.',
                   completer=get_resource_name_completion_list('Microsoft.ContainerService/ManagedClusters'))
        c.argument('kubernetes_version', options_list=['--kubernetes-version', '-k'], validator=validate_k8s_version)
        c.argument('node_count', options_list=['--node-count', '-c'], type=int)
        c.argument('tags', tags_type)

    with self.argument_context('aks create') as c:
        c.argument('name', validator=validate_linux_host_name)
        c.argument('kubernetes_version', completer=get_k8s_versions_completion_list)
        c.argument('admin_username', options_list=['--admin-username', '-u'], default='azureuser')
        c.argument('windows_admin_username', options_list=['--windows-admin-username'])
        c.argument('windows_admin_password', options_list=['--windows-admin-password'])
        c.argument('dns_name_prefix', options_list=['--dns-name-prefix', '-p'])
        c.argument('generate_ssh_keys', action='store_true', validator=validate_create_parameters)
        c.argument('node_vm_size', options_list=['--node-vm-size', '-s'], completer=get_vm_size_completion_list)
        c.argument('nodepool_name', type=str, default='nodepool1',
                   help='Node pool name, upto 12 alphanumeric characters', validator=validate_nodepool_name)
        c.argument('ssh_key_value', required=False, type=file_type, default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(), validator=validate_ssh_key)
        c.argument('aad_client_app_id')
        c.argument('aad_server_app_id')
        c.argument('aad_server_app_secret')
        c.argument('aad_tenant_id')
        c.argument('dns_service_ip')
        c.argument('docker_bridge_address')
        c.argument('enable_addons', options_list=['--enable-addons', '-a'])
        c.argument('disable_rbac', action='store_true')
        c.argument('enable_rbac', action='store_true', options_list=['--enable-rbac', '-r'],
                   deprecate_info=c.deprecate(redirect="--disable-rbac", hide="2.0.45"))
        c.argument('max_pods', type=int, options_list=['--max-pods', '-m'], validator=validate_max_pods)
        c.argument('network_plugin')
        c.argument('network_policy')
        c.argument('no_ssh_key', options_list=['--no-ssh-key', '-x'])
        c.argument('pod_cidr')
        c.argument('service_cidr')
        c.argument('vnet_subnet_id')
        c.argument('workspace_resource_id')
        c.argument('skip_subnet_role_assignment', action='store_true')
        c.argument('enable_cluster_autoscaler', action='store_true')
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('enable_vmss', action='store_true')
        c.argument('node_zones', zones_type, options_list='--node-zones', help='(PREVIEW) Space-separated list of availability zones where agent nodes will be placed.')
        c.argument('enable_pod_security_policy', action='store_true')
        c.argument('node_resource_group')

    with self.argument_context('aks update') as c:
        c.argument('enable_cluster_autoscaler', options_list=["--enable-cluster-autoscaler", "-e"], action='store_true')
        c.argument('disable_cluster_autoscaler', options_list=["--disable-cluster-autoscaler", "-d"], action='store_true')
        c.argument('update_cluster_autoscaler', options_list=["--update-cluster-autoscaler", "-u"], action='store_true')
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('api_server_authorized_ip_ranges', type=str, validator=validate_ip_ranges)
        c.argument('enable_pod_security_policy', action='store_true')
        c.argument('disable_pod_security_policy', action='store_true')

    with self.argument_context('aks scale') as c:
        c.argument('nodepool_name', type=str,
                   help='Node pool name, upto 12 alphanumeric characters', validator=validate_nodepool_name)

    with self.argument_context('aks upgrade') as c:
        c.argument('kubernetes_version', completer=get_k8s_upgrades_completion_list)

    with self.argument_context('aks nodepool') as c:
        c.argument('cluster_name', type=str, help='The cluster name.')

    for scope in ['aks nodepool add']:
        with self.argument_context(scope) as c:
            c.argument('nodepool_name', type=str, options_list=['--name', '-n'], validator=validate_nodepool_name, help='The node pool name.')
            c.argument('node_zones', zones_type, options_list='--node-zones', help='(PREVIEW) Space-separated list of availability zones where agent nodes will be placed.')
            c.argument('node_vm_size', options_list=['--node-vm-size', '-s'], completer=get_vm_size_completion_list)
            c.argument('max_pods', type=int, options_list=['--max-pods', '-m'], validator=validate_max_pods)
            c.argument('os_type', type=str)

    for scope in ['aks nodepool show', 'aks nodepool delete', 'aks nodepool scale', 'aks nodepool upgrade']:
        with self.argument_context(scope) as c:
            c.argument('nodepool_name', type=str, options_list=['--name', '-n'], validator=validate_nodepool_name, help='The node pool name.')

    with self.argument_context('aks disable-addons') as c:
        c.argument('addons', options_list=['--addons', '-a'])

    with self.argument_context('aks enable-addons') as c:
        c.argument('addons', options_list=['--addons', '-a'])
        c.argument('subnet_name', options_list=['--subnet-name', '-s'])
Example #42
0
orchestratorTypes = ["Custom", "DCOS", "Kubernetes", "Swarm", "DockerCE"]

aci_connector_os_type = ['Windows', 'Linux', 'Both']

aci_connector_chart_url = 'https://github.com/virtual-kubelet/virtual-kubelet/raw/master/charts/virtual-kubelet-0.1.0.tgz'

k8s_version_arg_type = CliArgumentType(options_list=('--kubernetes-version', '-k'), metavar='KUBERNETES_VERSION')

storageProfileTypes = ["StorageAccount", "ManagedDisks"]

register_cli_argument('acs', 'tags', tags_type)

register_cli_argument('acs', 'name', arg_type=name_arg_type, configured_default='acs',
                      help="ACS cluster name. You can configure the default using `az configure --defaults acs=<name>`",
                      completer=get_resource_name_completion_list('Microsoft.ContainerService/ContainerServices'))

register_cli_argument('acs', 'resource_group', arg_type=resource_group_name_type)

register_cli_argument('acs', 'orchestrator_type', options_list=('--orchestrator-type', '-t'), help='DockerCE - ' + _get_feature_in_preview_message(), **enum_choice_list(orchestratorTypes))
# some admin names are prohibited in acs, such as root, admin, etc. Because we have no control on the orchestrators, so default to a safe name.
register_cli_argument('acs', 'admin_username', options_list=('--admin-username',), default='azureuser', required=False)
register_cli_argument('acs', 'api_version', options_list=('--api-version',), required=False, help=_get_feature_in_preview_message() + 'Use API version of ACS to perform az acs operations. Available options: 2017-01-31, 2017-07-01. Default: the latest version for the location')
register_cli_argument('acs', 'dns_name_prefix', options_list=('--dns-prefix', '-d'), help='default use the format of <clustername>-<resourcegroupname>-<subid>, will trim the length and replace sensitive characters if needed')
register_cli_argument('acs', 'container_service_name', options_list=('--name', '-n'), help='The name of the container service', completer=get_resource_name_completion_list('Microsoft.ContainerService/ContainerServices'))

register_cli_argument('acs', 'ssh_key_value', required=False, help='SSH key file value or key file path.', type=file_type, default=os.path.join('~', '.ssh', 'id_rsa.pub'), completer=FilesCompleter())
register_cli_argument('acs create', 'name', arg_type=name_arg_type, validator=validate_ssh_key)

register_extra_cli_argument('acs create', 'generate_ssh_keys', action='store_true', help='Generate SSH public and private key files if missing', validator=validate_create_parameters)
register_cli_argument('acs create', 'master_profile', options_list=('--master-profile', '-m'), type=validate_file_or_dict, help=_get_feature_in_preview_message() + 'The file or dictionary representation of the master profile. Note it will override any master settings once set')
def load_arguments(self, _):

    ExpressRoutePeeringType = self.get_models('ExpressRoutePeeringType')

    name_arg_type = CLIArgumentType(options_list=('--name', '-n'), metavar='NAME')
    cross_connection_name_type = CLIArgumentType(options_list=('--cross-connection-name',), metavar='NAME', help='ExpressRoute cross-connection name.', id_part='name', completer=get_resource_name_completion_list('Microsoft.Network/expressRouteCrossConnections'))
    routing_registry_values = ['ARIN', 'APNIC', 'AFRINIC', 'LACNIC', 'RIPENCC', 'RADB', 'ALTDB', 'LEVEL3']
    device_path_values = ['primary', 'secondary']

    with self.argument_context('network cross-connection') as c:
        c.argument('cross_connection_name', cross_connection_name_type, options_list=['--name', '-n'])
        c.argument('device_path', options_list='--path', arg_type=get_enum_type(device_path_values))

    with self.argument_context('network cross-connection update') as c:
        c.argument('notes', help='Service provider notes.')
        c.argument('provisioning_state', arg_type=get_enum_type(['Provisioning', 'Provisioned', 'NotProvisioned']), help='Provisioning state of the customer ExpressRoute circuit.')

    with self.argument_context('network cross-connection peering') as c:
        # Using six.integer_types so we get int for Py3 and long for Py2
        c.argument('peer_asn', help='Autonomous system number of the customer/connectivity provider.', type=six.integer_types[-1])
        c.argument('vlan_id', help='Identifier used to identify the customer.', type=int)
        c.argument('cross_connection_name', cross_connection_name_type)
        c.argument('peering_name', name_arg_type, id_part='child_name_1')
        c.argument('peering_type', validator=validate_peering_type, arg_type=get_enum_type(ExpressRoutePeeringType), help='BGP peering type for the circuit.')
        c.argument('primary_peer_address_prefix', options_list='--primary-peer-subnet', help='/30 subnet used to configure IP addresses for primary interface.')
        c.argument('secondary_peer_address_prefix', options_list='--secondary-peer-subnet', help='/30 subnet used to configure IP addresses for secondary interface.')
        c.argument('advertised_public_prefixes', arg_group='Microsoft Peering', nargs='+', help='Space-separated list of prefixes to be advertised through the BGP peering.')
        c.argument('customer_asn', arg_group='Microsoft Peering', help='Autonomous system number of the customer.')
        c.argument('routing_registry_name', arg_group='Microsoft Peering', arg_type=get_enum_type(routing_registry_values), help='Internet Routing Registry / Regional Internet Registry')
        c.argument('ip_version', min_api='2017-06-01', help='The IP version to update Microsoft Peering settings for.', arg_group='Microsoft Peering', arg_type=get_enum_type(['IPv4', 'IPv6']))
        c.argument('shared_key', help='Key for generating an MD5 for the BGP session.')

    with self.argument_context('network cross-connection peering list') as c:
        c.argument('cross_connection_name', id_part=None)
Example #44
0
register_cli_argument('appservice',
                      'resource_group_name',
                      arg_type=resource_group_name_type)
register_cli_argument('appservice', 'location', arg_type=location_type)

register_cli_argument(
    'appservice list-locations',
    'linux_workers_enabled',
    action='store_true',
    help='get regions which support hosting webapps on Linux workers')
register_cli_argument(
    'appservice plan',
    'name',
    arg_type=name_arg_type,
    help='The name of the app service plan',
    completer=get_resource_name_completion_list('Microsoft.Web/serverFarms'),
    id_part='name')
register_cli_argument('appservice plan create',
                      'name',
                      options_list=('--name', '-n'),
                      help="Name of the new app service plan")
register_cli_argument('appservice plan create', 'sku', arg_type=sku_arg_type)
register_cli_argument('appservice plan create',
                      'is_linux',
                      action='store_true',
                      required=False,
                      help='host webapp on Linux worker')
register_cli_argument('appservice plan update', 'sku', arg_type=sku_arg_type)
register_cli_argument('appservice plan update', 'allow_pending_state',
                      ignore_type)
register_cli_argument('appservice plan',
Example #45
0
def load_arguments(self, _):
    batch_name_type = CLIArgumentType(
        help='Name of the Batch account.',
        options_list=('--account-name',),
        completer=get_resource_name_completion_list('Microsoft.Batch/batchAccounts'),
        id_part=None)

    with self.argument_context('batch') as c:
        c.argument('resource_group_name', resource_group_name_type, help='Name of the resource group', completer=None, validator=None, required=True)

    with self.argument_context('batch account') as c:
        c.argument('account_name', batch_name_type, options_list=('--name', '-n'))

    with self.argument_context('batch account show') 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.', required=False)
        c.argument('account_name', batch_name_type, options_list=('--name', '-n'), help='Name of the batch account to show. If not specified will display currently set account.', required=False)

    with self.argument_context('batch account list') as c:
        c.argument('resource_group_name', resource_group_name_type, help='Name of the resource group', required=False)

    with self.argument_context('batch account create') as c:
        c.argument('location', get_location_type(self.cli_ctx), help='The region in which to create the account.')
        c.argument('tags', tags_type, help="Space-separated tags in 'key[=value]' format.")
        c.argument('storage_account', help='The storage account name or resource ID to be used for auto storage.', validator=storage_account_id)
        c.argument('keyvault', help='The KeyVault name or resource ID to be used for an account with a pool allocation mode of \'User Subscription\'.', validator=keyvault_id)
        c.ignore('keyvault_url')

    with self.argument_context('batch account set') as c:
        c.argument('tags', tags_type)
        c.argument('storage_account', help='The storage account name or resource ID to be used for auto storage.', validator=storage_account_id)

    with self.argument_context('batch account keys renew') as c:
        c.argument('key_name', arg_type=get_enum_type(AccountKeyType))

    with self.argument_context('batch account login') as c:
        c.argument('shared_key_auth', action='store_true', help='Using Shared Key authentication, if not specified, it will use Azure Active Directory authentication.')
        c.argument('show', action='store_true', help='Display the credential information for the Batch account.')

    with self.argument_context('batch application set') as c:
        c.argument('application_id', options_list=('--application-id',), help="The ID of the application.")
        c.argument('allow_updates', options_list=('--allow-updates',), help="Specify to indicate whether packages within the application may be overwritten using the same version string. Specify either 'true' or 'false' to update the property.")

    with self.argument_context('batch application create') as c:
        c.argument('allow_updates', options_list=('--allow-updates',), action="store_true", help="Specify to indicate whether packages within the application may be overwritten using the same version string. True if flag present.")

    with self.argument_context('batch application package create') as c:
        c.argument('package_file', type=file_type, help='The path of the application package in zip format', completer=FilesCompleter())
        c.argument('application_id', options_list=('--application-id',), help="The ID of the application.")
        c.argument('version', options_list=('--version',), help="The version of the application.")

    with self.argument_context('batch location quotas show') as c:
        c.argument('location_name', get_location_type(self.cli_ctx), help='The region from which to display the Batch service quotas.')

    for command in ['list', 'show', 'create', 'set', 'delete', 'package']:
        with self.argument_context('batch application {}'.format(command)) as c:
            c.argument('account_name', batch_name_type, options_list=('--name', '-n'), validator=application_enabled)

    # TODO: Refactor so the help text can be extracted automatically
    with self.argument_context('batch pool resize') as c:
        c.argument('if_modified_since', help='The operation will be performed only if the resource has been modified since the specified timestamp.', type=datetime_format, arg_group='Pre-condition and Query')
        c.argument('if_unmodified_since', help='The operation will not be performed only if the resource has been modified since the specified timestamp.', type=datetime_format, arg_group='Pre-condition and Query')
        c.argument('if_match', help='The operation will be performed only if the resource\'s current ETag exactly matches the specified value.', arg_group='Pre-condition and Query')
        c.argument('if_none_match', help='The operation will not be performed only if the resource\'s current ETag exactly matches the specified value.', arg_group='Pre-condition and Query')
        c.argument('pool_id', help='The ID of the pool.')
        c.argument('abort', action='store_true', help='Stop the pool resize operation.', validator=validate_pool_resize_parameters)
        c.argument('node_deallocation_option', options_list=('--node-deallocation-option',), help='When nodes may be removed from the pool, if the pool size is decreasing.', arg_type=get_enum_type(ComputeNodeDeallocationOption))

    # TODO: Refactor so the help text can be extracted automatically
    with self.argument_context('batch pool reset') as c:
        c.argument('json_file', type=file_type, help='The file containing pool update properties parameter specification in JSON(formatted to match REST API request body). If this parameter is specified, all \'Pool Update Properties Parameter Arguments\' are ignored.', validator=validate_json_file, completer=FilesCompleter())
        c.argument('pool_id', help='The ID of the pool to update.')
        c.argument('application_package_references', nargs='+', type=application_package_reference_format, arg_group='Pool')
        c.argument('certificate_references', nargs='+', type=certificate_reference_format, arg_group='Pool')
        c.argument('metadata', nargs='+', type=metadata_item_format, arg_group='Pool')
        c.argument('start_task_command_line', arg_group='Pool: Start Task',
                   help='The command line of the start task. The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.')
        c.argument('start_task_wait_for_success', action='store_true', arg_group='Pool: Start Task',
                   help='Whether the Batch service should wait for the start task to complete successfully (that is, to exit with exit code 0) before scheduling any tasks on the compute node. True if flag present, otherwise defaults to False.')
        c.argument('start_task_max_task_retry_count', arg_group='Pool: Start Task',
                   help='The maximum number of times the task may be retried.')
        c.argument('start_task_environment_settings', nargs='+', type=environment_setting_format, arg_group='Pool: Start Task',
                   help='A list of environment variable settings for the start task. Space-separated values in \'key=value\' format.')

    with self.argument_context('batch job list') as c:
        c.argument('filter', help=' An OData $filter clause.', arg_group='Pre-condition and Query')
        c.argument('select', help=' An OData $select clause.', arg_group='Pre-condition and Query')
        c.argument('expand', help=' An OData $expand clause.', arg_group='Pre-condition and Query')
        c.argument('job_schedule_id', help='The ID of the job schedule from which you want to get a list of jobs. If omitted, lists all jobs in the account.')

    for command in ['job create', 'job set', 'job reset', 'job-schedule create', 'job-schedule set', 'job-schedule reset']:
        with self.argument_context('batch {}'.format(command)) as c:
            c.argument('pool_id', options_list=('--pool-id',), help='The id of an existing pool. All the tasks of the job will run on the specified pool.')

    with self.argument_context('batch pool create') as c:
        c.argument('os_family', arg_type=get_enum_type(['2', '3', '4', '5']))
        c.argument('auto_scale_formula', help='A formula for the desired number of compute nodes in the pool. The formula is checked for validity before the pool is created. If the formula is not valid, the Batch service rejects the request with detailed error information. For more information about specifying this formula, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/.')
        c.extra('image', completer=load_node_agent_skus, 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 node-agent-skus list'. For example: 'MicrosoftWindowsServer:WindowsServer:2012-R2-Datacenter:latest'")

    with self.argument_context('batch certificate') as c:
        c.argument('thumbprint', help='The certificate thumbprint.')
        c.argument('password', help='The password to access the certificate\'s private key.')
        c.argument('certificate_file', type=file_type, help='The certificate file: cer file or pfx file.', validator=validate_cert_file, completer=FilesCompleter())
        c.argument('abort', action='store_true', help='Cancel the failed certificate deletion operation.')

    with self.argument_context('batch certificate show') as c:
        c.argument('thumbprint', help='The certificate thumbprint.', validator=validate_cert_settings)

    with self.argument_context('batch task create') as c:
        c.argument('json_file', type=file_type, help='The file containing the task(s) to create in JSON(formatted to match REST API request body). When submitting multiple tasks, accepts either an array of tasks or a TaskAddCollectionParamater. If this parameter is specified, all other parameters are ignored.', validator=validate_json_file, completer=FilesCompleter())
        c.argument('application_package_references', nargs='+', help='The space-separated list of IDs specifying the application packages to be installed. Space-separated application IDs with optional version in \'id[#version]\' format.', type=application_package_reference_format)
        c.argument('job_id', help='The ID of the job containing the task.')
        c.argument('task_id', help='The ID of the task.')
        c.argument('command_line', help='The command line of the task. The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.')
        c.argument('environment_settings', nargs='+', help='A list of environment variable settings for the task. Space-separated values in \'key=value\' format.', type=environment_setting_format)
        c.argument('resource_files', nargs='+', help='A list of files that the Batch service will download to the compute node before running the command line. Space-separated resource references in filename=blobsource format.', type=resource_file_format)

    for item in ['batch certificate delete', 'batch certificate create', 'batch pool resize', 'batch pool reset', 'batch job list', 'batch task create']:
        with self.argument_context(item) as c:
            c.extra('account_name', arg_group='Batch Account', validator=validate_client_parameters,
                    help='The Batch account name. Alternatively, set by environment variable: AZURE_BATCH_ACCOUNT')
            c.extra('account_key', arg_group='Batch Account',
                    help='The Batch account key. Alternatively, set by environment variable: AZURE_BATCH_ACCESS_KEY')
            c.extra('account_endpoint', arg_group='Batch Account',
                    help='Batch service endpoint. Alternatively, set by environment variable: AZURE_BATCH_ENDPOINT')
Example #46
0
delete_snapshot_types = {
    'include': DeleteSnapshot.Include,
    'only': DeleteSnapshot.Only
}
table_payload_formats = {
    'none': TablePayloadFormat.JSON_NO_METADATA,
    'minimal': TablePayloadFormat.JSON_MINIMAL_METADATA,
    'full': TablePayloadFormat.JSON_FULL_METADATA
}

# ARGUMENT TYPES

account_name_type = CliArgumentType(
    options_list=('--account-name', '-n'),
    help='The storage account name.',
    completer=get_resource_name_completion_list(
        'Microsoft.Storage/storageAccounts'),
    id_part='name')
blob_name_type = CliArgumentType(options_list=('--blob-name', '-b'),
                                 help='The blob name.',
                                 completer=get_storage_name_completion_list(
                                     BaseBlobService,
                                     'list_blobs',
                                     parent='container_name'))
container_name_type = CliArgumentType(
    options_list=('--container-name', '-c'),
    help='The container name.',
    completer=get_storage_name_completion_list(BaseBlobService,
                                               'list_containers'))
directory_type = CliArgumentType(options_list=('--directory-name', '-d'),
                                 help='The directory name.',
                                 completer=get_storage_name_completion_list(
def load_arguments(self, _):    # pylint: disable=too-many-statements
    with self.argument_context('eventgrid') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location', arg_type=get_location_type(self.cli_ctx))
        c.argument('tags', arg_type=tags_type)
        c.argument('included_event_types', arg_type=included_event_types_type)
        c.argument('labels', arg_type=labels_type)
        c.argument('endpoint_type', arg_type=get_enum_type(['webhook', 'eventhub', 'storagequeue', 'hybridconnection', 'servicebusqueue'], default='webhook'))
        c.argument('source_resource_id', help="Fully qualified identifier of the source Azure resource.")
        c.argument('resource_id', deprecate_info=c.deprecate(redirect="--source-resource-id", expiration='2.1.0', hide=True), help="Fully qualified identifier of the Azure resource.")
        c.argument('endpoint', help="Endpoint where EventGrid should deliver events matching this event subscription. For webhook endpoint type, this should be the corresponding webhook URL. For other endpoint types, this should be the Azure resource identifier of the endpoint.")
        c.argument('event_subscription_name', help="Name of the event subscription.")
        c.argument('subject_begins_with', help="An optional string to filter events for an event subscription based on a prefix. Wildcard characters are not supported.")
        c.argument('subject_ends_with', help="An optional string to filter events for an event subscription based on a suffix. Wildcard characters are not supported.")
        c.argument('topic_type_name', help="Name of the topic type.")
        c.argument('is_subject_case_sensitive', arg_type=get_three_state_flag(), options_list=['--subject-case-sensitive'], help="Specify to indicate whether the subject fields should be compared in a case sensitive manner. True if flag present.", )
        c.argument('input_mapping_fields', arg_type=input_mapping_fields_type)
        c.argument('input_mapping_default_values', arg_type=input_mapping_default_values_type)
        c.argument('input_schema', arg_type=input_schema_type)
        c.argument('odata_query', arg_type=odata_query_type)
        c.argument('domain_name', arg_type=domain_name_type)
        c.argument('domain_topic_name', arg_type=domain_topic_name_type)

    with self.argument_context('eventgrid topic') as c:
        c.argument('topic_name', arg_type=name_type, help='Name of the topic.', id_part='name', completer=get_resource_name_completion_list('Microsoft.EventGrid/topics'))

    with self.argument_context('eventgrid topic key') as c:
        c.argument('topic_name', arg_type=name_type, help='Name of the topic', id_part=None, completer=get_resource_name_completion_list('Microsoft.EventGrid/topics'))

    with self.argument_context('eventgrid topic list') as c:
        c.argument('odata_query', arg_type=odata_query_type, id_part=None)

    with self.argument_context('eventgrid domain') as c:
        c.argument('domain_name', arg_type=domain_name_type, options_list=['--name', '-n'], id_part='name')

    with self.argument_context('eventgrid domain list') as c:
        c.argument('odata_query', arg_type=odata_query_type, id_part=None)

    with self.argument_context('eventgrid domain key') as c:
        c.argument('domain_name', arg_type=domain_name_type, options_list=['--name', '-n'], id_part=None)

    with self.argument_context('eventgrid domain topic') as c:
        c.argument('domain_name', arg_type=domain_name_type, id_part='name')
        c.argument('domain_topic_name', arg_type=domain_topic_name_type, options_list=['--name', '-n'], id_part='topics')

    with self.argument_context('eventgrid domain topic list') as c:
        c.argument('domain_name', arg_type=domain_name_type, id_part=None)
        c.argument('odata_query', arg_type=odata_query_type, id_part=None)

    with self.argument_context('eventgrid event-subscription') as c:
        c.argument('topic_name', deprecate_info=c.deprecate(expiration='2.1.0', hide=True), help='Name of Event Grid topic.', options_list=['--topic-name'], completer=get_resource_name_completion_list('Microsoft.EventGrid/topics'))
        c.argument('event_subscription_name', arg_type=name_type, help='Name of the event subscription.')
        c.argument('event_delivery_schema', arg_type=get_enum_type(['eventgridschema', 'custominputschema', 'cloudeventv01schema']), help='The schema in which events should be delivered for this event subscription. By default, events will be delivered in the same schema in which they are published (based on the corresponding topic\'s input schema).')
        c.argument('max_delivery_attempts', help="Maximum number of delivery attempts. Must be a number between 1 and 30.")
        c.argument('event_ttl', help="Event time to live (in minutes). Must be a number between 1 and 1440.")
        c.argument('deadletter_endpoint', help="The Azure resource ID of an Azure Storage blob container destination where EventGrid should deadletter undeliverable events for this event subscription.")
        c.argument('advanced_filter', action=EventSubscriptionAddFilter, nargs='+')
        c.argument('expiration_date', help="Date or datetime (in UTC, e.g. '2018-11-30T11:59:59+00:00' or '2018-11-30') after which the event subscription would expire. By default, there is no expiration for the event subscription.")

    with self.argument_context('eventgrid event-subscription create') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(expiration='2.1.0', hide=True), arg_type=resource_group_name_type)

    with self.argument_context('eventgrid event-subscription delete') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(expiration='2.1.0', hide=True), arg_type=resource_group_name_type)

    with self.argument_context('eventgrid event-subscription update') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(expiration='2.1.0', hide=True), arg_type=resource_group_name_type)

    with self.argument_context('eventgrid event-subscription list') as c:
        c.argument('odata_query', arg_type=odata_query_type, id_part=None)

    with self.argument_context('eventgrid event-subscription show') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(expiration='2.1.0', hide=True), arg_type=resource_group_name_type)
        c.argument('include_full_endpoint_url', arg_type=get_three_state_flag(), options_list=['--include-full-endpoint-url'], help="Specify to indicate whether the full endpoint URL should be returned. True if flag present.", )

    with self.argument_context('eventgrid topic-type') as c:
        c.argument('topic_type_name', arg_type=name_type, help="Name of the topic type.", completer=get_resource_name_completion_list('Microsoft.EventGrid/topictypes'))
Example #48
0
def load_arguments(self, _):    # pylint: disable=too-many-statements

    server_completers = {
        'mariadb': get_resource_name_completion_list('Microsoft.DBForMariaDB/servers'),
        'mysql': get_resource_name_completion_list('Microsoft.DBForMySQL/servers'),
        'postgres': get_resource_name_completion_list('Microsoft.DBForPostgreSQL/servers')
    }

    def _complex_params(command_group):
        with self.argument_context('{} server create'.format(command_group)) as c:
            c.argument('sku_name', options_list=['--sku-name'], required=True, help='The name of the sku. Follows the convention {pricing tier}_{compute generation}_{vCores} in shorthand. Examples: B_Gen5_1, GP_Gen5_4, MO_Gen5_16. ')
            c.argument('administrator_login', required=True, arg_group='Authentication')
            c.argument('administrator_login_password', required=True, arg_group='Authentication')

            c.argument('backup_retention', type=int, options_list=['--backup-retention'], help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.', validator=retention_validator)
            c.argument('geo_redundant_backup', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--geo-redundant-backup'], help='Enable or disable geo-redundant backups. Default value is Disabled. Not supported in Basic pricing tier.')
            c.argument('storage_mb', options_list=['--storage-size'], type=int, help='The storage capacity of the server (unit is megabytes). Minimum 5120 and increases in 1024 increments. Default is 51200.')

            c.argument('location', arg_type=get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)
            c.argument('version', help='Server major version.')

        with self.argument_context('{} server update'.format(command_group)) as c:
            c.ignore('family', 'capacity', 'tier')
            c.argument('sku_name', options_list=['--sku-name'], help='The name of the sku. Follows the convention {pricing tier}_{compute generation}_{vCores} in shorthand. Examples: B_Gen5_1, GP_Gen5_4, MO_Gen5_16.')

        with self.argument_context('{} server restore'. format(command_group)) as c:
            c.argument('source_server', options_list=['--source-server', '-s'], help='The name or resource ID of the source server to restore from.')
            c.argument('restore_point_in_time', help='The point in time to restore from (ISO8601 format), e.g., 2017-04-26T02:10:00+08:00')

        with self.argument_context('{} server georestore'. format(command_group)) as c:
            c.argument('location', arg_type=get_location_type(self.cli_ctx), required=True)
            c.argument('sku_name', options_list=['--sku-name'], required=False, help='The name of the sku. Defaults to sku of the source server. Follows the convention {pricing tier}_{compute generation}_{vCores} in shorthand. Examples: B_Gen5_1, GP_Gen5_4, MO_Gen5_16.')
            c.argument('source_server', options_list=['--source-server', '-s'], required=True, help='The name or ID of the source server to restore from.')
            c.argument('backup_retention', options_list=['--backup-retention'], type=int, help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.', validator=retention_validator)
            c.argument('geo_redundant_backup', options_list=['--geo-redundant-backup'], help='Enable or disable geo-redundant backups. Default value is Disabled. Not supported in Basic pricing tier.')

        with self.argument_context('mysql server replica') as c:
            c.argument('source_server', options_list=['--source-server', '-s'], help='The name or resource ID of the master server to the create replica for.')

        with self.argument_context('postgres server replica') as c:
            c.argument('source_server', options_list=['--source-server', '-s'], help='The name or resource ID of the master server to the create replica for.')

        with self.argument_context('{} server configuration set'.format(command_group)) as c:
            c.argument('value', help='Value of the configuration. If not provided, configuration value will be set to default.', validator=configuration_value_validator)
            c.ignore('source')

        with self.argument_context('{} server wait'.format(command_group)) as c:
            c.ignore('created', 'deleted', 'updated')

    _complex_params('mariadb')
    _complex_params('mysql')
    _complex_params('postgres')

    for scope in ['mariadb', 'mysql', 'postgres']:
        with self.argument_context(scope) as c:
            c.argument('name', options_list=['--sku-name'], required=True)
            c.argument('server_name', completer=server_completers[scope], options_list=['--server-name', '-s'], help='Name of the server. The name can contain only lowercase letters, numbers, and the hyphen (-) character. Minimum 3 characters and maximum 63 characters.')

    for scope in ['mariadb server', 'mysql server', 'postgres server']:
        with self.argument_context(scope) as c:
            c.ignore('family', 'capacity', 'tier')

            c.argument('server_name', options_list=['--name', '-n'], id_part='name', help='Name of the server. The name can contain only lowercase letters, numbers, and the hyphen (-) character. Minimum 3 characters and maximum 63 characters.')
            c.argument('administrator_login', options_list=['--admin-user', '-u'], help='Administrator username for the server. Once set, it cannot be changed.')
            c.argument('administrator_login_password', options_list=['--admin-password', '-p'], help='The password of the administrator. Minimum 8 characters and maximum 128 characters. Password must contain characters from three of the following categories: English uppercase letters, English lowercase letters, numbers, and non-alphanumeric characters.')
            c.argument('ssl_enforcement', arg_type=get_enum_type(['Enabled', 'Disabled']), options_list=['--ssl-enforcement'], help='Enable or disable ssl enforcement for connections to server. Default is Enabled.')
            c.argument('tier', arg_type=get_enum_type(['Basic', 'GeneralPurpose', 'MemoryOptimized']), options_list=['--performance-tier'], help='The performance tier of the server.')
            c.argument('capacity', options_list=['--vcore'], type=int, help='Number of vcore.')
            c.argument('family', options_list=['--family'], arg_type=get_enum_type(['Gen4', 'Gen5']), help='Hardware generation.')
            c.argument('storage_mb', options_list=['--storage-size'], type=int, help='The storage capacity of the server (unit is megabytes). Minimum 5120 and increases in 1024 increments. Default is 51200.')
            c.argument('backup_retention', options_list=['--backup-retention'], type=int, help='The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.', validator=retention_validator)
            c.argument('tags', tags_type)

    for scope in ['mariadb server-logs', 'mysql server-logs', 'postgres server-logs']:
        with self.argument_context(scope) as c:
            c.argument('file_name', options_list=['--name', '-n'], nargs='+', help='Space-separated list of log filenames on the server to download.')
            c.argument('max_file_size', type=int, help='The file size limitation to filter files.')
            c.argument('file_last_written', type=int, help='Integer in hours to indicate file last modify time, default value is 72.')
            c.argument('filename_contains', help='The pattern that file name should match.')

    for scope in ['mariadb db', 'mysql db', 'postgres db']:
        with self.argument_context(scope) as c:
            c.argument('database_name', options_list=['--name', '-n'])

    for scope in ['mariadb server firewall-rule', 'mysql server firewall-rule', 'postgres server firewall-rule']:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('firewall_rule_name', options_list=['--name', '-n'], id_part='child_name_1', help='The name of the firewall rule.')
            c.argument('start_ip_address', options_list=['--start-ip-address'], help='The start IP address of the firewall rule. Must be IPv4 format. Use value \'0.0.0.0\' to represent all Azure-internal IP addresses.')
            c.argument('end_ip_address', options_list=['--end-ip-address'], help='The end IP address of the firewall rule. Must be IPv4 format. Use value \'0.0.0.0\' to represent all Azure-internal IP addresses.')

    for scope in ['mariadb server vnet-rule', 'mysql server vnet-rule', 'postgres server vnet-rule']:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('virtual_network_rule_name', options_list=['--name', '-n'], id_part='child_name_1', help='The name of the vnet rule.')
            c.argument('virtual_network_subnet_id', options_list=['--subnet'], help='Name or ID of the subnet that allows access to an Azure Postgres Server. If subnet name is provided, --vnet-name must be provided.')
            c.argument('ignore_missing_vnet_service_endpoint', options_list=['--ignore-missing-endpoint', '-i'], help='Create vnet rule before virtual network has vnet service endpoint enabled', arg_type=get_three_state_flag())

    for scope in ['mariadb server vnet-rule create', 'mariadb server vnet-rule update', 'postgres server vnet-rule create', 'postgres server vnet-rule update', 'mysql server vnet-rule create', 'mysql server vnet-rule update']:
        with self.argument_context(scope) as c:
            c.extra('vnet_name', options_list=['--vnet-name'], help='The virtual network name', validator=validate_subnet)

    for scope in ['mariadb server configuration', 'mysql server configuration', 'postgres server configuration']:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('configuration_name', id_part='child_name_1', options_list=['--name', '-n'])

    with self.argument_context('postgres server replica list') as c:
        c.argument('server_name', options_list=['--server-name', '-s'], help='Name of the master server.')

    with self.argument_context('mysql server replica list') as c:
        c.argument('server_name', options_list=['--server-name', '-s'], help='Name of the master server.')
Example #49
0
def load_arguments(self, _):

    with self.argument_context('sql') as c:
        c.argument('location_name', arg_type=get_location_type(self.cli_ctx))
        c.argument('usage_name', options_list=['--usage', '-u'])

    with self.argument_context('sql db') as c:
        c.argument('server_name',
                   arg_type=server_param_type,
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')

        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help='Name of the Azure SQL Database.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

        c.argument('elastic_pool_name', options_list=['--elastic-pool'])
        c.argument('requested_service_objective_name', options_list=['--service-objective'])
        c.argument('max_size_bytes', options_list=['--max-size'],
                   type=SizeWithUnitConverter('B', result_type=int),
                   help='The max storage size of the database. Only the following'
                   ' sizes are supported (in addition to limitations being placed on'
                   ' each edition): 100MB, 500MB, 1GB, 5GB, 10GB, 20GB,'
                   ' 30GB, 150GB, 200GB, 500GB. If no unit is specified, defaults to bytes (B).')

        # Adjust help text.
        c.argument('edition',
                   options_list=['--edition'],
                   help='The edition of the database.')

        c.argument('zone_redundant',
                   options_list=['--zone-redundant', '-z'],
                   help='Specifies whether to enable zone redundancy for the database.',
                   arg_type=get_three_state_flag())

    with self.argument_context('sql db create') as c:
        _configure_db_create_params(c, Engine.db, CreateMode.default)

    with self.argument_context('sql db copy') as c:
        _configure_db_create_params(c, Engine.db, CreateMode.copy)

        c.argument('elastic_pool_name',
                   help='Name of the elastic pool to create the new database in.')

        c.argument('dest_name',
                   help='Name of the database that will be created as the copy destination.')

        c.argument('dest_resource_group_name',
                   options_list=['--dest-resource-group'],
                   help='Name of the resouce group to create the copy in.'
                   ' If unspecified, defaults to the origin resource group.')

        c.argument('dest_server_name',
                   options_list=['--dest-server'],
                   help='Name of the server to create the copy in.'
                   ' If unspecified, defaults to the origin server.')

        c.argument('requested_service_objective_name',
                   options_list=['--service-objective'],
                   help='Name of the service objective for the new database.')

    with self.argument_context('sql db rename') as c:
        c.argument('new_name',
                   help='The new name that the database will be renamed to.')

    with self.argument_context('sql db restore') as c:
        _configure_db_create_params(c, Engine.db, CreateMode.point_in_time_restore)

        c.argument('dest_name',
                   help='Name of the database that will be created as the restore destination.')

        restore_point_arg_group = 'Restore Point'

        c.argument('restore_point_in_time',
                   options_list=['--time', '-t'],
                   arg_group=restore_point_arg_group,
                   help='The point in time of the source database that will be restored to create the'
                   ' new database. Must be greater than or equal to the source database\'s'
                   ' earliestRestoreDate value. Either --time or --deleted-time (or both) must be specified.')

        c.argument('source_database_deletion_date',
                   options_list=['--deleted-time'],
                   arg_group=restore_point_arg_group,
                   help='If specified, restore from a deleted database instead of from an existing database.'
                   ' Must match the deleted time of a deleted database in the same server.'
                   ' Either --time or --deleted-time (or both) must be specified.')

        c.argument('edition',
                   help='The edition for the new database.')
        c.argument('elastic_pool_name',
                   help='Name of the elastic pool to create the new database in.')
        c.argument('requested_service_objective_name',
                   help='Name of service objective for the new database.')

    with self.argument_context('sql db show') as c:
        # Service tier advisors and transparent data encryption are not included in the first batch
        # of GA commands.
        c.ignore('expand')

    with self.argument_context('sql db list') as c:
        c.argument('elastic_pool_name',
                   help='If specified, lists only the databases in this elastic pool')

    with self.argument_context('sql db list-editions') as c:
        c.argument('show_details',
                   options_list=['--show-details', '-d'],
                   help='List of additional details to include in output.',
                   nargs='+',
                   arg_type=get_enum_type(DatabaseCapabilitiesAdditionalDetails))

        search_arg_group = 'Search'

        # We could used get_enum_type here, but that will validate the inputs which means there
        # will be no way to query for new editions/service objectives that are made available after
        # this version of CLI is released.
        c.argument('edition',
                   arg_group=search_arg_group,
                   help='Edition to search for. If unspecified, all editions are shown.')
        c.argument('service_objective',
                   arg_group=search_arg_group,
                   help='Service objective to search for. If unspecified, all editions are shown.')

    with self.argument_context('sql db update') as c:
        c.argument('requested_service_objective_name',
                   help='The name of the new service objective. If this is a standalone db service'
                   ' objective and the db is currently in an elastic pool, then the db is removed from'
                   ' the pool.')
        c.argument('elastic_pool_name', help='The name of the elastic pool to move the database into.')
        c.argument('max_size_bytes', help='The new maximum size of the database expressed in bytes.')

    with self.argument_context('sql db export') as c:
        c.expand('parameters', ExportRequest)
        c.argument('administrator_login', options_list=['--admin-user', '-u'])
        c.argument('administrator_login_password', options_list=['--admin-password', '-p'])
        c.argument('authentication_type', options_list=['--auth-type', '-a'],
                   arg_type=get_enum_type(AuthenticationType))
        c.argument('storage_key_type', arg_type=get_enum_type(StorageKeyType))

    with self.argument_context('sql db import') as c:
        c.expand('parameters', ImportExtensionRequest)
        c.argument('administrator_login', options_list=['--admin-user', '-u'])
        c.argument('administrator_login_password', options_list=['--admin-password', '-p'])
        c.argument('authentication_type', options_list=['--auth-type', '-a'],
                   arg_type=get_enum_type(AuthenticationType))
        c.argument('storage_key_type', arg_type=get_enum_type(StorageKeyType))

        c.ignore('type')

        # The parameter name '--name' is used for 'database_name', so we need to give a different name
        # for the import extension 'name' parameter to avoid conflicts. This parameter is actually not
        # needed, but we still need to avoid this conflict.
        c.argument('name', options_list=['--not-name'], arg_type=ignore_type)

    with self.argument_context('sql db show-connection-string') as c:
        c.argument('client_provider',
                   options_list=['--client', '-c'],
                   help='Type of client connection provider.',
                   arg_type=get_enum_type(ClientType))

        auth_group = 'Authentication'

        c.argument('auth_type',
                   options_list=['--auth-type', '-a'],
                   arg_group=auth_group,
                   help='Type of authentication.',
                   arg_type=get_enum_type(ClientAuthenticationType))

    #####
    #           sql db op
    #####
    with self.argument_context('sql db op') as c:
        c.argument('database_name',
                   options_list=['--database', '-d'],
                   required=True,
                   help='Name of the Azure SQL Database.')

        c.argument('operation_id',
                   options_list=['--name', '-n'],
                   required=True,
                   help='The unique name of the operation to cancel.')

    #####
    #           sql db replica
    #####
    with self.argument_context('sql db replica create') as c:
        _configure_db_create_params(c, Engine.db, CreateMode.online_secondary)

        c.argument('elastic_pool_name',
                   options_list=['--elastic-pool'],
                   help='Name of elastic pool to create the new replica in.')

        c.argument('requested_service_objective_name',
                   options_list=['--service-objective'],
                   help='Name of service objective for the new replica.')

        c.argument('partner_resource_group_name',
                   options_list=['--partner-resource-group'],
                   help='Name of the resource group to create the new replica in.'
                   ' If unspecified, defaults to the origin resource group.')

        c.argument('partner_server_name',
                   options_list=['--partner-server'],
                   help='Name of the server to create the new replica in.')

    with self.argument_context('sql db replica set-primary') as c:
        c.argument('database_name', help='Name of the database to fail over.')
        c.argument('server_name',
                   help='Name of the server containing the secondary replica that will become'
                   ' the new primary.')
        c.argument('resource_group_name',
                   help='Name of the resource group containing the secondary replica that'
                   ' will become the new primary.')
        c.argument('allow_data_loss',
                   help='If specified, the failover operation will allow data loss.')

    with self.argument_context('sql db replica delete-link') as c:
        c.argument('partner_server_name',
                   options_list=['--partner-server'],
                   help='Name of the server that the other replica is in.')
        c.argument('partner_resource_group_name',
                   options_list=['--partner-resource-group'],
                   help='Name of the resource group that the other replica is in. If unspecified,'
                   ' defaults to the first database\'s resource group.')

    #####
    #           sql db audit-policy & threat-policy
    #####
    def _configure_security_policy_storage_params(arg_ctx):
        storage_arg_group = 'Storage'

        arg_ctx.argument('storage_account',
                         options_list=['--storage-account'],
                         arg_group=storage_arg_group,
                         help='Name of the storage account.')

        arg_ctx.argument('storage_account_access_key',
                         options_list=['--storage-key'],
                         arg_group=storage_arg_group,
                         help='Access key for the storage account.')

        arg_ctx.argument('storage_endpoint',
                         arg_group=storage_arg_group,
                         help='The storage account endpoint.')

    with self.argument_context('sql db audit-policy update') as c:
        _configure_security_policy_storage_params(c)

        policy_arg_group = 'Policy'

        c.argument('state',
                   arg_group=policy_arg_group,
                   help='Auditing policy state',
                   arg_type=get_enum_type(BlobAuditingPolicyState))

        c.argument('audit_actions_and_groups',
                   options_list=['--actions'],
                   arg_group=policy_arg_group,
                   help='List of actions and action groups to audit.',
                   nargs='+')

        c.argument('retention_days',
                   arg_group=policy_arg_group,
                   help='The number of days to retain audit logs.')

    with self.argument_context('sql db threat-policy update') as c:
        _configure_security_policy_storage_params(c)

        policy_arg_group = 'Policy'
        notification_arg_group = 'Notification'

        c.argument('state',
                   arg_group=policy_arg_group,
                   help='Threat detection policy state',
                   arg_type=get_enum_type(SecurityAlertPolicyState))

        c.argument('retention_days',
                   arg_group=policy_arg_group,
                   help='The number of days to retain threat detection logs.')

        c.argument('disabled_alerts',
                   arg_group=policy_arg_group,
                   options_list=['--disabled-alerts'],
                   help='List of disabled alerts.',
                   nargs='+')

        c.argument('email_addresses',
                   arg_group=notification_arg_group,
                   options_list=['--email-addresses'],
                   help='List of email addresses that alerts are sent to.',
                   nargs='+')

        c.argument('email_account_admins',
                   arg_group=notification_arg_group,
                   options_list=['--email-account-admins'],
                   help='Whether the alert is sent to the account administrators.',
                   arg_type=get_enum_type(SecurityAlertPolicyEmailAccountAdmins))

        # TODO: use server default

    #####
    #           sql db transparent-data-encryption
    #####
    with self.argument_context('sql db tde') as c:
        c.argument('database_name',
                   options_list=['--database', '-d'],
                   required=True,
                   help='Name of the Azure SQL Database.')

    with self.argument_context('sql db tde set') as c:
        c.argument('status',
                   options_list=['--status'],
                   required=True,
                   help='Status of the transparent data encryption.',
                   arg_type=get_enum_type(TransparentDataEncryptionStatus))

    ###############################################
    #                sql dw                       #
    ###############################################
    with self.argument_context('sql dw') as c:
        c.argument('server_name',
                   arg_type=server_param_type,
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')

        c.argument('database_name', options_list=['--name', '-n'],
                   help='Name of the data warehouse.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

        c.argument('max_size_bytes', options_list=['--max-size'],
                   type=SizeWithUnitConverter('B', result_type=int),
                   help='The max storage size of the data warehouse. If no unit is specified, defaults'
                   'to bytes (B).')

        c.argument('requested_service_objective_name',
                   options_list=['--service-objective'],
                   help='The service objective of the data warehouse.')

        c.argument('collation',
                   options_list=['--collation'],
                   help='The collation of the data warehouse.')

    with self.argument_context('sql dw create') as c:
        _configure_db_create_params(c, Engine.dw, CreateMode.default)

    with self.argument_context('sql dw show') as c:
        # Service tier advisors and transparent data encryption are not included in the first batch
        # of GA commands.
        c.ignore('expand')

    # Data Warehouse restore will not be included in the first batch of GA commands
    # (list_restore_points also applies to db, but it's not very useful. It's
    # mainly useful for dw.)
    # with ParametersContext(command='sql dw restore-point') as c:
    #     c.register_alias('database_name', ('--database', '-d'))

    ###############################################
    #                sql elastic-pool             #
    ###############################################
    with self.argument_context('sql elastic-pool') as c:
        c.argument('server_name',
                   arg_type=server_param_type,
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')

        c.argument('elastic_pool_name',
                   options_list=['--name', '-n'],
                   help='The name of the elastic pool.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

        # --db-dtu-max and --db-dtu-min were the original param names, which is consistent with the
        # underlying REST API.
        # --db-max-dtu and --db-min-dtu are aliases which are consistent with the `sql elastic-pool
        # list-editions --show-details db-max-dtu db-min-dtu` parameter values. These are more
        # consistent with other az sql commands, but the original can't be removed due to
        # compatibility.
        c.argument('database_dtu_max', options_list=['--db-dtu-max', '--db-max-dtu'])
        c.argument('database_dtu_min', options_list=['--db-dtu-min', '--db-min-dtu'])

        # --storage was the original param name, which is consistent with the underlying REST API.
        # --max-size is an alias which is consistent with the `sql elastic-pool list-editions
        # --show-details max-size` parameter value and also matches `sql db --max-size` parameter name.
        c.argument('storage_mb', options_list=['--storage', '--max-size'],
                   type=SizeWithUnitConverter('MB', result_type=int),
                   help='The max storage size of the elastic pool. If no unit is specified, defaults'
                   ' to megabytes (MB).')

        c.argument('zone_redundant',
                   options_list=['--zone-redundant', '-z'],
                   help='Specifies whether to enable zone redundancy for the elastic pool.',
                   arg_type=get_three_state_flag())

    with self.argument_context('sql elastic-pool create') as c:
        c.expand('parameters', ElasticPool)
        # We have a wrapper function that determines server location so user doesn't need to specify
        # it as param.
        c.ignore('location')

    with self.argument_context('sql elastic-pool list-editions') as c:
        # Note that `ElasticPoolCapabilitiesAdditionalDetails` intentionally match param names to
        # other commands, such as `sql elastic-pool create --db-max-dtu --db-min-dtu --max-size`.
        c.argument('show_details',
                   options_list=['--show-details', '-d'],
                   help='List of additional details to include in output.',
                   nargs='+',
                   arg_type=get_enum_type(ElasticPoolCapabilitiesAdditionalDetails))

        search_arg_group = 'Search'

        # We could used 'arg_type=get_enum_type' here, but that will validate the inputs which means there
        # will be no way to query for new editions that are made available after
        # this version of CLI is released.
        c.argument('edition',
                   arg_group=search_arg_group,
                   help='Edition to search for. If unspecified, all editions are shown.')
        c.argument('dtu',
                   arg_group=search_arg_group,
                   help='Elastic pool DTU limit to search for. If unspecified, all DTU limits are shown.')

    with self.argument_context('sql elastic-pool update') as c:
        c.argument('database_dtu_max', help='The maximum DTU any one database can consume.')
        c.argument('database_dtu_min', help='The minimum DTU all databases are guaranteed.')
        c.argument('dtu', help='TThe total shared DTU for the elastic eool.')
        c.argument('storage_mb', help='Storage limit for the elastic pool in MB.')

    #####
    #           sql elastic-pool op
    #####
    with self.argument_context('sql elastic-pool op') as c:
        c.argument('elastic_pool_name',
                   options_list=['--elastic-pool'],
                   help='Name of the Azure SQL Elastic Pool.')

        c.argument('operation_id',
                   options_list=['--name', '-n'],
                   help='The unique name of the operation to cancel.')

    ###############################################
    #                sql server                   #
    ###############################################
    with self.argument_context('sql server') as c:
        c.argument('server_name', options_list=['--name', '-n'],
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')
        c.argument('administrator_login', options_list=['--admin-user', '-u'])
        c.argument('administrator_login_password', options_list=['--admin-password', '-p'])

    with self.argument_context('sql server create') as c:
        # Both administrator_login and administrator_login_password are required for server creation.
        # However these two parameters are given default value in the create_or_update function
        # signature, therefore, they can't be automatically converted to requirement arguments.
        c.expand('parameters', Server, patches={
            'administrator_login': patch_arg_make_required,
            'administrator_login_password': patch_arg_make_required
        })

        c.argument('assign_identity',
                   options_list=['--assign-identity', '-i'],
                   help='Generate and assign an Azure Active Directory Identity for this server'
                   'for use with key management services like Azure KeyVault.')

        # 12.0 is the only server version allowed and it's already the default.
        c.ignore('version')

        # Identity will be handled with its own parameter.
        c.ignore('identity')

    with self.argument_context('sql server update') as c:
        c.argument('administrator_login_password', help='The administrator login password.')
        c.argument('assign_identity',
                   options_list=['--assign_identity', '-i'],
                   help='Generate and assign an Azure Active Directory Identity for this server'
                   'for use with key management services like Azure KeyVault.')

    #####
    #           sql server ad-admin
    ######
    with self.argument_context('sql server ad-admin') as c:
        c.argument('server_name', options_list=['--server-name', '-s'],
                   help='The name of the SQL Server')
        c.argument('login', options_list=['--display-name', '-u'],
                   help='Display name of the Azure AD administrator user or group.')
        c.argument('sid', options_list=['--object-id', '-i'],
                   help='The unique ID of the Azure AD administrator ')
        c.ignore('tenant_id')

    with self.argument_context('sql server ad-admin create') as c:
        c.expand('properties', ServerAzureADAdministrator, patches={
            'tenant_id': patch_arg_make_optional})

    #####
    #           sql server conn-policy
    #####
    with self.argument_context('sql server conn-policy') as c:
        c.argument('server_name', arg_type=server_param_type)
        c.argument('connection_type', options_list=['--connection-type', '-t'],
                   arg_type=get_enum_type(ServerConnectionType))

    #####
    #           sql server dns-alias
    #####
    with self.argument_context('sql server dns-alias') as c:
        c.argument('server_name', arg_type=server_param_type)
        c.argument('dns_alias_name', options_list=('--name', '-n'))
        c.argument('original_server_name', options_list=('--original-server'),
                   help='The name of the server to which alias is currently pointing')
        c.argument('original_resource_group_name', options_list=('--original-resource-group'))
        c.argument('original_subscription_id', options_list=('--original-subscription-id'))

    #####
    #           sql server firewall-rule
    #####
    with self.argument_context('sql server firewall-rule') as c:
        # Help text needs to be specified because 'sql server firewall-rule update' is a custom
        # command.
        c.argument('server_name',
                   arg_type=server_param_type,
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')

        c.argument('firewall_rule_name',
                   options_list=['--name', '-n'],
                   help='The name of the firewall rule.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

        c.argument('start_ip_address',
                   options_list=['--start-ip-address'],
                   help='The start IP address of the firewall rule. Must be IPv4 format. Use value'
                   ' \'0.0.0.0\' to represent all Azure-internal IP addresses.')

        c.argument('end_ip_address',
                   options_list=['--end-ip-address'],
                   help='The end IP address of the firewall rule. Must be IPv4 format. Use value'
                   ' \'0.0.0.0\' to represent all Azure-internal IP addresses.')

    #####
    #           sql server key
    #####
    with self.argument_context('sql server key') as c:
        c.argument('server_name', arg_type=server_param_type)
        c.argument('key_name', options_list=['--name', '-n'])
        c.argument('kid',
                   options_list=['--kid', '-k'],
                   required=True,
                   help='The Azure Key Vault key identifier of the server key. An example key identifier is '
                   '"https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901"')

    #####
    #           sql server tde-key
    #####
    with self.argument_context('sql server tde-key') as c:
        c.argument('server_name', arg_type=server_param_type)

    with self.argument_context('sql server tde-key set') as c:
        c.argument('kid',
                   options_list=['--kid', '-k'],
                   help='The Azure Key Vault key identifier of the server key to be made encryption protector.'
                   'An example key identifier is '
                   '"https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901"')
        c.argument('server_key_type',
                   options_list=['--server-key-type', '-t'],
                   help='The type of the server key',
                   arg_type=get_enum_type(ServerKeyType))

    #####
    #           sql server vnet-rule
    #####
    with self.argument_context('sql server vnet-rule') as c:
        # Help text needs to be specified because 'sql server vnet-rule create' is a custom
        # command.
        c.argument('server_name',
                   options_list=['--server', '-s'],
                   completer=get_resource_name_completion_list('Microsoft.SQL/servers'))

        c.argument('virtual_network_rule_name',
                   options_list=['--name', '-n'])

        c.argument('virtual_network_subnet_id',
                   options_list=['--subnet'],
                   help='Name or ID of the subnet that allows access to an Azure Sql Server. '
                   'If subnet name is provided, --vnet-name must be provided.')

        c.argument('ignore_missing_vnet_service_endpoint',
                   options_list=['--ignore-missing-endpoint', '-i'],
                   help='Create firewall rule before the virtual network has vnet service endpoint enabled',
                   arg_type=get_three_state_flag())

    with self.argument_context('sql server vnet-rule create') as c:
        c.extra('vnet_name', options_list=['--vnet-name'], help='The virtual network name')
Example #50
0
def load_arguments(self, _):
    from knack.arguments import CLIArgumentType
    from azure.mgmt.cosmosdb.models import KeyKind, DefaultConsistencyLevel, DatabaseAccountKind, TriggerType, TriggerOperation, ServerVersion, NetworkAclBypass

    with self.argument_context('cosmosdb') as c:
        c.argument('account_name',
                   arg_type=name_type,
                   help='Name of the Cosmos DB database account',
                   completer=get_resource_name_completion_list(
                       'Microsoft.DocumentDb/databaseAccounts'),
                   id_part='name')
        c.argument('database_id',
                   options_list=['--db-name', '-d'],
                   help='Database Name')

    with self.argument_context('cosmosdb create') as c:
        c.argument('account_name', completer=None)
        c.argument('key_uri', help="The URI of the key vault", is_preview=True)
        c.argument('enable_free_tier',
                   arg_type=get_three_state_flag(),
                   help="If enabled the account is free-tier.",
                   is_preview=True)
        c.argument(
            'assign_identity',
            nargs='*',
            help=
            "accept system or user assigned identities separated by spaces. Use '[system]' to refer system assigned identity. Currently only system assigned identity is supported.",
            is_preview=True)

    for scope in ['cosmosdb create', 'cosmosdb update']:
        with self.argument_context(scope) as c:
            c.ignore('resource_group_location')
            c.argument('locations', nargs='+', action=CreateLocation)
            c.argument('tags', arg_type=tags_type)
            c.argument(
                'default_consistency_level',
                arg_type=get_enum_type(DefaultConsistencyLevel),
                help=
                "default consistency level of the Cosmos DB database account")
            c.argument(
                'max_staleness_prefix',
                type=int,
                help=
                "when used with Bounded Staleness consistency, this value represents the number of stale requests tolerated. Accepted range for this value is 1 - 2,147,483,647"
            )
            c.argument(
                'max_interval',
                type=int,
                help=
                "when used with Bounded Staleness consistency, this value represents the time amount of staleness (in seconds) tolerated. Accepted range for this value is 1 - 100"
            )
            c.argument(
                'ip_range_filter',
                nargs='+',
                options_list=['--ip-range-filter'],
                validator=validate_ip_range_filter,
                help=
                "firewall support. Specifies the set of IP addresses or IP address ranges in CIDR form to be included as the allowed list of client IPs for a given database account. IP addresses/ranges must be comma-separated and must not contain any spaces"
            )
            c.argument('kind',
                       arg_type=get_enum_type(DatabaseAccountKind),
                       help='The type of Cosmos DB database account to create')
            c.argument(
                'enable_automatic_failover',
                arg_type=get_three_state_flag(),
                help=
                'Enables automatic failover of the write region in the rare event that the region is unavailable due to an outage. Automatic failover will result in a new write region for the account and is chosen based on the failover priorities configured for the account.'
            )
            c.argument(
                'capabilities',
                nargs='+',
                validator=validate_capabilities,
                help=
                'set custom capabilities on the Cosmos DB database account.')
            c.argument(
                'enable_virtual_network',
                arg_type=get_three_state_flag(),
                help='Enables virtual network on the Cosmos DB database account'
            )
            c.argument('virtual_network_rules',
                       nargs='+',
                       validator=validate_virtual_network_rules,
                       help='ACL\'s for virtual network')
            c.argument('enable_multiple_write_locations',
                       arg_type=get_three_state_flag(),
                       help="Enable Multiple Write Locations")
            c.argument(
                'disable_key_based_metadata_write_access',
                arg_type=get_three_state_flag(),
                help=
                "Disable write operations on metadata resources (databases, containers, throughput) via account keys"
            )
            c.argument(
                'enable_public_network',
                options_list=['--enable-public-network', '-e'],
                arg_type=get_three_state_flag(),
                help="Enable or disable public network access to server.")
            c.argument('enable_analytical_storage',
                       arg_type=get_three_state_flag(),
                       help="Flag to enable log storage on the account.",
                       is_preview=True)
            c.argument('network_acl_bypass',
                       arg_type=get_enum_type(NetworkAclBypass),
                       options_list=['--network-acl-bypass'],
                       help="Flag to enable or disable Network Acl Bypass.")
            c.argument(
                'network_acl_bypass_resource_ids',
                nargs='+',
                options_list=['--network-acl-bypass-resource-ids', '-i'],
                help="List of Resource Ids to allow Network Acl Bypass.")
            c.argument(
                'backup_interval',
                type=int,
                help=
                "the frequency(in minutes) with which backups are taken (only for accounts with periodic mode backups)",
                arg_group='Backup Policy')
            c.argument(
                'backup_retention',
                type=int,
                help=
                "the time(in hours) for which each backup is retained (only for accounts with periodic mode backups)",
                arg_group='Backup Policy')
            c.argument('server_version',
                       arg_type=get_enum_type(ServerVersion),
                       help="Valid only for MongoDB accounts.",
                       is_preview=True)
            c.argument(
                'default_identity',
                help=
                "The primary identity to access key vault in CMK related features. e.g. 'FirstPartyIdentity', 'SystemAssignedIdentity' and more.",
                is_preview=True)

    for scope in ['cosmosdb regenerate-key', 'cosmosdb keys regenerate']:
        with self.argument_context(scope) as c:
            c.argument('key_kind',
                       arg_type=get_enum_type(KeyKind),
                       help="The access key to regenerate.")

    with self.argument_context('cosmosdb failover-priority-change') as c:
        c.argument(
            'failover_parameters',
            options_list=['--failover-policies'],
            validator=validate_failover_policies,
            help=
            "space-separated failover policies in 'regionName=failoverPriority' format. E.g eastus=0 westus=1",
            nargs='+')

    with self.argument_context('cosmosdb network-rule list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('cosmosdb keys list') as c:
        c.argument('account_name', help="Cosmosdb account name", id_part=None)
        c.argument('key_type',
                   arg_type=get_enum_type(CosmosKeyTypes),
                   options_list=['--type'],
                   help="The type of account key.")

    with self.argument_context('cosmosdb network-rule add') as c:
        c.argument('subnet', help="Name or ID of the subnet")
        c.argument(
            'virtual_network',
            options_list=['--vnet-name', '--virtual-network'],
            help=
            "The name of the VNET, which must be provided in conjunction with the name of the subnet"
        )
        c.argument(
            "ignore_missing_vnet_service_endpoint",
            options_list=[
                '--ignore-missing-endpoint',
                '--ignore-missing-vnet-service-endpoint'
            ],
            arg_type=get_three_state_flag(),
            help=
            "Create firewall rule before the virtual network has vnet service endpoint enabled."
        )

    with self.argument_context('cosmosdb network-rule remove') as c:
        c.argument('subnet', help="Name or ID of the subnet")
        c.argument(
            'virtual_network',
            options_list=['--vnet-name', '--virtual-network'],
            help=
            "The name of the VNET, which must be provided in conjunction with the name of the subnet"
        )

    with self.argument_context('cosmosdb collection') as c:
        c.argument('collection_id',
                   options_list=['--collection-name', '-c'],
                   help='Collection Name')
        c.argument('throughput', type=int, help='Offer Throughput (RU/s)')
        c.argument('partition_key_path',
                   help='Partition Key Path, e.g., \'/properties/name\'')
        c.argument(
            'indexing_policy',
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexing Policy, you can enter it as a string or as a file, e.g., --indexing-policy @policy-file.json)'
        )
        c.argument('default_ttl',
                   type=int,
                   help='Default TTL. Provide 0 to disable.')

    with self.argument_context('cosmosdb database') as c:
        c.argument('throughput', type=int, help='Offer Throughput (RU/s)')

    account_name_type = CLIArgumentType(options_list=['--account-name', '-a'],
                                        help="Cosmosdb account name.")
    database_name_type = CLIArgumentType(
        options_list=['--database-name', '-d'], help='Database name.')
    container_name_type = CLIArgumentType(
        options_list=['--container-name', '-c'], help='Container name.')
    max_throughput_type = CLIArgumentType(
        options_list=['--max-throughput'],
        help=
        'The maximum throughput resource can scale to (RU/s). Provided when the resource is autoscale enabled. The minimum value can be 4000 (RU/s)'
    )
    throughput_type = CLIArgumentType(
        options_list=['--throughput-type', '-t'],
        arg_type=get_enum_type(ThroughputTypes),
        help='The type of throughput to migrate to.')

    with self.argument_context('cosmosdb private-endpoint-connection') as c:
        c.argument(
            'private_endpoint_connection_name',
            options_list=['--name', '-n'],
            required=False,
            help=
            'The name of the private endpoint connection associated with Azure Cosmos DB. '
            'Required if --connection-id is not specified')
        c.argument(
            'account_name',
            account_name_type,
            required=False,
            help=
            'Name of the Cosmos DB database account. Required if --connection-id is not specified'
        )
        c.argument(
            'resource_group_name',
            required=False,
            help=
            'The resource group name of specified Cosmos DB account. Required if --connection-id is not specified'
        )

    for item in ['approve', 'reject', 'delete', 'show']:
        with self.argument_context(
                'cosmosdb private-endpoint-connection {}'.format(item)) as c:
            c.extra(
                'connection_id',
                options_list=['--id'],
                required=False,
                help=
                'The ID of the private endpoint connection associated with Azure Cosmos DB. '
                'If specified --account-name --resource-group/-g and --name/-n, this should be omitted.'
            )
            c.argument('description',
                       options_list=['--description'],
                       required=False,
                       help='Comments for the {} operation.'.format(item))

    with self.argument_context('cosmosdb private-link-resource') as c:
        c.argument('account_name',
                   account_name_type,
                   required=True,
                   help="Cosmosdb account name",
                   id_part=None)

# SQL database
    with self.argument_context('cosmosdb sql database') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument(
            'throughput',
            help='The throughput of SQL database (RU/s). Default value is 400')
        c.argument('max_throughput', max_throughput_type)

# SQL container
    with self.argument_context('cosmosdb sql container') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name',
                   options_list=['--name', '-n'],
                   help="Container name")
        c.argument('partition_key_path',
                   options_list=['--partition-key-path', '-p'],
                   help='Partition Key Path, e.g., \'/address/zipcode\'')
        c.argument('partition_key_version',
                   type=int,
                   options_list=['--partition-key-version'],
                   help='The version of partition key.')
        c.argument(
            'default_ttl',
            options_list=['--ttl'],
            type=int,
            help=
            'Default TTL. If the value is missing or set to "-1", items don’t expire. If the value is set to "n", items will expire "n" seconds after last modified time.'
        )
        c.argument(
            'indexing_policy',
            options_list=['--idx'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexing Policy, you can enter it as a string or as a file, e.g., --idx @policy-file.json or '
            + SQL_GREMLIN_INDEXING_POLICY_EXAMPLE)
        c.argument(
            'unique_key_policy',
            options_list=['--unique-key-policy', '-u'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Unique Key Policy, you can enter it as a string or as a file, e.g., --unique-key-policy @policy-file.json or '
            + SQL_UNIQUE_KEY_POLICY_EXAMPLE)
        c.argument(
            'conflict_resolution_policy',
            options_list=['--conflict-resolution-policy', '-c'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Conflict Resolution Policy, you can enter it as a string or as a file, e.g., --conflict-resolution-policy @policy-file.json or '
            + SQL_GREMLIN_CONFLICT_RESOLUTION_POLICY_EXAMPLE)
        c.argument('max_throughput', max_throughput_type)
        c.argument(
            'throughput',
            help=
            'The throughput of SQL container (RU/s). Default value is 400. Omit this parameter if the database has shared throughput unless the container should have dedicated throughput.'
        )
        c.argument('analytical_storage_ttl',
                   options_list=['--analytical-storage-ttl', '-t'],
                   type=int,
                   help='Analytical TTL, when analytical storage is enabled.')

# SQL stored procedure
    with self.argument_context('cosmosdb sql stored-procedure') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name', container_name_type)
        c.argument('stored_procedure_name',
                   options_list=['--name', '-n'],
                   help="StoredProcedure name")
        c.argument(
            'stored_procedure_body',
            options_list=['--body', '-b'],
            completer=FilesCompleter(),
            help=
            "StoredProcedure body, you can enter it as a string or as a file, e.g., --body @sprocbody-file.json"
        )

# SQL trigger
    with self.argument_context('cosmosdb sql trigger') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name', container_name_type)
        c.argument('trigger_name',
                   options_list=['--name', '-n'],
                   help="Trigger name")
        c.argument(
            'trigger_body',
            options_list=['--body', '-b'],
            completer=FilesCompleter(),
            help=
            "Trigger body, you can enter it as a string or as a file, e.g., --body @triggerbody-file.json"
        )
        c.argument('trigger_type',
                   options_list=['--type', '-t'],
                   arg_type=get_enum_type(TriggerType),
                   help="Trigger type")
        c.argument('trigger_operation',
                   options_list=['--operation'],
                   arg_type=get_enum_type(TriggerOperation),
                   help="The operation of the trigger.")

# SQL user defined function
    with self.argument_context('cosmosdb sql user-defined-function') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name', container_name_type)
        c.argument('user_defined_function_name',
                   options_list=['--name', '-n'],
                   help="UserDefinedFunction name")
        c.argument(
            'user_defined_function_body',
            options_list=['--body', '-b'],
            completer=FilesCompleter(),
            help=
            "UserDefinedFunction body, you can enter it as a string or as a file, e.g., --body @udfbody-file.json"
        )

# MongoDB
    with self.argument_context('cosmosdb mongodb database') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument(
            'throughput',
            help=
            'The throughput of MongoDB database (RU/s). Default value is 400')
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb mongodb collection') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('collection_name',
                   options_list=['--name', '-n'],
                   help="Collection name")
        c.argument('shard_key_path',
                   options_list=['--shard'],
                   help="Sharding key path.")
        c.argument(
            'indexes',
            options_list=['--idx'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexes, you can enter it as a string or as a file, e.g., --idx @indexes-file.json or '
            + MONGODB_INDEXES_EXAMPLE)
        c.argument('max_throughput', max_throughput_type)
        c.argument('analytical_storage_ttl',
                   type=int,
                   help='Analytical TTL, when analytical storage is enabled.')
        c.argument(
            'throughput',
            help=
            'The throughput of MongoDB collection (RU/s). Default value is 400. Omit this parameter if the database has shared throughput unless the collection should have dedicated throughput.'
        )

# Cassandra
    with self.argument_context('cosmosdb cassandra keyspace') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('keyspace_name',
                   options_list=['--name', '-n'],
                   help="Keyspace name")
        c.argument(
            'throughput',
            help=
            'The throughput of Cassandra keyspace (RU/s). Default value is 400'
        )
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb cassandra table') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('keyspace_name',
                   options_list=['--keyspace-name', '-k'],
                   help="Keyspace name")
        c.argument('table_name',
                   options_list=['--name', '-n'],
                   help="Table name")
        c.argument(
            'default_ttl',
            options_list=['--ttl'],
            type=int,
            help=
            'Default TTL. If the value is missing or set to "-1", items don’t expire. If the value is set to "n", items will expire "n" seconds after last modified time.'
        )
        c.argument(
            'schema',
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Schema, you can enter it as a string or as a file, e.g., --schema @schema-file.json or '
            + CASSANDRA_SCHEMA_EXAMPLE)
        c.argument('max_throughput', max_throughput_type)
        c.argument('analytical_storage_ttl',
                   type=int,
                   help='Analytical TTL, when analytical storage is enabled.')
        c.argument(
            'throughput',
            help=
            'The throughput of Cassandra table (RU/s). Default value is 400. Omit this parameter if the keyspace has shared throughput unless the table should have dedicated throughput.'
        )

# Gremlin
    with self.argument_context('cosmosdb gremlin database') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument(
            'throughput',
            help='The throughput Gremlin database (RU/s). Default value is 400'
        )
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb gremlin graph') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('graph_name',
                   options_list=['--name', '-n'],
                   help="Graph name")
        c.argument('partition_key_path',
                   options_list=['--partition-key-path', '-p'],
                   help='Partition Key Path, e.g., \'/address/zipcode\'')
        c.argument(
            'default_ttl',
            options_list=['--ttl'],
            type=int,
            help=
            'Default TTL. If the value is missing or set to "-1", items don’t expire. If the value is set to "n", items will expire "n" seconds after last modified time.'
        )
        c.argument(
            'indexing_policy',
            options_list=['--idx'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexing Policy, you can enter it as a string or as a file, e.g., --idx @policy-file.json or '
            + SQL_GREMLIN_INDEXING_POLICY_EXAMPLE)
        c.argument(
            'conflict_resolution_policy',
            options_list=['--conflict-resolution-policy', '-c'],
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Conflict Resolution Policy, you can enter it as a string or as a file, e.g., --conflict-resolution-policy @policy-file.json or '
            + SQL_GREMLIN_CONFLICT_RESOLUTION_POLICY_EXAMPLE)
        c.argument('max_throughput', max_throughput_type)
        c.argument(
            'throughput',
            help=
            'The throughput of Gremlin graph (RU/s). Default value is 400. Omit this parameter if the database has shared throughput unless the graph should have dedicated throughput.'
        )

# Table
    with self.argument_context('cosmosdb table') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('table_name',
                   options_list=['--name', '-n'],
                   help="Table name")
        c.argument('throughput',
                   help='The throughput of Table (RU/s). Default value is 400')
        c.argument('max_throughput', max_throughput_type)

# Throughput
    with self.argument_context('cosmosdb sql database throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of SQL database (RU/s).')
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb sql container throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('container_name',
                   options_list=['--name', '-n'],
                   help="Container name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of SQL container (RU/s).')
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb mongodb database throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of MongoDB database (RU/s).')
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb mongodb collection throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('collection_name',
                   options_list=['--name', '-n'],
                   help="Collection name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of MongoDB collection (RU/s).')
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb cassandra keyspace throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('keyspace_name',
                   options_list=['--name', '-n'],
                   help="Keyspace name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of Cassandra keyspace (RU/s).')
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb cassandra table throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('keyspace_name',
                   options_list=['--keyspace-name', '-k'],
                   help="Keyspace name")
        c.argument('table_name',
                   options_list=['--name', '-n'],
                   help="Table name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of Cassandra table (RU/s).')
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb gremlin database throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name',
                   options_list=['--name', '-n'],
                   help="Database name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of Gremlin database (RU/s).')
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb gremlin graph throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('graph_name',
                   options_list=['--name', '-n'],
                   help="Graph name")
        c.argument('throughput',
                   type=int,
                   help='The throughput Gremlin graph (RU/s).')
        c.argument('max_throughput', max_throughput_type)

    with self.argument_context('cosmosdb table throughput') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('table_name',
                   options_list=['--name', '-n'],
                   help="Table name")
        c.argument('throughput',
                   type=int,
                   help='The throughput of Table (RU/s).')
        c.argument('max_throughput', max_throughput_type)

    for scope in [
            'sql database throughput migrate',
            'sql container throughput migrate',
            'gremlin database throughput migrate',
            'gremlin graph throughput migrate',
            'cassandra table throughput migrate',
            'cassandra keyspace throughput migrate',
            'mongodb collection throughput migrate',
            'mongodb database throughput migrate', 'table throughput migrate'
    ]:
        with self.argument_context('cosmosdb {}'.format(scope)) as c:
            c.argument('throughput_type', throughput_type)
Example #51
0
def load_arguments(self, _):

    # ACS command argument configuration
    with self.argument_context('acs') as c:
        c.argument('resource_name', name_type,
                   completer=get_resource_name_completion_list('Microsoft.ContainerService/ContainerServices'),
                   help='Name of the container service. You can configure the default using `az configure --defaults acs=<name>`')
        c.argument('name', name_type,
                   completer=get_resource_name_completion_list('Microsoft.ContainerService/ContainerServices'),
                   help='Name of the container service. You can configure the default using `az configure --defaults acs=<name>`')
        c.argument('container_service_name', name_type, help='Name of the container service. You can configure the default using `az configure --defaults acs=<name>`',
                   completer=get_resource_name_completion_list('Microsoft.ContainerService/ContainerServices'))
        c.argument('admin_username', options_list=['--admin-username', '-u'], default='azureuser')
        c.argument('api_version',
                   help=_get_feature_in_preview_message() + 'Use API version of ACS to perform az acs operations. Available options: 2017-01-31, 2017-07-01. Default: the latest version for the location')
        c.argument('dns_name_prefix', options_list=['--dns-prefix', '-d'])
        c.argument('orchestrator_type', get_enum_type(orchestrator_types), options_list=['--orchestrator-type', '-t'])
        c.argument('ssh_key_value', required=False, type=file_type, default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(), validator=validate_ssh_key)
        c.argument('tags', tags_type)
        c.argument('disable_browser', help='Do not open browser after opening a proxy to the cluster web user interface')

    with self.argument_context('acs create') as c:
        c.argument('ssh_key_value', required=False, type=file_type, default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(), validator=validate_ssh_key)
        c.argument('master_profile', options_list=['--master-profile', '-m'], type=validate_file_or_dict,
                   help=_get_feature_in_preview_message() + 'The file or dictionary representation of the master profile. Note it will override any master settings once set')
        c.argument('master_vm_size', completer=get_vm_size_completion_list, help=_get_feature_in_preview_message())
        c.argument('agent_count', type=int)
        c.argument('generate_ssh_keys', action='store_true', validator=validate_create_parameters,
                   help='Generate SSH public and private key files if missing')
        c.argument('master_osdisk_size', type=int,
                   help=_get_feature_in_preview_message() + 'The disk size for master pool vms. Unit in GB. Default: corresponding vmsize disk size')
        c.argument('master_vnet_subnet_id', type=str,
                   help=_get_feature_in_preview_message() + 'The custom vnet subnet id. Note agent need to used the same vnet if master set. Default: ""')
        c.argument('master_first_consecutive_static_ip', type=str,
                   help=_get_feature_in_preview_message() + 'The first consecutive ip used to specify static ip block.')
        c.argument('master_storage_profile', get_enum_type(storage_profile_types),
                   help=_get_feature_in_preview_message() + 'Default: varies based on Orchestrator')
        c.argument('agent_profiles', options_list=['--agent-profiles', '-a'], type=validate_file_or_dict,
                   help=_get_feature_in_preview_message() + 'The file or dictionary representation of the agent profiles. Note it will override any agent settings once set')
        c.argument('agent_vm_size', completer=get_vm_size_completion_list,
                   help='Set the default size for agent pools vms.')
        c.argument('agent_osdisk_size', type=int,
                   help=_get_feature_in_preview_message() + 'Set the default disk size for agent pools vms. Unit in GB. Default: corresponding vmsize disk size')
        c.argument('agent_vnet_subnet_id', type=str,
                   help=_get_feature_in_preview_message() + 'Set the default custom vnet subnet id for agent pools. Note agent need to used the same vnet if master set. Default: ""')
        c.argument('agent_ports', type=validate_list_of_integers,
                   help=_get_feature_in_preview_message() + 'Set the default ports exposed on the agent pools. Only usable for non-Kubernetes. Default: 8080,4000,80')
        c.argument('agent_storage_profile', get_enum_type(storage_profile_types),
                   help=_get_feature_in_preview_message() + 'Set default storage profile for agent pools. Default: varies based on Orchestrator')
        c.argument('windows', action='store_true',
                   help='If true, set the default osType of agent pools to be Windows.')
        c.argument('validate', action='store_true',
                   help='Generate and validate the ARM template without creating any resources')
        c.argument('orchestrator_version',
                   help=_get_feature_in_preview_message() + 'Use Orchestrator Version to specify the semantic version for your choice of orchestrator.')

    with self.argument_context('acs scale') as c:
        c.argument('new_agent_count', type=int)

    with self.argument_context('acs dcos browse') as c:
        c.argument('ssh_key_file', required=False, type=file_type, default=os.path.join('~', '.ssh', 'id_rsa'),
                   completer=FilesCompleter(), help='Path to an SSH key file to use.')

    with self.argument_context('acs dcos install-cli') as c:
        c.argument('install_location', default=_get_default_install_location('dcos'))

    with self.argument_context('acs kubernetes get-credentials') as c:
        c.argument('path', options_list=['--file', '-f'])

    with self.argument_context('acs kubernetes install-cli') as c:
        c.argument('install_location', type=file_type, completer=FilesCompleter(),
                   default=_get_default_install_location('kubectl'))
        c.argument('ssh_key_file', required=False, type=file_type, default=os.path.join('~', '.ssh', 'id_rsa'),
                   completer=FilesCompleter(), help='Path to an SSH key file to use.')

    # AKS command argument configuration
    with self.argument_context('aks') as c:
        c.argument('resource_name', name_type, help='Name of the managed cluster.',
                   completer=get_resource_name_completion_list('Microsoft.ContainerService/ManagedClusters'))
        c.argument('name', name_type, help='Name of the managed cluster.',
                   completer=get_resource_name_completion_list('Microsoft.ContainerService/ManagedClusters'))
        c.argument('kubernetes_version', options_list=['--kubernetes-version', '-k'], validator=validate_k8s_version)
        c.argument('node_count', options_list=['--node-count', '-c'], type=int)
        c.argument('tags', tags_type)

    with self.argument_context('aks create') as c:
        c.argument('name', validator=validate_linux_host_name)
        c.argument('kubernetes_version', completer=get_k8s_versions_completion_list)
        c.argument('admin_username', options_list=['--admin-username', '-u'], default='azureuser')
        c.argument('dns_name_prefix', options_list=['--dns-name-prefix', '-p'])
        c.argument('generate_ssh_keys', action='store_true', validator=validate_create_parameters)
        c.argument('node_vm_size', options_list=['--node-vm-size', '-s'], completer=get_vm_size_completion_list)
        c.argument('ssh_key_value', required=False, type=file_type, default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(), validator=validate_ssh_key)

    with self.argument_context('aks get-credentials') as c:
        c.argument('admin', options_list=['--admin', '-a'], default=False)
        c.argument('path', options_list=['--file', '-f'], type=file_type, completer=FilesCompleter(),
                   default=os.path.join(os.path.expanduser('~'), '.kube', 'config'))

    with self.argument_context('aks install-cli') as c:
        c.argument('client_version', validator=validate_k8s_client_version)
        c.argument('install_location', default=_get_default_install_location('kubectl'))

    with self.argument_context('aks install-connector') as c:
        c.argument('aci_resource_group', help='The resource group to create the ACI container groups')
        c.argument('chart_url', default=aci_connector_chart_url, help='URL to the chart')
        c.argument('client_secret', help='Client secret to use with the service principal for making calls to Azure APIs')
        c.argument('connector_name', help='The name for the ACI Connector', validator=validate_connector_name)
        c.argument('image_tag', help='The image tag of the virtual kubelet')
        c.argument('location', help='The location to create the ACI container groups')
        c.argument('os_type', get_enum_type(aci_connector_os_type), help='The OS type of the connector')
        c.argument('service_principal',
                   help='Service principal for making calls into Azure APIs. If not set, auto generate a new service principal of Contributor role, and save it locally for reusing')

    with self.argument_context('aks remove-connector') as c:
        c.argument('connector_name', help='The name for the ACI Connector', validator=validate_connector_name)
        c.argument('graceful', action='store_true',
                   help='Mention if you want to drain/uncordon your aci-connector to move your applications')
        c.argument('os_type', get_enum_type(aci_connector_os_type), help='The OS type of the connector')

    with self.argument_context('aks upgrade') as c:
        c.argument('kubernetes_version', completer=get_k8s_upgrades_completion_list)

    with self.argument_context('aks upgrade-connector') as c:
        c.argument('aci_resource_group')
        c.argument('chart_url', default=aci_connector_chart_url)
        c.argument('client_secret')
        c.argument('connector_name', validator=validate_connector_name)
        c.argument('image_tag')
        c.argument('location')
        c.argument('os_type', get_enum_type(aci_connector_os_type))
        c.argument('service_principal')
Example #52
0
def load_arguments(self, _):

    AzureFirewallNetworkRuleProtocol, AzureFirewallRCActionType, AzureFirewallNatRCActionType = self.get_models(
        'AzureFirewallNetworkRuleProtocol', 'AzureFirewallRCActionType', 'AzureFirewallNatRCActionType')

    firewall_name_type = CLIArgumentType(options_list=['--firewall-name', '-f'], metavar='NAME', help='Azure Firewall name.', id_part='name', completer=get_resource_name_completion_list('Microsoft.Network/azureFirewalls'))
    collection_name_type = CLIArgumentType(options_list=['--collection-name', '-c'], help='Name of the rule collection.', id_part='child_name_1')
    virtual_network_name_type = CLIArgumentType(options_list='--vnet-name', metavar='NAME', help='The virtual network (VNet) name.', completer=get_resource_name_completion_list('Microsoft.Network/virtualNetworks'))

    # region AzureFirewalls
    with self.argument_context('network firewall') as c:
        c.argument('azure_firewall_name', firewall_name_type, options_list=['--name', '-n'], id_part='name')
        c.argument('location', get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)
        c.argument('description', help='Rule description.')
        c.argument('destination_addresses', nargs='+', help="Space-separated list of destination IP addresses. Use '*' to match all.")
        c.argument('source_addresses', nargs='+', help="Space-separated list of source IP addresses. Use '*' to match all.")
        c.argument('destination_ports', nargs='+', help="Space-separated list of destination ports. Use '*' to match all.")
        c.argument('translated_address', help='Translated address for this NAT rule.')
        c.argument('translated_port', help='Translated port for this NAT rule.')
        c.argument('tags', tags_type)

    for scope in ['network-rule', 'nat-rule']:
        with self.argument_context('network firewall {}'.format(scope)) as c:
            c.argument('protocols', arg_type=get_enum_type(AzureFirewallNetworkRuleProtocol), nargs='+', help='Space-separated list of protocols.')

    with self.argument_context('network firewall application-rule') as c:
        c.argument('target_fqdns', nargs='+', help='Space-separated list of fully qualified domain names (FDQN).')
        c.argument('fqdn_tags', nargs='+', help='Space-separated list of FQDN tags.')
        c.argument('protocols', nargs='+', validator=validate_application_rule_protocols, help='Space-separated list of protocols and port numbers to use, in PROTOCOL=PORT format. Valid protocols are Http, Https.')

    af_sub_subresources = [
        {'name': 'network-rule', 'display': 'network rule', 'ref': 'network_rule_collections'},
        {'name': 'nat-rule', 'display': 'NAT rule', 'ref': 'nat_rule_collections'},
        {'name': 'application-rule', 'display': 'application rule', 'ref': 'application_rule_collections'},
    ]
    for item in af_sub_subresources:
        with self.argument_context('network firewall {}'.format(item['name'])) as c:
            c.argument('item_name', options_list=['--name', '-n'], help='The name of the {}'.format(item['display']), completer=get_af_subresource_completion_list(item['ref']), id_part='child_name_2')
            c.argument('collection_name', collection_name_type)
            c.argument('firewall_name', firewall_name_type)
            c.argument('azure_firewall_name', firewall_name_type)

        with self.argument_context('network firewall {} list'.format(item['name'])) as c:
            c.argument('item_name', options_list=['--name', '-n'], help='The name of the {}'.format(item['display']), completer=get_af_subresource_completion_list(item['ref']), id_part='child_name_2')
            c.argument('firewall_name', firewall_name_type, id_part=None)

        with self.argument_context('network firewall {} create'.format(item['name']), arg_group='Collection') as c:
            c.argument('collection_name', collection_name_type, help='Name of the collection to create the rule in. Will create the collection if it does not exist.')
            c.argument('priority', help='Priority of the rule collection from 100 (high) to 65000 (low).', type=int)

        with self.argument_context('network firewall {} collection'.format(item['name'])) as c:
            c.argument('item_name', collection_name_type)
            c.argument('resource_name', firewall_name_type)

        with self.argument_context('network firewall {} collection list'.format(item['name'])) as c:
            c.argument('item_name', collection_name_type)
            c.argument('resource_name', firewall_name_type, id_part=None)

    for scope in ['network-rule', 'application-rule']:
        with self.argument_context('network firewall {}'.format(scope), arg_group='Collection') as c:
            c.argument('action', arg_type=get_enum_type(AzureFirewallRCActionType), help='The action to apply for the rule collection.')

    with self.argument_context('network firewall nat-rule', arg_group='Collection') as c:
        c.argument('action', arg_type=get_enum_type(AzureFirewallNatRCActionType), help='The action to apply for the rule collection.')

    with self.argument_context('network firewall ip-config') as c:
        c.argument('item_name', options_list=['--name', '-n'], help='Name of the IP configuration.', id_part='child_name_2')
        c.argument('resource_name', firewall_name_type)
        c.argument('azure_firewall_name', firewall_name_type)
        c.argument('subnet', validator=get_subnet_validator(), help=argparse.SUPPRESS)
        c.argument('virtual_network_name', virtual_network_name_type)
        c.argument('public_ip_address', help='Name or ID of the public IP to use.', validator=get_public_ip_validator())
        c.argument('private_ip_address', help='IP address used by the Firewall ILB as the next hop in User Defined Routes.')

    with self.argument_context('network firewall ip-config list') as c:
        c.argument('resource_name', firewall_name_type, id_part=None)
from azure.cli.core.commands.parameters import \
    (tags_type, location_type, resource_group_name_type, ignore_type,
     get_resource_name_completion_list, enum_choice_list, file_type)

from azure.cli.command_modules.batch._validators import \
    (application_enabled, datetime_format, storage_account_id, application_package_reference_format,
     validate_pool_resize_parameters, metadata_item_format,
     certificate_reference_format, validate_json_file, validate_cert_file, keyvault_id,
     environment_setting_format, validate_cert_settings, resource_file_format, load_node_agent_skus)

from azure.cli.command_modules.batch._command_type import validate_client_parameters

# pylint: disable=line-too-long
# ARGUMENT DEFINITIONS

batch_name_type = CliArgumentType(help='Name of the Batch account.', options_list=('--account-name',), completer=get_resource_name_completion_list('Microsoft.Batch/batchAccounts'), id_part=None)

# PARAMETER REGISTRATIONS

register_cli_argument('batch', 'resource_group_name', resource_group_name_type, help='Name of the resource group', completer=None, validator=None)
register_cli_argument('batch account', 'account_name', batch_name_type, options_list=('--name', '-n'))
register_cli_argument('batch account create', 'location', location_type, help='The region in which to create the account.')
register_cli_argument('batch account create', 'tags', tags_type, help="Space separated tags in 'key[=value]' format.")
register_cli_argument('batch account create', 'storage_account', help='The storage account name or resource ID to be used for auto storage.', validator=storage_account_id)
register_cli_argument('batch account create', 'keyvault', help='The KeyVault name or resource ID to be used for an account with a pool allocation mode of \'User Subscription\'.', validator=keyvault_id)
register_cli_argument('batch account create', 'keyvault_url', ignore_type)
register_cli_argument('batch account set', 'tags', tags_type)
register_cli_argument('batch account set', 'storage_account', help='The storage account name or resource ID to be used for auto storage.', validator=storage_account_id)
register_cli_argument('batch account keys renew', 'key_name', **enum_choice_list(AccountKeyType))
register_cli_argument('batch account login', 'shared_key_auth', action='store_true', help='Using Shared Key authentication, if not specified, it will use Azure Active Directory authentication.')
Example #54
0
    c.argument('server_key_type',
               options_list=('--server-key-type', '-t'),
               help='The type of the server key',
               **enum_choice_list(ServerKeyType))

#####
#           sql server vnet-rule
#####

with ParametersContext(command='sql server vnet-rule') as c:
    # Help text needs to be specified because 'sql server vnet-rule create' is a custom
    # command.
    c.argument(
        'server_name',
        options_list=('--server', '-s'),
        completer=get_resource_name_completion_list('Microsoft.SQL/servers'))

    c.argument('virtual_network_rule_name', options_list=('--name', '-n'))

    c.argument(
        'virtual_network_subnet_id',
        options_list=('--subnet'),
        help=
        'Name or ID of the subnet that allows access to an Azure Sql Server. '
        'If subnet name is provided, --vnet-name must be provided.')

register_extra_cli_argument('sql server vnet-rule create',
                            'vnet_name',
                            options_list=('--vnet-name'),
                            help='The virtual network name',
                            validator=validate_subnet)
Example #55
0
# --------------------------------------------------------------------------------------------
# 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
from knack.arguments import CLIArgumentType
from azure.mgmt.iotcentral.models import AppSku

from azure.cli.core.commands.parameters import (get_location_type,
                                                get_resource_name_completion_list,
                                                get_enum_type)

app_name_type = CLIArgumentType(
    completer=get_resource_name_completion_list(
        'Microsoft.IoTCentral/IoTApps'),
    help='IoT Central application name.')


def load_arguments(self, _):

    with self.argument_context('iotcentral app') as c:
        c.argument('app_name',
                   app_name_type,
                   options_list=['--name', '-n'],
                   id_part='display_name')

    with self.argument_context('iotcentral app create') as c:
        c.argument('app_name', completer=None)
        c.argument('location', get_location_type(self.cli_ctx),
                   help='Location of your IoT Central application. Default is the location of target resource group.')
Example #56
0
def load_arguments(self, _):

    from azure.mgmt.cosmosdb.models.cosmos_db_enums import KeyKind, DefaultConsistencyLevel, DatabaseAccountKind

    with self.argument_context('cosmosdb') as c:
        c.argument('account_name',
                   arg_type=name_type,
                   help='Name of the Cosmos DB database account',
                   completer=get_resource_name_completion_list(
                       'Microsoft.DocumentDb/databaseAccounts'),
                   id_part='name')
        c.argument('database_id',
                   options_list=['--db-name', '-d'],
                   help='Database Name')

    for scope in ['cosmosdb create', 'cosmosdb update']:
        with self.argument_context(scope) as c:
            c.argument('account_name', completer=None)
            c.ignore('resource_group_location')
            c.argument(
                'locations',
                nargs='+',
                validator=validate_locations,
                help=
                "space-separated locations in 'regionName=failoverPriority' format. E.g eastus=0 westus=1. Failover priority values are 0 for write regions and greater than 0 for read regions. A failover priority value must be unique and less than the total number of regions. Default: single region account in the location of the specified resource group."
            )
            c.argument('tags', arg_type=tags_type)
            c.argument(
                'default_consistency_level',
                arg_type=get_enum_type(DefaultConsistencyLevel),
                help=
                "default consistency level of the Cosmos DB database account")
            c.argument(
                'max_staleness_prefix',
                type=int,
                help=
                "when used with Bounded Staleness consistency, this value represents the number of stale requests tolerated. Accepted range for this value is 1 - 2,147,483,647"
            )
            c.argument(
                'max_interval',
                type=int,
                help=
                "when used with Bounded Staleness consistency, this value represents the time amount of staleness (in seconds) tolerated. Accepted range for this value is 1 - 100"
            )
            c.argument(
                'ip_range_filter',
                nargs='+',
                validator=validate_ip_range_filter,
                help=
                "firewall support. Specifies the set of IP addresses or IP address ranges in CIDR form to be included as the allowed list of client IPs for a given database account. IP addresses/ranges must be comma-separated and must not contain any spaces"
            )
            c.argument('kind',
                       arg_type=get_enum_type(DatabaseAccountKind),
                       help='The type of Cosmos DB database account to create')
            c.argument(
                'enable_automatic_failover',
                arg_type=get_three_state_flag(),
                help=
                'Enables automatic failover of the write region in the rare event that the region is unavailable due to an outage. Automatic failover will result in a new write region for the account and is chosen based on the failover priorities configured for the account.'
            )
            c.argument(
                'capabilities',
                nargs='+',
                validator=validate_capabilities,
                help=
                'set custom capabilities on the Cosmos DB database account.')
            c.argument(
                'enable_virtual_network',
                arg_type=get_three_state_flag(),
                help='Enables virtual network on the Cosmos DB database account'
            )
            c.argument('virtual_network_rules',
                       nargs='+',
                       validator=validate_virtual_network_rules,
                       help='ACL\'s for virtual network')

    with self.argument_context('cosmosdb regenerate-key') as c:
        c.argument('key_kind', arg_type=get_enum_type(KeyKind))

    with self.argument_context('cosmosdb failover-priority-change') as c:
        c.argument(
            'failover_policies',
            validator=validate_failover_policies,
            help=
            "space-separated failover policies in 'regionName=failoverPriority' format. E.g eastus=0 westus=1",
            nargs='+')

    with self.argument_context('cosmosdb collection') as c:
        c.argument('collection_id',
                   options_list=['--collection-name', '-c'],
                   help='Collection Name')
        c.argument('throughput', type=int, help='Offer Throughput')
        c.argument('partition_key_path',
                   help='Partition Key Path, e.g., \'/properties/name\'')
        c.argument(
            'indexing_policy',
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexing Policy, you can enter it as a string or as a file, e.g., --indexing-policy @policy-file.json)'
        )
        c.argument('default_ttl', type=int, help='Default TTL')
from azure.cli.core.commands.parameters import \
    (tags_type, get_resource_name_completion_list, resource_group_name_type, enum_choice_list)

from azure.cli.command_modules.dls._validators import validate_resource_group_name
from azure.mgmt.datalake.store.models.data_lake_store_account_management_client_enums \
    import (FirewallState,
            TrustedIdProviderState,
            TierType,
            FirewallAllowAzureIpsState)

from azure.mgmt.datalake.store.models import (EncryptionConfigType)

# ARGUMENT DEFINITIONS
# pylint: disable=line-too-long
datalake_store_name_type = CliArgumentType(help='Name of the Data Lake Store account.', options_list=('--account_name',), completer=get_resource_name_completion_list('Microsoft.DataLakeStore/accounts'), id_part='name')

# PARAMETER REGISTRATIONS
# global params
register_cli_argument('dls', 'account_name', datalake_store_name_type, options_list=('--account', '-n'))
register_cli_argument('dls', 'top', help='Maximum number of items to return.', type=int)
register_cli_argument('dls', 'skip', help='The number of items to skip over before returning elements.', type=int)
register_cli_argument('dls', 'count', help='The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true.', type=bool)
# global account params
register_cli_argument('dls account', 'tags', tags_type)
register_cli_argument('dls account', 'resource_group_name', resource_group_name_type, id_part=None, required=False, help='If not specified, will attempt to discover the resource group for the specified Data Lake Store account.', validator=validate_resource_group_name)
# account params
register_cli_argument('dls account show', 'name', datalake_store_name_type, options_list=('--account', '-n'))
register_cli_argument('dls account delete', 'name', datalake_store_name_type, options_list=('--account', '-n'))
register_cli_argument('dls account', 'tier', help='The desired commitment tier for this account to use.', **enum_choice_list(TierType))
register_cli_argument('dls account create', 'resource_group_name', resource_group_name_type, validator=None)
Example #58
0
def load_arguments(self, _):  # pylint: disable=too-many-statements
    SkuName, PasswordName, DefaultAction, PolicyStatus, WebhookAction, WebhookStatus, TaskStatus, \
        BaseImageTriggerType, RunStatus, SourceRegistryLoginMode, UpdateTriggerPayloadType, \
        TokenStatus, ZoneRedundancy = self.get_models(
            'SkuName', 'PasswordName', 'DefaultAction', 'PolicyStatus', 'WebhookAction', 'WebhookStatus',
            'TaskStatus', 'BaseImageTriggerType', 'RunStatus', 'SourceRegistryLoginMode', 'UpdateTriggerPayloadType',
            'TokenStatus', 'ZoneRedundancy')

    with self.argument_context('acr') as c:
        c.argument('tags', arg_type=tags_type)
        c.argument('registry_name', options_list=['--name', '-n'], help='The name of the container registry. You can configure the default registry name using `az configure --defaults acr=<registry name>`', completer=get_resource_name_completion_list(REGISTRY_RESOURCE_TYPE), configured_default='acr', validator=validate_registry_name)
        c.argument('tenant_suffix', options_list=['--suffix'], help="The tenant suffix in registry login server. You may specify '--suffix tenant' if your registry login server is in the format 'registry-tenant.azurecr.io'. Applicable if you\'re accessing the registry from a different subscription or you have permission to access images but not the permission to manage the registry resource.")
        c.argument('sku', help='The SKU of the container registry', arg_type=get_enum_type(SkuName))
        c.argument('admin_enabled', help='Indicates whether the admin user is enabled', arg_type=get_three_state_flag())
        c.argument('password_name', help='The name of password to regenerate', arg_type=get_enum_type(PasswordName))
        c.argument('username', options_list=['--username', '-u'], help='The username used to log into a container registry')
        c.argument('password', options_list=['--password', '-p'], help='The password used to log into a container registry')
        c.argument('yes', options_list=['--yes', '-y'], help='Do not prompt for confirmation.', action='store_true')
        c.argument('image_names', options_list=['--image', '-t'], help="The name and tag of the image using the format: '-t repo/image:tag'. Multiple tags are supported by passing -t multiple times.", action='append')
        c.argument('timeout', type=int, help='The timeout in seconds.')
        c.argument('docker_file_path', options_list=['--file', '-f'], help="The relative path of the the docker file to the source code root folder. Default to 'Dockerfile'.")
        c.argument('no_logs', help="Do not show logs after successfully queuing the build.", action='store_true')
        c.argument('no_wait', help="Do not wait for the run to complete and return immediately after queuing the run.", action='store_true')
        c.argument('no_format', help="Indicates whether the logs should be displayed in raw format", action='store_true')
        c.argument('platform', help="The platform where build/task is run, Eg, 'windows' and 'linux'. When it's used in build commands, it also can be specified in 'os/arch/variant' format for the resulting image. Eg, linux/arm/v7. The 'arch' and 'variant' parts are optional.")
        c.argument('target', help='The name of the target build stage.')
        c.argument('auth_mode', help='Auth mode of the source registry.', arg_type=get_enum_type(SourceRegistryLoginMode))
        # Overwrite default shorthand of cmd to make availability for acr usage
        c.argument('cmd', options_list=['--__cmd__'])
        c.argument('cmd_value', help="Commands to execute.", options_list=['--cmd'])
        c.argument('zone_redundancy', is_preview=True, arg_type=get_enum_type(ZoneRedundancy), help="Indicates whether or not zone redundancy should be enabled for this registry or replication. For more information, such as supported locations, please visit https://aka.ms/acr/az. Zone-redundancy cannot be updated. Defaults to 'Disabled'.")

    for scope in ['acr create', 'acr update']:
        with self.argument_context(scope, arg_group='Network Rule') as c:
            default_allow_suffix = " The Default is to allow." if "create" in scope else ""

            c.argument('default_action', arg_type=get_enum_type(DefaultAction),
                       help='Default action to apply when no rule matches. Only applicable to Premium SKU.')
            c.argument('public_network_enabled', get_three_state_flag(), help="Allow public network access for the container registry.{suffix}".format(suffix=default_allow_suffix))
            c.argument('allow_trusted_services', get_three_state_flag(), is_preview=True, help="Allow trusted Azure Services to access network restricted registries. For more information, please visit https://aka.ms/acr/trusted-services.{suffix}".format(suffix=default_allow_suffix))

    with self.argument_context('acr create', arg_group="Customer managed key") as c:
        c.argument('identity', help="Use assigned managed identity resource id or name if in the same resource group")
        c.argument('key_encryption_key', help="Key vault key uri. To enable automated rotation, provide a version-less key uri. For manual rotation, provide a versioned key uri.")

    with self.argument_context('acr update', arg_group='Network Rule') as c:
        c.argument('data_endpoint_enabled', get_three_state_flag(), help="Enable dedicated data endpoint for client firewall configuration")

    with self.argument_context('acr update') as c:
        c.argument('anonymous_pull_enabled', get_three_state_flag(), help="Enable registry-wide pull from unauthenticated clients")

    with self.argument_context('acr import') as c:
        c.argument('source_image', options_list=['--source'], help="Source image name or fully qualified source containing the registry login server. If `--registry` is used, `--source` will always be interpreted as a source image, even if it contains the login server.")
        c.argument('source_registry', options_list=['--registry', '-r'], help='The source Azure container registry. This can be name, login server or resource ID of the source registry.')
        c.argument('source_registry_username', options_list=['--username', '-u'], help='The username of source container registry')
        c.argument('source_registry_password', options_list=['--password', '-p'], help='The password of source container registry')
        c.argument('target_tags', options_list=['--image', '-t'], help="The name and tag of the image using the format: '-t repo/image:tag'. Multiple tags are supported by passing -t multiple times.", action='append')
        c.argument('repository', help='The repository name for a manifest-only copy of images. Multiple copies supported by passing --repository multiple times.', action='append')
        c.argument('force', help='Overwrite the existing tag of the image to be imported.', action='store_true')

    with self.argument_context('acr config content-trust') as c:
        c.argument('registry_name', options_list=['--registry', '-r', c.deprecate(target='-n', redirect='-r', hide=True), c.deprecate(target='--name', redirect='--registry', hide=True)])
        c.argument('status', help="Indicates whether content-trust is enabled.", arg_type=get_enum_type(PolicyStatus))

    with self.argument_context('acr config retention') as c:
        c.argument('status', help="Indicates whether retention policy is enabled.", arg_type=get_enum_type(PolicyStatus))
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('days', type=int, help='The number of days to retain an untagged manifest after which it gets purged (Range: 0 to 365). Value "0" will delete untagged manifests immediately.', validator=validate_retention_days, default=7)
        c.argument('policy_type', options_list=['--type'], help='The type of retention policy.', arg_type=get_enum_type(RetentionType))

    with self.argument_context('acr login') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(hide=True))
        c.argument('expose_token', options_list=['--expose-token', '-t'], help='Expose access token instead of automatically logging in through Docker CLI', action='store_true')

    with self.argument_context('acr repository') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(hide=True))
        c.argument('repository', help="The name of the repository.")
        c.argument('image', arg_type=image_by_tag_or_digest_type)
        c.argument('top', type=int, help='Limit the number of items in the results.')
        c.argument('orderby', help='Order the items in the results. Default to alphabetical order of names.', arg_type=get_enum_type(['time_asc', 'time_desc']))
        c.argument('detail', help='Show detailed information.', action='store_true')
        c.argument('delete_enabled', help='Indicates whether delete operation is allowed.', arg_type=get_three_state_flag())
        c.argument('list_enabled', help='Indicates whether this item shows in list operation results.', arg_type=get_three_state_flag())
        c.argument('read_enabled', help='Indicates whether read operation is allowed.', arg_type=get_three_state_flag())
        c.argument('write_enabled', help='Indicates whether write or delete operation is allowed.', arg_type=get_three_state_flag())

    with self.argument_context('acr repository untag') as c:
        c.argument('image', options_list=['--image', '-t'], help="The name of the image. May include a tag in the format 'name:tag'.")

    with self.argument_context('acr create') as c:
        c.argument('registry_name', completer=None, validator=None)
        c.argument('deployment_name', validator=None)
        c.argument('location', validator=get_default_location_from_resource_group)
        c.argument('workspace', is_preview=True,
                   help='Name or ID of the Log Analytics workspace to send registry diagnostic logs to. All events will be enabled. You can use "az monitor log-analytics workspace create" to create one. Extra billing may apply.')

    with self.argument_context('acr check-name') as c:
        c.argument('registry_name', completer=None, validator=None)

    with self.argument_context('acr webhook') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('webhook_name', options_list=['--name', '-n'], help='The name of the webhook', completer=get_resource_name_completion_list(WEBHOOK_RESOURCE_TYPE))
        c.argument('uri', help='The service URI for the webhook to post notifications.')
        c.argument('headers', nargs='+', help="Space-separated custom headers in 'key[=value]' format that will be added to the webhook notifications. Use {} to clear existing headers.".format(quotes), validator=validate_headers)
        c.argument('actions', nargs='+', help='Space-separated list of actions that trigger the webhook to post notifications.', arg_type=get_enum_type(WebhookAction))
        c.argument('status', help='Indicates whether the webhook is enabled.', arg_type=get_enum_type(WebhookStatus))
        c.argument('scope', help="The scope of repositories where the event can be triggered. For example, 'foo:*' means events for all tags under repository 'foo'. 'foo:bar' means events for 'foo:bar' only. 'foo' is equivalent to 'foo:latest'. Empty means events for all repositories.")

    with self.argument_context('acr webhook create') as c:
        c.argument('webhook_name', completer=None)

    with self.argument_context('acr replication') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('replication_name', options_list=['--name', '-n'], help='The name of the replication.', completer=get_resource_name_completion_list(REPLICATION_RESOURCE_TYPE))

    with self.argument_context('acr replication create') as c:
        c.argument('replication_name', help='The name of the replication. Default to the location name.', completer=None)

    for scope in ['acr replication create', 'acr replication update']:
        help_str = "Allow routing to this replication. Requests will not be routed to a disabled replication." \
                   " Data syncing will continue regardless of the region endpoint status."
        help_str += ' Default: true.' if 'create' in scope else ''  # suffix help with default if command is for create

        with self.argument_context(scope) as c:
            c.argument('region_endpoint_enabled', arg_type=get_three_state_flag(), help=help_str, is_preview=True)

    with self.argument_context('acr run') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.positional('source_location', help="The local source code directory path (e.g., './src'), or the URL to a git repository (e.g., 'https://github.com/Azure-Samples/acr-build-helloworld-node.git'), or a remote tarball (e.g., 'http://server/context.tar.gz'), or the repository of an OCI artifact in an Azure container registry (e.g., 'oci://myregistry.azurecr.io/myartifact:mytag'). If '/dev/null' is specified, the value will be set to None and ignored.", completer=FilesCompleter())
        c.argument('file', options_list=['--file', '-f'], help="The task template/definition file path relative to the source context. It can be '-' to pipe a file from the standard input.")
        c.argument('values', help="The task values file path relative to the source context.")
        c.argument('set_value', options_list=['--set'], help="Value in 'name[=value]' format. Multiples supported by passing --set multiple times.", action='append', validator=validate_set)
        c.argument('set_secret', help="Secret value in '--set name[=value]' format. Multiples supported by passing --set multiple times.", action='append', validator=validate_set_secret)
        c.argument('agent_pool_name', options_list=['--agent-pool'], help='The name of the agent pool.', is_preview=True)
        c.argument('log_template', options_list=['--log-template'], help="The repository and tag template for run log artifact using the format: 'log/repo:tag' (e.g., 'acr/logs:{{.Run.ID}}'). Only applicable to CMK enabled registry.", is_preview=True)

    with self.argument_context('acr pack build') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('image_name', options_list=['--image', '-t'], help="The name and tag of the image using the format: '-t repo/image:tag'.")
        c.argument('builder', options_list=['--builder', '-b'], help="The name and tag of a Buildpack builder image.")
        c.argument('pack_image_tag', options_list=['--pack-image-tag'], help="The tag of the 'pack' runner image ('mcr.microsoft.com/oryx/pack').", is_preview=True)
        c.argument('pull', options_list=['--pull'], help="Pull the latest builder and run images before use.", action='store_true')
        c.positional('source_location', help="The local source code directory path (e.g., './src'), or the URL to a git repository (e.g., 'https://github.com/Azure-Samples/acr-build-helloworld-node.git') or a remote tarball (e.g., 'http://server/context.tar.gz'), or the repository of an OCI artifact in an Azure container registry (e.g., 'oci://myregistry.azurecr.io/myartifact:mytag').", completer=FilesCompleter())
        c.argument('agent_pool_name', options_list=['--agent-pool'], help='The name of the agent pool.', is_preview=True)

    with self.argument_context('acr build') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.positional('source_location', help="The local source code directory path (e.g., './src'), or the URL to a git repository (e.g., 'https://github.com/Azure-Samples/acr-build-helloworld-node.git') or a remote tarball (e.g., 'http://server/context.tar.gz'), or the repository of an OCI artifact in an Azure container registry (e.g., 'oci://myregistry.azurecr.io/myartifact:mytag').", completer=FilesCompleter())
        c.argument('no_push', help="Indicates whether the image built should be pushed to the registry.", action='store_true')
        c.argument('no_wait', help="Do not wait for the build to complete and return immediately after queuing the build.", action='store_true')
        c.argument('arg', options_list=['--build-arg'], help="Build argument in '--build-arg name[=value]' format. Multiples supported by passing --build-arg multiple times.", action='append', validator=validate_arg)
        c.argument('secret_arg', options_list=['--secret-build-arg'], help="Secret build argument in '--secret-build-arg name[=value]' format. Multiples supported by passing '--secret-build-arg name[=value]' multiple times.", action='append', validator=validate_secret_arg)
        c.argument('agent_pool_name', options_list=['--agent-pool'], help='The name of the agent pool.', is_preview=True)
        c.argument('log_template', options_list=['--log-template'], help="The repository and tag template for run log artifact using the format: 'log/repo:tag' (e.g., 'acr/logs:{{.Run.ID}}'). Only applicable to CMK enabled registry.", is_preview=True)

    with self.argument_context('acr task') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('task_name', options_list=['--name', '-n'], help='The name of the task.', completer=get_resource_name_completion_list(TASK_RESOURCE_TYPE))
        c.argument('status', help='The current status of task.', arg_type=get_enum_type(TaskStatus))
        c.argument('with_secure_properties', help="Indicates whether the secure properties of a task should be returned.", action='store_true')
        c.argument('log_template', options_list=['--log-template'], help="The repository and tag template for run log artifact using the format: 'log/repo:tag' (e.g., 'acr/logs:{{.Run.ID}}'). Only applicable to CMK enabled registry.", is_preview=True)
        c.argument('is_system_task', options_list=['--is-system-task'], help="Indicates whether the task resource is a system task. The name of the task must be 'quicktask'. Only applicable to CMK enabled registry.", action='store_true', is_preview=True)

        # DockerBuildStep, FileTaskStep parameters
        c.argument('file', options_list=['--file', '-f'], help="Relative path of the the task/docker file to the source code root folder. Task files must be suffixed with '.yaml' or piped from the standard input using '-'.")
        c.argument('image', arg_type=image_by_tag_or_digest_type)
        c.argument('no_push', help="Indicates whether the image built should be pushed to the registry.", arg_type=get_three_state_flag())
        c.argument('no_cache', help='Indicates whether the image cache is enabled.', arg_type=get_three_state_flag())
        c.argument('values', help="The task values/parameters file path relative to the source context.")

        # common to DockerBuildStep, FileTaskStep and RunTaskStep
        c.argument('context_path', options_list=['--context', '-c'], help="The full URL to the source code repository (Requires '.git' suffix for a github repo) or the repository of an OCI artifact in an Azure container registry (e.g., 'oci://myregistry.azurecr.io/myartifact:mytag'). If '/dev/null' is specified, the value will be set to None and ignored. This is a required argument if the task is not a system task.")
        c.argument('arg', help="Build argument in '--arg name[=value]' format. Multiples supported by passing '--arg` multiple times.", action='append', validator=validate_arg)
        c.argument('secret_arg', help="Secret build argument in '--secret-arg name[=value]' format. Multiples supported by passing --secret-arg multiple times.", action='append', validator=validate_secret_arg)
        c.argument('set_value', options_list=['--set'], help="Task value in '--set name[=value]' format. Multiples supported by passing --set multiple times.", action='append', validator=validate_set)
        c.argument('set_secret', help="Secret task value in '--set-secret name[=value]' format. Multiples supported by passing --set-secret multiple times.", action='append', validator=validate_set_secret)

        # Trigger parameters
        c.argument('source_trigger_name', arg_group='Trigger', help="The name of the source trigger.")
        c.argument('commit_trigger_enabled', arg_group='Trigger', help="Indicates whether the source control commit trigger is enabled.", arg_type=get_three_state_flag())
        c.argument('pull_request_trigger_enabled', arg_group='Trigger', help="Indicates whether the source control pull request trigger is enabled. The trigger is disabled by default.", arg_type=get_three_state_flag())
        c.argument('schedule', arg_group='Trigger', help="Schedule for a timer trigger represented as a cron expression. An optional trigger name can be specified using `--schedule name:schedule` format. Multiples supported by passing --schedule multiple times.", action='append')
        c.argument('git_access_token', arg_group='Trigger', help="The access token used to access the source control provider.")
        c.argument('base_image_trigger_name', arg_group='Trigger', help="The name of the base image trigger.")
        c.argument('base_image_trigger_enabled', arg_group='Trigger', help="Indicates whether the base image trigger is enabled.", arg_type=get_three_state_flag())
        c.argument('base_image_trigger_type', arg_group='Trigger', help="The type of the auto trigger for base image dependency updates.", arg_type=get_enum_type(BaseImageTriggerType))
        c.argument('update_trigger_endpoint', arg_group='Trigger', help="The full URL of the endpoint to receive base image update trigger notifications.", is_preview=True)
        c.argument('update_trigger_payload_type', arg_group='Trigger', help="Indicates whether to include metadata about the base image trigger in the payload alongwith the update trigger token, when a notification is sent.", arg_type=get_enum_type(UpdateTriggerPayloadType), is_preview=True)

        # Run related parameters
        c.argument('run_id', help='The unique run identifier.')

        # Run agent parameters
        c.argument('cpu', type=int, help='The CPU configuration in terms of number of cores required for the run.')

        # MSI parameter
        c.argument('assign_identity', nargs='*', help="Assigns managed identities to the task. Use '[system]' to refer to the system-assigned identity or a resource ID to refer to a user-assigned identity. Please see https://aka.ms/acr/tasks/task-create-managed-identity for more information.")

        # Agent Pool Parameter
        c.argument('agent_pool_name', options_list=['--agent-pool'], help='The name of the agent pool.', is_preview=True)

    with self.argument_context('acr task create') as c:
        c.argument('task_name', completer=None)

    with self.argument_context('acr task identity') as c:
        c.argument('identities', options_list=['--identities'], nargs='*', help="Assigns managed identities to the task. Use '[system]' to refer to the system-assigned identity or a resource ID to refer to a user-assigned identity.")

    with self.argument_context('acr task credential') as c:
        # Custom registry credentials
        c.argument('login_server', help="The login server of the custom registry. For instance, 'myregistry.azurecr.io'.", required=True)

    with self.argument_context('acr task run') as c:
        # Update trigger token parameters
        c.argument('update_trigger_token', help="The payload that will be passed back alongwith the base image trigger notification.", is_preview=True)

    with self.argument_context('acr task list-runs') as c:
        c.argument('run_status', help='The current status of run.', arg_type=get_enum_type(RunStatus))
        c.argument('top', help='Limit the number of latest runs in the results.')

    with self.argument_context('acr task update-run') as c:
        c.argument('no_archive', help='Indicates whether the run should be archived.', arg_type=get_three_state_flag())

    for scope in ['acr task credential add', 'acr task credential update']:
        with self.argument_context(scope) as c:
            c.argument('username', options_list=['--username', '-u'], help="The username to login to the custom registry. This can be plain text or a key vault secret URI.")
            c.argument('password', options_list=['--password', '-p'], help="The password to login to the custom registry. This can be plain text or a key vault secret URI.")
            c.argument('use_identity', help="The task managed identity used for the credential. Use '[system]' to refer to the system-assigned identity or a client id to refer to a user-assigned identity. Please see https://aka.ms/acr/tasks/cross-registry-authentication for more information.")

    with self.argument_context('acr task timer') as c:
        # Timer trigger parameters
        c.argument('timer_name', help="The name of the timer trigger.", required=True)
        c.argument('timer_schedule', options_list=['--schedule'], help="The schedule of the timer trigger represented as a cron expression.")
        c.argument('enabled', help="Indicates whether the timer trigger is enabled.", arg_type=get_three_state_flag())

    with self.argument_context('acr taskrun') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('taskrun_name', options_list=['--name', '-n'], help='The name of the taskrun.', completer=get_resource_name_completion_list(TASKRUN_RESOURCE_TYPE))

    with self.argument_context('acr helm') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(hide=True))
        c.argument('repository', help=argparse.SUPPRESS)
        c.argument('version', help='The helm chart version.')

    with self.argument_context('acr helm show') as c:
        c.positional('chart', help='The helm chart name.')

    with self.argument_context('acr helm delete') as c:
        c.positional('chart', help='The helm chart name.')
        c.argument('prov', help='Only delete the provenance file.', action='store_true')

    with self.argument_context('acr helm push') as c:
        c.positional('chart_package', help="The helm chart package.", completer=FilesCompleter())
        c.argument('force', help='Overwrite the existing chart package.', action='store_true')

    with self.argument_context('acr helm install-cli') as c:
        c.argument('client_version', help='The target Helm CLI version. (Attention: Currently, Helm 3 does not work with "az acr helm" commands) ')
        c.argument('install_location', help='Path at which to install Helm CLI (Existing one at the same path will be overwritten)', default=_get_helm_default_install_location())
        c.argument('yes', help='Agree to the license of Helm, and do not prompt for confirmation.')

    with self.argument_context('acr network-rule') as c:
        c.argument('subnet', help='Name or ID of subnet. If name is supplied, `--vnet-name` must be supplied.')
        c.argument('vnet_name', help='Name of a virtual network.')
        c.argument('ip_address', help='IPv4 address or CIDR range.')

    with self.argument_context('acr check-health') as c:
        c.argument('ignore_errors', options_list=['--ignore-errors'], help='Provide all health checks, even if errors are found', action='store_true', required=False)
        c.argument('vnet', options_list=['--vnet'],
                   help="Virtual network ID so to run this command inside a VNET to verify the DNS routing to private endpoints", required=False)

    with self.argument_context('acr scope-map') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('description', options_list=['--description'], help='Description for the scope map. Maximum 256 characters are allowed.', required=False)
        c.argument('scope_map_name', options_list=['--name', '-n'], help='The name of the scope map.', required=True)

    repo_valid_actions = "Valid actions are {}".format({action.value for action in RepoScopeMapActions})
    gateway_valid_actions = "Valid actions are {}".format({action.value for action in GatewayScopeMapActions})
    with self.argument_context('acr scope-map update') as c:
        c.argument('add_repository', options_list=['--add-repository', c.deprecate(target='--add', redirect='--add-repository', hide=True)], nargs='+', action='append', required=False,
                   help='repository permissions to be added. Use the format "--add-repository REPO [ACTION1 ACTION2 ...]" per flag. ' + repo_valid_actions)
        c.argument('remove_repository', options_list=['--remove-repository', c.deprecate(target='--remove', redirect='--remove-repository', hide=True)], nargs='+', action='append', required=False,
                   help='respsitory permissions to be removed. Use the format "--remove-repository REPO [ACTION1 ACTION2 ...]" per flag. ' + repo_valid_actions)
        c.argument('add_gateway', options_list=['--add-gateway'], nargs='+', action='append', required=False,
                   help='gateway permissions to be added. Use the format "--add-gateway GATEWAY [ACTION1 ACTION2 ...]" per flag. ' + gateway_valid_actions)
        c.argument('remove_gateway', options_list=['--remove-gateway'], nargs='+', action='append', required=False,
                   help='gateway permissions to be removed. Use the format "--remove-gateway GATEWAY [ACTION1 ACTION2 ...]" per flag. ' + gateway_valid_actions)

    with self.argument_context('acr scope-map create') as c:
        c.argument('repository_actions_list', options_list=['--repository'], nargs='+', action='append', required=False,
                   help='repository permissions. Use the format "--repository REPO [ACTION1 ACTION2 ...]" per flag. ' + repo_valid_actions)
        c.argument('gateway_actions_list', options_list=['--gateway'], nargs='+', action='append', required=False,
                   help='gateway permissions. Use the format "--gateway GATEWAY [ACTION1 ACTION2 ...]" per flag. ' + gateway_valid_actions)

    with self.argument_context('acr token') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('token_name', options_list=['--name', '-n'], help='The name of the token.', required=True)
        c.argument('scope_map_name', options_list=['--scope-map'], help='The name of the scope map associated with the token', required=False)
        c.argument('status', options_list=['--status'], arg_type=get_enum_type(TokenStatus),
                   help='The status of the token', required=False, default="enabled")

    with self.argument_context('acr token create') as c:
        c.argument('scope_map_name', options_list=['--scope-map'],
                   help='The name of the scope map with pre-configured repository permissions. Use "--repository" and/or "--gateway" if you would like CLI to configure one for you')
        c.argument('repository_actions_list', options_list=['--repository'], nargs='+', action='append',
                   help='repository permissions. Use the format "--repository REPO [ACTION1 ACTION2 ...]" per flag. ' + repo_valid_actions)
        c.argument('gateway_actions_list', options_list=['--gateway'], nargs='+', action='append',
                   help='gateway permissions. Use the format "--gateway GATEWAY [ACTION1 ACTION2 ...]" per flag. ' + gateway_valid_actions)
        c.argument('no_passwords', arg_type=get_three_state_flag(), help='Do not generate passwords, instead use "az acr token credential generate"')
        c.argument('expiration_in_days', help='Number of days for which the credentials will be valid. If not specified, the expiration will default to the max value "9999-12-31T23:59:59.999999+00:00"', type=int, required=False)

    with self.argument_context('acr token update') as c:
        c.argument('scope_map_name', options_list=['--scope-map'], help='The name of the scope map associated with the token. If not specified, running this command will disassociate the current scope map related to the token.', required=False)

    with self.argument_context('acr token credential generate') as c:
        c.argument('password1', options_list=['--password1'], help='Flag indicating if password1 should be generated.', action='store_true', required=False)
        c.argument('password2', options_list=['--password2'], help='Flag indicating if password2 should be generated.', action='store_true', required=False)
        c.argument('expiration_in_days', options_list=['--expiration-in-days', c.deprecate(target='--days', redirect='--expiration-in-days', hide=True)],
                   help='Number of days for which the credentials will be valid. If not specified, the expiration will default to the max value "9999-12-31T23:59:59.999999+00:00"', type=int, required=False)

    for scope in ['acr token create', 'acr token credential generate']:
        with self.argument_context(scope) as c:
            c.argument('expiration', validator=validate_expiration_time,
                       help='UTC time for which the credentials will be valid. In the format of %Y-%m-%dT%H:%M:%SZ, e.g. 2025-12-31T12:59:59Z')

    with self.argument_context('acr token credential delete') as c:
        c.argument('password1', options_list=['--password1'], help='Flag indicating if first password should be deleted', action='store_true', required=False)
        c.argument('password2', options_list=['--password2'], help='Flag indicating if second password should be deleted.', action='store_true', required=False)

    with self.argument_context('acr agentpool') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('agent_pool_name', options_list=['--name', '-n'], help='The name of the agent pool.')
        c.argument('count', options_list=['--count', '-c'], type=int, help='The count of the agent pool.')
        c.argument('tier', help='Sets the VM your agent pool will run on. Valid values are: S1(2 vCPUs, 3 GiB RAM), S2(4 vCPUs, 8 GiB RAM), S3(8 vCPUs, 16 GiB RAM) or I6(64 vCPUs, 216 GiB RAM, Isolated)')
        c.argument('os_type', options_list=['--os'], help='The os of the agent pool.', deprecate_info=c.deprecate(hide=True))
        c.argument('subnet_id', options_list=['--subnet-id'], help='The Virtual Network Subnet Resource Id of the agent machine.')
        c.argument('no_wait', help="Do not wait for the Agent Pool to complete action and return immediately after queuing the request.", action='store_true')

    with self.argument_context('acr agentpool show') as c:
        c.argument('queue_count', help="Get only the queue count", action='store_true')

    with self.argument_context('acr private-endpoint-connection') as c:
        # to match private_endpoint_connection_command_guideline.md guidelines
        c.argument('registry_name', options_list=['--registry-name', '-r'], help='The name of the container registry. You can configure the default registry name using `az configure --defaults acr=<registry name>`', completer=get_resource_name_completion_list(REGISTRY_RESOURCE_TYPE), configured_default='acr')
        c.argument('private_endpoint_connection_name', options_list=['--name', '-n'], help='The name of the private endpoint connection')

        c.argument('approval_description', options_list=['--description'], help='Approval description. For example, the reason for approval.')
        c.argument('rejection_description', options_list=['--description'], help='Rejection description. For example, the reason for rejection.')

    with self.argument_context('acr identity') as c:
        c.argument('identities', nargs='+', help="Space-separated identities. Use '[system]' to refer to the system assigned identity")

    with self.argument_context('acr encryption') as c:
        c.argument('key_encryption_key', help="Key vault key uri. To enable automated rotation, provide a version-less key uri. For manual rotation, provide a versioned key uri.")
        c.argument('identity', help="client id of managed identity, resource name or id of user assigned identity. Use '[system]' to refer to the system assigned identity")

    with self.argument_context('acr connected-registry') as c:
        c.argument('registry_name', options_list=['--registry', '-r'], help='The login server of the Cloud ACR registry. Must be the FQDN to support also Azure Stack.', required=True)
        c.argument('connected_registry_name', options_list=['--name', '-n'], help='Name for the connected registry. Name must be between 5 to 40 character long, start with a letter and contain only alphanumeric characters (including ‘_’ or ‘-’). Name must be unique under the Cloud ACR hierarchy.', required=True)
        c.argument('parent_name', options_list=['--parent', '-p'], help='The name of the parent connected registry.', required=False)
        c.argument('repositories', options_list=['--repository', c.deprecate(target='-t', redirect='--repository', hide=True)], nargs='+', help='Specifies the repositories that need to be sync to the connected registry. It can be in the format [REPO01] [REPO02]...', required=False)
        c.argument('sync_token_name', options_list=['--sync-token'], help='Specifies the sync token used to synchronize the connected registry with its parent. It most have only repo permissions and at least the actions required for its mode. It can include access for multiple repositories.', required=False)
        c.argument('cleanup', help='It will aslo delete the sync token and the scope map resources.', required=False)
        c.argument('no_children', help='Used to remove all children from the list.', required=False, action='store_true')
        c.argument('sync_audit_logs_enabled', options_list=['--audit-logs-enabled'], help='Indicates whether audit log synchronization is enabled. It is enabled by default.', required=False, arg_type=get_three_state_flag(), deprecate_info=c.deprecate(hide=True))

    with self.argument_context('acr connected-registry create') as c:
        c.argument('log_level', help='Sets the log level for logging on the instance. Accepted log levels are Debug, Information, Warning, Error, and None.', required=False, default="Information")
        c.argument('mode', options_list=['--mode', '-m'], help='Can be one of the two operating modes: registry or mirror(pull-only mode).', required=False, default="Registry")
        c.argument('client_token_list', options_list=['--client-tokens'], nargs='+', help='Specifies the client access to the repositories in the connected registry. It can be in the format [TOKEN_NAME01] [TOKEN_NAME02]...', required=False)
        c.argument('sync_window', options_list=['--sync-window', '-w'], help='Required parameter if --sync-schedule is present. Used to determine the schedule duration. Uses ISO 8601 duration format.', required=False)
        c.argument('sync_schedule', options_list=['--sync-schedule', '-s'], help='Optional parameter to define the sync schedule. Uses cron expression to determine the schedule. If not specified, the instance is considered always online and attempts to sync every minute.', required=False, default="* * * * *")
        c.argument('sync_message_ttl', help='Determines how long the sync messages will be kept in the cloud. Uses ISO 8601 duration format.', required=False, default="P2D")

    with self.argument_context('acr connected-registry update') as c:
        c.argument('log_level', help='Sets the log level for logging on the instance. Accepted log levels are Debug, Information, Warning, Error, and None.', required=False)
        c.argument('add_client_token_list', options_list=['--add-client-tokens'], nargs='*', required=False,
                   help='Client tokens to be added. Use the format "--add-client-tokens [TOKEN_ID1 TOKEN_ID2 ...]" per token id.')
        c.argument('remove_client_token_list', options_list=['--remove-client-tokens'], nargs='*', required=False,
                   help='Client tokens to be removed. Use the format "--remove-client-tokens [TOKEN_ID1 TOKEN_ID2 ...]" per token id.')
        c.argument('sync_window', options_list=['--sync-window', '-w'], help='Used to determine the schedule duration. Uses ISO 8601 duration format.', required=False)
        c.argument('sync_schedule', options_list=['--sync-schedule', '-s'], help='Optional parameter to define the sync schedule. Uses cron expression to determine the schedule. If not specified, the instance is considered always online and attempts to sync every minute.', required=False)
        c.argument('sync_message_ttl', help='Determines how long the sync messages will be kept in the cloud. Uses ISO 8601 duration format.', required=False)

    with self.argument_context('acr connected-registry repo') as c:
        c.argument('add_repos', options_list=['--add'], nargs='*', required=False,
                   help='repository permissions to be added to the targeted connected registry and it\'s ancestors sync scope maps. Use the format "--add [REPO1 REPO2 ...]" per flag. ' + repo_valid_actions)
        c.argument('remove_repos', options_list=['--remove'], nargs='*', required=False,
                   help='respsitory permissions to be removed from the targeted connected registry and it\'s succesors sync scope maps. Use the format "--remove [REPO1 REPO2 ...]" per flag. ' + repo_valid_actions)
Example #59
0
def get_vm_size_completion_list(prefix, action, parsed_args, **kwargs):  # pylint: disable=unused-argument
    try:
        location = parsed_args.location
    except AttributeError:
        location = get_one_of_subscription_locations()
    result = get_vm_sizes(location)
    return [r.name for r in result]

# REUSABLE ARGUMENT DEFINITIONS


name_arg_type = CliArgumentType(options_list=('--name', '-n'), metavar='NAME')
multi_ids_type = CliArgumentType(nargs='+')
admin_username_type = CliArgumentType(options_list=('--admin-username',), default=getpass.getuser(), required=False)
existing_vm_name = CliArgumentType(overrides=name_arg_type, help='The name of the virtual machine', completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachines'), id_part='name')
vmss_name_type = CliArgumentType(name_arg_type, completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'), help='Scale set name.', id_part='name')

# ARGUMENT REGISTRATION

register_cli_argument('vm', 'vm_name', existing_vm_name)
register_cli_argument('vm', 'size', completer=get_vm_size_completion_list)
register_cli_argument('vm', 'tags', tags_type)
register_cli_argument('vm', 'name', arg_type=name_arg_type)

for item in ['show', 'list']:
    register_cli_argument('vm {}'.format(item), 'show_details', action='store_true', options_list=('--show-details', '-d'), help='show public ip address, FQDN, and power states. command will run slow')

register_cli_argument('vm disk', 'vm_name', arg_type=existing_vm_name, options_list=('--vm-name',))
register_cli_argument('vm disk', 'disk_name', options_list=('--name', '-n'), help='The data disk name. If missing, will retrieve from vhd uri')
register_cli_argument('vm disk', 'disk_size', help='Size of disk (GiB)', default=1023, type=int)
Example #60
0
    except AttributeError:
        location = get_one_of_subscription_locations()
    result = get_vm_sizes(location)
    return [r.name for r in result]


# REUSABLE ARGUMENT DEFINITIONS

name_arg_type = CliArgumentType(options_list=('--name', '-n'), metavar='NAME')
multi_ids_type = CliArgumentType(nargs='+')
existing_vm_name = CliArgumentType(
    overrides=name_arg_type,
    configured_default='vm',
    help=
    "The name of the Virtual Machine. You can configure the default using `az configure --defaults vm=<name>`",
    completer=get_resource_name_completion_list(
        'Microsoft.Compute/virtualMachines'),
    id_part='name')
vmss_name_type = CliArgumentType(
    name_arg_type,
    configured_default='vmss',
    completer=get_resource_name_completion_list(
        'Microsoft.Compute/virtualMachineScaleSets'),
    help=
    "Scale set name. You can configure the default using `az configure --defaults vmss=<name>`",
    id_part='name')
disk_sku = CliArgumentType(required=False,
                           help='underlying storage sku',
                           **enum_choice_list(['Premium_LRS', 'Standard_LRS']))

# ARGUMENT REGISTRATION