def test_override_existing_option_string(self):
     arg = CLIArgumentType(options_list=('--funky', '-f'))
     updated_options_list = ('--something-else', '-s')
     arg.update(options_list=updated_options_list, validator=lambda: (), completer=lambda: ())
     self.assertEqual(arg.settings['options_list'], updated_options_list)
     self.assertIsNotNone(arg.settings['validator'])
     self.assertIsNotNone(arg.settings['completer'])
Exemplo n.º 2
0
def load_arguments(self, _):
    from argcomplete.completers import FilesCompleter

    from azure.mgmt.resource.resources.models import DeploymentMode
    from azure.mgmt.resource.locks.models import LockLevel
    from azure.mgmt.resource.managedapplications.models import ApplicationLockLevel

    from azure.cli.core.api import get_subscription_id_list
    from azure.cli.core.commands.parameters import (
        resource_group_name_type, get_location_type, tag_type, tags_type,
        get_resource_group_completion_list, no_wait_type, file_type,
        get_enum_type, get_three_state_flag)
    from azure.cli.core.profiles import ResourceType

    from knack.arguments import ignore_type, CLIArgumentType

    from azure.cli.command_modules.resource._completers import (
        get_policy_completion_list, get_policy_set_completion_list,
        get_policy_assignment_completion_list,
        get_resource_types_completion_list, get_providers_completion_list)
    from azure.cli.command_modules.resource._validators import (
        validate_lock_parameters, validate_resource_lock, validate_group_lock,
        validate_subscription_lock, validate_metadata, RollbackAction,
        validate_msi)

    # BASIC PARAMETER CONFIGURATION

    resource_name_type = CLIArgumentType(options_list=['--name', '-n'],
                                         help='The resource name. (Ex: myC)')
    resource_type_type = CLIArgumentType(
        help=
        "The resource type (Ex: 'resC'). Can also accept namespace/type format (Ex: 'Microsoft.Provider/resC')"
    )
    resource_namespace_type = CLIArgumentType(
        options_list='--namespace',
        completer=get_providers_completion_list,
        help="Provider namespace (Ex: 'Microsoft.Provider')")
    resource_parent_type = CLIArgumentType(
        required=False,
        options_list=['--parent'],
        help="The parent path (Ex: 'resA/myA/resB/myB')")
    existing_policy_definition_name_type = CLIArgumentType(
        options_list=['--name', '-n'],
        completer=get_policy_completion_list,
        help='The policy definition name.')
    existing_policy_set_definition_name_type = CLIArgumentType(
        options_list=['--name', '-n'],
        completer=get_policy_set_completion_list,
        help='The policy set definition name.')
    subscription_type = CLIArgumentType(
        options_list='--subscription',
        FilesCompleter=get_subscription_id_list,
        help='The subscription id of the policy [set] definition.')
    management_group_name_type = CLIArgumentType(
        options_list='--management-group',
        help='The name of the management group of the policy [set] definition.'
    )
    identity_scope_type = CLIArgumentType(
        help="Scope that the system assigned identity can access")
    identity_role_type = CLIArgumentType(
        options_list=['--role'],
        help="Role name or id that will be assigned to the managed identity")
    extended_json_format_type = CLIArgumentType(
        options_list=['--handle-extended-json-format', '-j'],
        action='store_true',
        is_preview=True,
        help=
        'Support to handle extended template content including multiline and comments in deployment'
    )

    _PROVIDER_HELP_TEXT = 'the resource namespace, aka \'provider\''

    with self.argument_context('resource') as c:
        c.argument('no_wait', no_wait_type)
        c.argument('resource_group_name',
                   resource_group_name_type,
                   arg_group='Resource Id')
        c.ignore('resource_id')
        c.argument('resource_name',
                   resource_name_type,
                   arg_group='Resource Id')
        c.argument('api_version',
                   help='The api version of the resource (omit for latest)',
                   required=False,
                   arg_group='Resource Id')
        c.argument('resource_provider_namespace',
                   resource_namespace_type,
                   arg_group='Resource Id')
        c.argument('resource_type',
                   arg_type=resource_type_type,
                   completer=get_resource_types_completion_list,
                   arg_group='Resource Id')
        c.argument('parent_resource_path',
                   resource_parent_type,
                   arg_group='Resource Id')
        c.argument('tag', tag_type)
        c.argument('tags', tags_type)
        c.argument(
            'resource_ids',
            nargs='+',
            options_list=['--ids'],
            help=
            'One or more resource IDs (space-delimited). If provided, no other "Resource Id" arguments should be specified.',
            arg_group='Resource Id')
        c.argument(
            'include_response_body',
            arg_type=get_three_state_flag(),
            help=
            'Use if the default command output doesn\'t capture all of the property data.'
        )

    with self.argument_context('resource list') as c:
        c.argument('name', resource_name_type)

    with self.argument_context('resource move') as c:
        c.argument('ids', nargs='+')

    with self.argument_context('resource invoke-action') as c:
        c.argument(
            'action',
            help='The action that will be invoked on the specified resource')
        c.argument(
            'request_body',
            help=
            'JSON encoded parameter arguments for the action that will be passed along in the post request body. Use @{file} to load from a file.'
        )

    with self.argument_context('resource create') as c:
        c.argument('resource_id',
                   options_list=['--id'],
                   help='Resource ID.',
                   action=None)
        c.argument(
            'properties',
            options_list=['--properties', '-p'],
            help='a JSON-formatted string containing resource properties')
        c.argument(
            'is_full_object',
            action='store_true',
            help=
            'Indicates that the properties object includes other options such as location, tags, sku, and/or plan.'
        )

    with self.argument_context('resource link') as c:
        c.argument(
            'target_id',
            options_list=[
                '--target',
                c.deprecate(target='--target-id',
                            redirect='--target',
                            hide=True)
            ],
            help='Fully-qualified resource ID of the resource link target.')
        c.argument('link_id',
                   options_list=[
                       '--link',
                       c.deprecate(target='--link-id',
                                   redirect='--link',
                                   hide=True)
                   ],
                   help='Fully-qualified resource ID of the resource link.')
        c.argument('notes', help='Notes for the link.')
        c.argument('scope', help='Fully-qualified scope for retrieving links.')
        c.argument('filter_string',
                   options_list=[
                       '--filter',
                       c.deprecate(target='--filter-string',
                                   redirect='--filter',
                                   hide=True)
                   ],
                   help='Filter string for limiting results.')

    with self.argument_context('provider') as c:
        c.ignore('top')
        c.argument('resource_provider_namespace',
                   options_list=['--namespace', '-n'],
                   completer=get_providers_completion_list,
                   help=_PROVIDER_HELP_TEXT)

    with self.argument_context('provider register') as c:
        c.argument('wait',
                   action='store_true',
                   help='wait for the registration to finish')

    with self.argument_context('provider unregister') as c:
        c.argument('wait',
                   action='store_true',
                   help='wait for unregistration to finish')

    with self.argument_context('provider operation') as c:
        c.argument(
            'api_version',
            help=
            "The api version of the 'Microsoft.Authorization/providerOperations' resource (omit for latest)"
        )

    with self.argument_context('feature') as c:
        c.argument('resource_provider_namespace',
                   options_list='--namespace',
                   required=True,
                   help=_PROVIDER_HELP_TEXT)
        c.argument('feature_name',
                   options_list=['--name', '-n'],
                   help='the feature name')

    with self.argument_context('feature list') as c:
        c.argument('resource_provider_namespace',
                   options_list='--namespace',
                   required=False,
                   help=_PROVIDER_HELP_TEXT)

    with self.argument_context('policy') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   help='the resource group where the policy will be applied')

    with self.argument_context(
            'policy definition',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('policy_definition_name',
                   arg_type=existing_policy_definition_name_type)
        c.argument(
            'rules',
            help='JSON formatted string or a path to a file with such content',
            type=file_type,
            completer=FilesCompleter())
        c.argument('display_name', help='Display name of policy definition.')
        c.argument('description', help='Description of policy definition.')
        c.argument(
            'params',
            help=
            'JSON formatted string or a path to a file or uri with parameter definitions.',
            type=file_type,
            completer=FilesCompleter(),
            min_api='2016-12-01')
        c.argument('metadata',
                   min_api='2017-06-01-preview',
                   nargs='+',
                   validator=validate_metadata,
                   help='Metadata in space-separated key=value pairs.')
        c.argument('management_group', arg_type=management_group_name_type)
        c.argument(
            'mode',
            options_list=['--mode', '-m'],
            help=
            'Mode of the policy definition, e.g. All, Indexed. Please visit https://aka.ms/azure-policy-mode for more information.',
            min_api='2016-12-01')
        c.argument('subscription', arg_type=subscription_type)
        c.ignore('_subscription')  # disable global subscription

    with self.argument_context(
            'policy definition create',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='Name of the new policy definition.')

    with self.argument_context(
            'policy assignment',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.ignore('_subscription')
        c.argument('name',
                   options_list=['--name', '-n'],
                   completer=get_policy_assignment_completion_list,
                   help='Name of the policy assignment.')
        c.argument('scope',
                   help='Scope to which this policy assignment applies.')
        c.argument(
            'disable_scope_strict_match',
            action='store_true',
            help=
            'Include policy assignments either inherited from parent scope or at child scope.'
        )
        c.argument('display_name',
                   help='Display name of the policy assignment.')
        c.argument('policy',
                   help='Name or id of the policy definition.',
                   completer=get_policy_completion_list)

    with self.argument_context(
            'policy assignment create',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='Name of the new policy assignment.')
        c.argument(
            'params',
            options_list=['--params', '-p'],
            help=
            'JSON formatted string or a path to a file or uri with parameter values of the policy rule.',
            type=file_type,
            completer=FilesCompleter(),
            min_api='2016-12-01')

    with self.argument_context('policy assignment create',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               min_api='2017-06-01-preview') as c:
        c.argument('policy_set_definition',
                   options_list=['--policy-set-definition', '-d'],
                   help='Name or id of the policy set definition.')
        c.argument('sku',
                   options_list=['--sku', '-s'],
                   help='policy sku.',
                   arg_type=get_enum_type(['free', 'standard']))
        c.argument('notscopes', options_list='--not-scopes', nargs='+')

    with self.argument_context('policy assignment create',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               min_api='2018-05-01') as c:
        c.argument('location', arg_type=get_location_type(self.cli_ctx))

    with self.argument_context('policy assignment create',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               arg_group='Managed Identity',
                               min_api='2018-05-01') as c:
        c.argument(
            'assign_identity',
            nargs='*',
            validator=validate_msi,
            help="Assigns a system assigned identity to the policy assignment."
        )
        c.argument('identity_scope', arg_type=identity_scope_type)
        c.argument('identity_role', arg_type=identity_role_type)

    with self.argument_context('policy assignment create',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               min_api='2019-06-01') as c:
        c.argument(
            'enforcement_mode',
            options_list=['--enforcement-mode', '-e'],
            help=
            'Enforcement mode of the policy assignment, e.g. Default, DoNotEnforce. Please visit https://aka.ms/azure-policyAssignment-enforcement-mode for more information.',
            arg_type=get_enum_type(['Default', 'DoNotEnforce']))

    with self.argument_context('policy assignment identity',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               min_api='2018-05-01') as c:
        c.argument('identity_scope', arg_type=identity_scope_type)
        c.argument('identity_role', arg_type=identity_role_type)

    with self.argument_context(
            'policy set-definition',
            min_api='2017-06-01-preview',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('policy_set_definition_name',
                   arg_type=existing_policy_set_definition_name_type)
        c.argument('display_name',
                   help='Display name of policy set definition.')
        c.argument('description', help='Description of policy set definition.')
        c.argument(
            'params',
            help=
            'JSON formatted string or a path to a file or uri with parameter definitions.',
            type=file_type,
            completer=FilesCompleter())
        c.argument(
            'definitions',
            help=
            'JSON formatted string or a path to a file or uri containing definitions.',
            type=file_type,
            completer=FilesCompleter())
        c.argument('management_group', arg_type=management_group_name_type)
        c.argument('subscription', arg_type=subscription_type)
        c.ignore('_subscription')  # disable global subscription

    with self.argument_context(
            'policy set-definition create',
            min_api='2017-06-01-preview',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='Name of the new policy set definition.')

    with self.argument_context('group') as c:
        c.argument('tag', tag_type)
        c.argument('tags', tags_type)
        c.argument('resource_group_name',
                   resource_group_name_type,
                   options_list=['--name', '-n', '--resource-group', '-g'])

    with self.argument_context('group deployment') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   completer=get_resource_group_completion_list)
        c.argument('deployment_name',
                   options_list=['--name', '-n'],
                   required=True,
                   help='The deployment name.')
        c.argument('template_file',
                   completer=FilesCompleter(),
                   type=file_type,
                   help="a template file path in the file system")
        c.argument('template_uri', help='a uri to a remote template file')
        c.argument(
            'mode',
            arg_type=get_enum_type(DeploymentMode, default='incremental'),
            help=
            'Incremental (only add resources to resource group) or Complete (remove extra resources from resource group)'
        )
        c.argument('parameters',
                   action='append',
                   nargs='+',
                   completer=FilesCompleter())
        c.argument(
            'rollback_on_error',
            nargs='?',
            action=RollbackAction,
            help=
            'The name of a deployment to roll back to on error, or use as a flag to roll back to the last successful deployment.'
        )

    with self.argument_context('group deployment create') as c:
        c.argument(
            'deployment_name',
            options_list=['--name', '-n'],
            required=False,
            help='The deployment name. Default to template file base name')
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type)

    with self.argument_context('group deployment validate') as c:
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type)

    with self.argument_context('group deployment operation show') as c:
        c.argument('operation_ids',
                   nargs='+',
                   help='A list of operation ids to show')

    with self.argument_context('deployment') as c:
        c.argument('deployment_name',
                   options_list=['--name', '-n'],
                   required=True,
                   help='The deployment name.')
        c.argument('deployment_location',
                   arg_type=get_location_type(self.cli_ctx),
                   required=True)
        c.argument('template_file',
                   completer=FilesCompleter(),
                   type=file_type,
                   help="a template file path in the file system")
        c.argument('template_uri', help='a uri to a remote template file')
        c.argument('parameters',
                   action='append',
                   nargs='+',
                   completer=FilesCompleter())

    with self.argument_context('deployment create') as c:
        c.argument(
            'deployment_name',
            options_list=['--name', '-n'],
            required=False,
            help='The deployment name. Default to template file base name')
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type)

    with self.argument_context('deployment validate') as c:
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type)

    with self.argument_context('deployment operation show') as c:
        c.argument('operation_ids',
                   nargs='+',
                   help='A list of operation ids to show')

    with self.argument_context('group export') as c:
        c.argument('include_comments', action='store_true')
        c.argument('include_parameter_default_value', action='store_true')

    with self.argument_context('group create') as c:
        c.argument('rg_name',
                   options_list=['--name', '--resource-group', '-n', '-g'],
                   help='name of the new resource group',
                   completer=None)

    with self.argument_context('tag') as c:
        c.argument('tag_name', options_list=['--name', '-n'])
        c.argument('tag_value', options_list='--value')

    with self.argument_context('lock') as c:
        c.argument('lock_name',
                   options_list=['--name', '-n'],
                   validator=validate_lock_parameters)
        c.argument('level',
                   arg_type=get_enum_type(LockLevel),
                   options_list=['--lock-type', '-t'],
                   help='The type of lock restriction.')
        c.argument('parent_resource_path', resource_parent_type)
        c.argument('resource_provider_namespace', resource_namespace_type)
        c.argument('resource_type',
                   arg_type=resource_type_type,
                   completer=get_resource_types_completion_list)
        c.argument(
            'resource_name',
            options_list=['--resource', '--resource-name'],
            help=
            'Name or ID of the resource being locked. If an ID is given, other resource arguments should not be given.'
        )
        c.argument(
            'ids',
            nargs='+',
            options_list='--ids',
            help=
            'One or more resource IDs (space-delimited). If provided, no other "Resource Id" arguments should be specified.'
        )
        c.argument('resource_group',
                   resource_group_name_type,
                   validator=validate_lock_parameters)

    with self.argument_context('resource lock') as c:
        c.argument('resource_group', resource_group_name_type)
        c.argument(
            'resource_name',
            options_list=['--resource', '--resource-name'],
            help=
            'If an ID is given, other resource arguments should not be given.',
            validator=validate_resource_lock)

    with self.argument_context('group lock') as c:
        c.argument('resource_group',
                   resource_group_name_type,
                   validator=validate_group_lock,
                   id_part=None)

    with self.argument_context('group lock create') as c:
        c.argument('resource_group', required=True)

    with self.argument_context('account lock') as c:
        c.argument('resource_group',
                   ignore_type,
                   validator=validate_subscription_lock)

    for scope in ['account', 'group']:
        with self.argument_context('{} lock'.format(scope)) as c:
            c.ignore('resource_provider_namespace', 'parent_resource_path',
                     'resource_type', 'resource_name')

    for scope in ['lock', 'account lock', 'group lock', 'resource lock']:
        with self.argument_context(scope) as c:
            c.argument('lock_name',
                       options_list=['--name', '-n'],
                       help='Name of the lock')
            c.argument('level',
                       options_list=['--lock-type', '-t'],
                       arg_type=get_enum_type(
                           [LockLevel.can_not_delete, LockLevel.read_only]),
                       help='The type of lock restriction.')
            c.argument(
                'ids',
                nargs='+',
                options_list='--ids',
                help=
                'One or more resource IDs (space-delimited). If provided, no other "Resource Id" arguments should be specified.'
            )
            c.argument('notes', help='Notes about this lock.')

    with self.argument_context('managedapp') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   help='the resource group of the managed application',
                   id_part='resource_group')
        c.argument('application_name',
                   options_list=['--name', '-n'],
                   id_part='name')

    with self.argument_context('managedapp definition') as c:
        c.argument(
            'resource_group_name',
            arg_type=resource_group_name_type,
            help='the resource group of the managed application definition',
            id_part='resource_group')
        c.argument('application_definition_name',
                   options_list=['--name', '-n'],
                   id_part='name')

    with self.argument_context('managedapp create') as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='name of the new managed application',
                   completer=None)
        c.argument('location', help='the managed application location')
        c.argument('managedapp_definition_id',
                   options_list=['--managedapp-definition-id', '-d'],
                   help='the full qualified managed application definition id')
        c.argument(
            'managedby_resource_group_id',
            options_list=['--managed-rg-id', '-m'],
            help='the resource group managed by the managed application')
        c.argument(
            'parameters',
            help='JSON formatted string or a path to a file with such content',
            type=file_type)

    with self.argument_context('managedapp definition create') as c:
        c.argument('lock_level',
                   arg_type=get_enum_type(ApplicationLockLevel),
                   help='The type of lock restriction.')
        c.argument(
            'authorizations',
            options_list=['--authorizations', '-a'],
            nargs='+',
            help=
            "space-separated authorization pairs in a format of <principalId>:<roleDefinitionId>"
        )
        c.argument(
            'createUiDefinition',
            options_list=['--create-ui-definition', '-c'],
            help='JSON formatted string or a path to a file with such content',
            type=file_type)
        c.argument(
            'mainTemplate',
            options_list=['--main-template', '-t'],
            help='JSON formatted string or a path to a file with such content',
            type=file_type)

    with self.argument_context('account') as c:
        c.argument('subscription',
                   options_list=['--subscription', '-s'],
                   help='Name or ID of subscription.',
                   completer=get_subscription_id_list)
        c.ignore('_subscription')  # hide global subscription parameter

    with self.argument_context('account management-group') as c:
        c.argument('group_name', options_list=['--name', '-n'])

    with self.argument_context('account management-group show') as c:
        c.argument('expand',
                   options_list=['--expand', '-e'],
                   action='store_true')
        c.argument('recurse',
                   options_list=['--recurse', '-r'],
                   action='store_true')

    with self.argument_context('account management-group create') as c:
        c.argument('display_name', options_list=['--display-name', '-d'])
        c.argument('parent', options_list=['--parent', '-p'])

    with self.argument_context('account management-group update') as c:
        c.argument('display_name', options_list=['--display-name', '-d'])
        c.argument('parent_id', options_list=['--parent', '-p'])

    with self.argument_context('rest') as c:
        c.argument(
            'method',
            options_list=['--method', '-m'],
            arg_type=get_enum_type(
                ['head', 'get', 'put', 'post', 'delete', 'options', 'patch'],
                default='get'),
            help='HTTP request method')
        c.argument(
            'uri',
            options_list=['--uri', '-u'],
            help=
            'request uri. For uri without host, CLI will assume "https://management.azure.com/".'
            ' Common tokens will also be replaced with real values including "{subscriptionId}"'
        )
        c.argument(
            'headers',
            nargs='+',
            help=
            "Space-separated headers in KEY=VALUE format or JSON string. Use @{file} to load from a file"
        )
        c.argument(
            'uri_parameters',
            nargs='+',
            help=
            'Space-separated queries in KEY=VALUE format or JSON string. Use @{file} to load from a file'
        )
        c.argument('skip_authorization_header',
                   action='store_true',
                   help='do not auto append "Authorization" header')
        c.argument('body',
                   options_list=['--body', '-b'],
                   help='request body. Use @{file} to load from a file')
        c.argument('output_file', help='save response payload to a file')
        c.argument(
            'resource',
            help=
            'Resource url for which CLI should acquire a token in order to access '
            'the service. The token will be placed in the "Authorization" header. By default, '
            'CLI can figure this out based on "--url" argument, unless you use ones not in the list '
            'of "az cloud show --query endpoints"')
Exemplo n.º 3
0
def load_arguments(self, _):
    account_name_type = CLIArgumentType(options_list=['--account-name', '-a'],
                                        id_part='name',
                                        help='Name of the ANF account.')
    pool_name_type = CLIArgumentType(options_list=['--pool-name', '-p'],
                                     id_part='child_name_1',
                                     help='Name of the ANF pool.')
    volume_name_type = CLIArgumentType(options_list=['--volume-name', '-v'],
                                       id_part='child_name_2',
                                       help='Name of the ANF volume.')

    with self.argument_context('netappfiles') as c:
        c.argument('resource_group', resource_group_name_type)
        c.argument('tags', arg_type=tags_type)
        c.argument('protocol_types', arg_type=tags_type)
        c.argument('account_name', account_name_type)
        c.argument('pool_name', pool_name_type)
        c.argument('volume_name', volume_name_type)
        c.argument('snapshot_name',
                   options_list=['--snapshot-name', '-s'],
                   help='The name of the ANF snapshot')
        c.argument('tag', tags_type)
        c.argument('service_level',
                   options_list=['--service-level'],
                   arg_type=get_enum_type(['Standard', 'Premium', 'Ultra']),
                   help='Service level')
        c.argument('enabled',
                   options_list=['--enabled', '-e'],
                   arg_type=get_three_state_flag(),
                   id_part=None)

    with self.argument_context('netappfiles account') as c:
        c.argument('account_name',
                   account_name_type,
                   options_list=['--name', '--account-name', '-n', '-a'])

    with self.argument_context('netappfiles account list') as c:
        c.argument('account_name',
                   help='The name of the ANF account',
                   id_part=None)

    with self.argument_context('netappfiles account ad') as c:
        c.argument('backup_operators', arg_type=tags_type)
        c.argument('security_operators', arg_type=tags_type)

    with self.argument_context('netappfiles account ad list') as c:
        c.argument('account_name',
                   help='The name of the ANF account',
                   id_part=None)

    with self.argument_context('netappfiles account backup-policy') as c:
        c.argument('account_name', account_name_type)
        c.argument('backup_policy_name',
                   options_list=['--backup-policy-name', '-b'],
                   help='The name of the backup policy',
                   id_part='child_name_1')
        c.argument('daily_backups',
                   options_list=['--daily-backups', '-d'],
                   help='Daily backups count to keep')
        c.argument('weekly_backups',
                   options_list=['--weekly-backups', '-w'],
                   help='Weekly backups count to keep')
        c.argument('monthly_backups',
                   options_list=['--monthly-backups', '-m'],
                   help='Monthly backups count to keep')
        c.argument('yearly_backups',
                   options_list=['--yearly-backups', '-y'],
                   help='Yearly backups count to keep')

    with self.argument_context('netappfiles account backup-policy list') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('backup_policy_name',
                   options_list=['--backup-policy-name', '-b'],
                   help='The name of the backup policy')

    with self.argument_context('netappfiles account backup') as c:
        c.argument('account_name', account_name_type, id_part=None)

    load_poolArguments(self, account_name_type, pool_name_type)
    load_volumeArguments(self, account_name_type, pool_name_type,
                         volume_name_type)
    load_snapshotArguments(self, account_name_type, pool_name_type,
                           volume_name_type)
    load_vaultArguments(self, account_name_type)

    with self.argument_context('netappfiles account backup') as c:
        c.argument('account_name', account_name_type, id_part=None)

    load_poolArguments(self, account_name_type, pool_name_type)
    load_volumeArguments(self, account_name_type, pool_name_type,
                         volume_name_type)
    load_snapshotArguments(self, account_name_type, pool_name_type,
                           volume_name_type)
    load_vaultArguments(self, account_name_type)
Exemplo n.º 4
0
def load_arguments(self, _):

    name_arg_type = CLIArgumentType(options_list=('--name', '-n'), metavar='NAME')
    endpoint_name_type = CLIArgumentType(options_list=('--endpoint-name'), metavar='ENDPOINT_NAME')
    origin_group_name_type = CLIArgumentType(options_list=('--origin-group-name'), metavar='ORIGIN_GROUP_NAME')
    rule_set_name_type = CLIArgumentType(options_list=('--rule-set-name'), metavar='RULE_SET_NAME')
    route_name_type = CLIArgumentType(options_list=('--route-name'), metavar='ROUTE_NAME')
    rule_name_type = CLIArgumentType(options_list=('--rule-name'), metavar='RULE_NAME')
    custom_name_arg_type = CLIArgumentType(options_list=('--custom-domain-name'), metavar='CUSTOM_DOMAIN_NAME')
    secret_name_arg_type = CLIArgumentType(options_list=('--secret-name'), metavar='SECRET_NAME')
    origin_name_type = CLIArgumentType(options_list=('--origin-name'), metavar='ORIGIN_NAME')
    profile_name_help = 'Name of the CDN profile which is unique within the resource group.'

    with self.argument_context('cdn') as c:
        c.argument('name', name_arg_type, id_part='name')
        c.argument('tags', tags_type)

    # Profile #
    with self.argument_context('cdn profile') as c:
        c.argument('profile_name', name_arg_type, id_part='name', help=profile_name_help)

    with self.argument_context('cdn profile create') as c:
        # Remove Stardard/Premium Front Door from old cdn profile's supported SKU list
        supported_skus = [item.value for item in list(SkuName) if item.value not in
                          (SkuName.premium_azure_front_door, SkuName.standard_azure_front_door)]
        c.argument('sku', arg_type=get_enum_type(supported_skus))
        c.argument('location', validator=get_default_location_from_resource_group)
        c.argument('name', name_arg_type, id_part='name', help=profile_name_help)

    # Endpoint #

    with self.argument_context('cdn endpoint') as c:
        c.argument('content_paths', nargs='+')
        c.argument('endpoint_name', name_arg_type, id_part='child_name_1', help='Name of the CDN endpoint.')
        c.argument('location', validator=get_default_location_from_resource_group)
        c.argument('origins', options_list='--origin', nargs='+', action=OriginType, validator=validate_origin,
                   help='Endpoint origin specified by the following space-delimited 6 tuple: '
                        '`www.example.com http_port https_port private_link_resource_id private_link_location '
                        'private_link_approval_message`. The HTTP and HTTPS ports and the private link resource ID and '
                        'location are optional. The HTTP and HTTPS ports default to 80 and 443, respectively. Private '
                        'link fields are only valid for the sku Standard_Microsoft, and private_link_location is '
                        'required if private_link_resource_id is set.')
        c.argument('is_http_allowed', arg_type=get_three_state_flag(invert=True), options_list='--no-http',
                   help='Indicates whether HTTP traffic is not allowed on the endpoint. '
                   'Default is to allow HTTP traffic.')
        c.argument('is_https_allowed', arg_type=get_three_state_flag(invert=True), options_list='--no-https',
                   help='Indicates whether HTTPS traffic is not allowed on the endpoint. '
                   'Default is to allow HTTPS traffic.')
        c.argument('is_compression_enabled', arg_type=get_three_state_flag(), options_list='--enable-compression',
                   help='If compression is enabled, content will be served as compressed if '
                        'user requests for a compressed version. Content won\'t be compressed '
                        'on CDN when requested content is smaller than 1 byte or larger than 1 '
                        'MB.')
        c.argument('profile_name', help=profile_name_help, id_part='name')

    with self.argument_context('cdn endpoint update') as c:
        caching_behavior = [item.value for item in list(QueryStringCachingBehavior)]
        c.argument('query_string_caching_behavior', options_list='--query-string-caching',
                   arg_type=get_enum_type(caching_behavior))
        c.argument('content_types_to_compress', nargs='+')

    with self.argument_context('cdn endpoint rule') as c:
        configure_rule_parameters(c)

    with self.argument_context('cdn endpoint create') as c:
        c.argument('name', name_arg_type, id_part='name', help='Name of the CDN endpoint.')
    with self.argument_context('cdn endpoint set') as c:
        c.argument('name', name_arg_type, id_part='name', help='Name of the CDN endpoint.')

    with self.argument_context('cdn endpoint list') as c:
        c.argument('profile_name', id_part=None)

    with self.argument_context('cdn endpoint waf') as c:
        c.argument('endpoint_name', endpoint_name_type, help='Name of the CDN endpoint.')

    # Custom Domain #

    with self.argument_context('cdn custom-domain') as c:
        c.argument('custom_domain_name', name_arg_type, id_part=None, help='Name of the custom domain.')

    with self.argument_context('cdn custom-domain create') as c:
        c.argument('location', validator=get_default_location_from_resource_group)

    with self.argument_context('cdn custom-domain enable-https') as c:
        c.argument('profile_name', id_part=None, help='Name of the parent profile.')
        c.argument('endpoint_name', help='Name of the parent endpoint.')
        c.argument('custom_domain_name', name_arg_type, help='Name of the custom domain.')
        c.argument('min_tls_version',
                   help='The minimum TLS version required for the custom domain.',
                   arg_type=get_enum_type(['none', '1.0', '1.2']))
        c.argument('user_cert_protocol_type',
                   arg_group='Bring Your Own Certificate',
                   help='The protocol type of the certificate.',
                   arg_type=get_enum_type(['sni', 'ip']))
        c.argument('user_cert_subscription_id',
                   arg_group='Bring Your Own Certificate',
                   help='The subscription id of the KeyVault certificate')
        c.argument('user_cert_group_name',
                   arg_group='Bring Your Own Certificate',
                   help='The resource group of the KeyVault certificate')
        c.argument('user_cert_vault_name',
                   arg_group='Bring Your Own Certificate',
                   help='The vault name of the KeyVault certificate')
        c.argument('user_cert_secret_name',
                   arg_group='Bring Your Own Certificate',
                   help='The secret name of the KeyVault certificate')
        c.argument('user_cert_secret_version',
                   arg_group='Bring Your Own Certificate',
                   help='The secret version of the KeyVault certificate')

    # Origin #
    with self.argument_context('cdn origin') as c:
        # Some command handlers use name, others origin_name, so we specify both
        c.argument('name', name_arg_type, id_part='child_name_2', help='Name of the origin.')
        c.argument('origin_name', name_arg_type, id_part='child_name_2', help='Name of the origin.')
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('endpoint_name', endpoint_name_type, id_part='child_name_1', help='Name of the CDN endpoint.')
        c.argument('http_port', type=int)
        c.argument('https_port', type=int)
        c.argument('disabled', arg_type=get_three_state_flag())
        c.argument('priority', type=int)
        c.argument('weight', type=int)
        c.argument('private_link_approval_message', options_list=['--private-link-approval-message', '-m'])
        c.argument('private_link_resource_id', options_list=['--private-link-resource-id', '-p'])
        c.argument('private_link_location', options_list=['--private-link-location', '-l'])
    with self.argument_context('cdn origin list') as c:
        # list commands can't use --ids argument.
        c.argument('profile_name', id_part=None)
        c.argument('endpoint_name', id_part=None)

    with self.argument_context('cdn origin-group') as c:
        # Some command handlers use name, others origin_name, so we specify both
        c.argument('name', name_arg_type, id_part='child_name_2', help='Name of the origin group.')
        c.argument('origin_group_name', name_arg_type, id_part='child_name_2', help='Name of the origin group.')
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('endpoint_name', endpoint_name_type, id_part='child_name_1', help='Name of the CDN endpoint.')
        c.argument('disabled', arg_type=get_three_state_flag())
        c.argument('probe_method', arg_type=get_enum_type(["HEAD", "GET"]))
        c.argument('probe_protocol', arg_type=get_enum_type(["HTTP", "HTTPS"]))
        c.argument('probe_interval', type=int)
        c.argument('failover_threshold', type=int)
        c.argument('detection_type', arg_type=get_enum_type(["TcpErrorsOnly", "TcpAndHttpErrors"]))

    with self.argument_context('cdn origin-group list') as c:
        # list commands can't use --ids argument.
        c.argument('profile_name', id_part=None)
        c.argument('endpoint_name', id_part=None)

    # WAF #

    with self.argument_context('cdn waf policy set') as c:
        c.argument('disabled', arg_type=get_three_state_flag())
        c.argument('block_response_status_code', type=int)
        c.argument('name', name_arg_type, id_part='name', help='The name of the CDN WAF policy.')
    with self.argument_context('cdn waf policy show') as c:
        c.argument('policy_name', name_arg_type, id_part='name', help='The name of the CDN WAF policy.')
    with self.argument_context('cdn waf policy delete') as c:
        c.argument('policy_name', name_arg_type, id_part='name', help='The name of the CDN WAF policy.')
    with self.argument_context('cdn waf policy set') as c:
        c.argument('waf_policy_resource_group_name', options_list=['--waf-policy-resource-group-name',
                                                                   '--policy-group'])

    with self.argument_context('cdn waf policy managed-rule-set') as c:
        c.argument('policy_name', id_part='name', help='Name of the CDN WAF policy.')
        c.argument('rule_set_type', help='The type of the managed rule set.')
        c.argument('rule_set_version', help='The version of the managed rule set.')
    with self.argument_context('cdn waf policy managed-rule-set list') as c:
        # List commands cannot use --ids flag
        c.argument('policy_name', id_part=None)
    with self.argument_context('cdn waf policy managed-rule-set add') as c:
        c.argument('enabled', arg_type=get_three_state_flag())

    with self.argument_context('cdn waf policy managed-rule-set rule-group-override') as c:
        c.argument('name', name_arg_type, id_part=None, help='The name of the rule group.')
    with self.argument_context('cdn waf policy managed-rule-set rule-group-override list') as c:
        # List commands cannot use --ids flag
        c.argument('policy_name', id_part=None)
    with self.argument_context('cdn waf policy managed-rule-set rule-group-override set') as c:
        c.argument('rule_overrides',
                   options_list=['-r', '--rule-override'],
                   action=ManagedRuleOverrideAction,
                   nargs='+')

    with self.argument_context('cdn waf policy custom-rule') as c:
        c.argument('name', name_arg_type, id_part=None, help='The name of the custom rule.')
        c.argument('policy_name', id_part='name', help='Name of the CDN WAF policy.')
    with self.argument_context('cdn waf policy custom-rule list') as c:
        # List commands cannot use --ids flag
        c.argument('policy_name', id_part=None)
    with self.argument_context('cdn waf policy rate-limit-rule') as c:
        c.argument('name', name_arg_type, id_part=None, help='The name of the rate limit rule.')
        c.argument('policy_name', id_part='name', help='Name of the CDN WAF policy.')
    with self.argument_context('cdn waf policy rate-limit-rule list') as c:
        # List commands cannot use --ids flag
        c.argument('policy_name', id_part=None)

    with self.argument_context('cdn waf policy custom-rule set') as c:
        c.argument('match_conditions', options_list=['-m', '--match-condition'], action=MatchConditionAction, nargs='+')
        c.argument('priority', type=int, validator=validate_priority)
        c.argument('action', arg_type=get_enum_type([item.value for item in list(ActionType)]))

    with self.argument_context('cdn waf policy rate-limit-rule set') as c:
        c.argument('match_conditions', options_list=['-m', '--match-condition'], action=MatchConditionAction, nargs='+')
        c.argument('priority', type=int, validator=validate_priority)
        c.argument('action', arg_type=get_enum_type([item.value for item in list(ActionType)]))
        c.argument('request_threshold', type=int)
        c.argument('duration', type=int)

    # AFDX
    with self.argument_context('afd') as c:
        c.argument('tags', tags_type)

    # AFD Profiles
    with self.argument_context('afd profile') as c:
        c.argument('sku',
                   arg_type=get_enum_type([SkuName.standard_azure_front_door, SkuName.premium_azure_front_door]),
                   help="The pricing tier of the AFD profile.")
        c.argument('profile_name', help=profile_name_help, id_part='name')

    # AFD endpoint #
    with self.argument_context('afd endpoint') as c:
        c.argument('origin_response_timeout_seconds', type=int,
                   options_list=["--origin-response-timeout-seconds"],
                   help="Send and receive timeout on forwarding request to the origin. "
                        "When timeout is reached, the request fails and returns.")
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('enabled_state', arg_type=get_enum_type(EnabledState),
                   options_list=["--enabled-state"],
                   help="Whether to enable this endpoint.")
        c.argument('endpoint_name', endpoint_name_type, id_part='child_name_1',
                   help='Name of the endpoint under the profile which is unique globally.')
        c.argument('content_paths', nargs='+',
                   help="The path to the content to be purged. Can describe a file path or a wildcard directory.")
        c.argument('domains', nargs='+', help='List of domains.')

    with self.argument_context('afd endpoint list') as c:
        c.argument('profile_name', id_part=None)

    # AFD Origin Group #
    with self.argument_context('afd origin-group') as c:
        c.argument('origin_group_name', origin_group_name_type, id_part='child_name_1',
                   help='Name of the origin group.')
        c.argument('profile_name', help=profile_name_help, id_part='name')

        # health probe related paramters
        c.argument('probe_request_type', arg_type=get_enum_type(HealthProbeRequestType),
                   help='The type of health probe request that is made.')
        c.argument('probe_protocol', arg_type=get_enum_type(ProbeProtocol),
                   help='Protocol to use for health probe.')
        c.argument('probe_interval_in_seconds', type=int,
                   help='The number of seconds between health probes.')
        c.argument('probe_path',
                   help="The path relative to the origin that is used to determine the health of the origin.")

        # load balancing related parameters
        c.argument('load_balancing_sample_size', type=int,
                   options_list='--sample-size',
                   arg_group="Load Balancing",
                   help="The number of samples to consider for load balancing decisions.")
        c.argument('load_balancing_successful_samples_required', type=int,
                   options_list='--successful-samples-required',
                   arg_group="Load Balancing",
                   help="The number of samples within the sample period that must succeed.")
        c.argument('load_balancing_additional_latency_in_milliseconds', type=int,
                   options_list='--additional-latency-in-milliseconds',
                   arg_group="Load Balancing",
                   help="The additional latency in milliseconds for probes to fall into the lowest latency bucket.")

    with self.argument_context('afd origin-group list') as c:
        c.argument('origin_group_name', id_part=None)
        c.argument('profile_name', id_part=None)

    # AFD Origin #
    with self.argument_context('afd origin') as c:
        c.argument('origin_name', origin_name_type, id_part='child_name_2', help='Name of the origin.')
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('origin_group_name', origin_group_name_type, id_part='child_name_1',
                   help='Name of the origin group which is unique within the endpoint.')
        c.argument('host_name',
                   help="The address of the origin. Domain names, IPv4 addresses, and IPv6 addresses are supported."
                        "This should be unique across all origins in a origin group.")
        c.argument('origin_host_header',
                   help="The Host header to send for requests to this origin. If you leave this blank, "
                        "the request hostname determines this value. "
                        "Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services "
                        "require this host header value to match the origin hostname by default.")
        c.argument('http_port', type=int, help="The port used for http requests to the origin.")
        c.argument('https_port', type=int, help="The port used for https requests to the origin.")
        c.argument('enabled_state', arg_type=get_enum_type(EnabledState),
                   help="Whether to enable this origin.")
        c.argument('priority', type=int,
                   help="Priority of origin in given origin group for load balancing. Higher priorities will not be "
                        "used for load balancing if any lower priority origin is healthy. Must be between 1 and 5.")
        c.argument('weight', type=int,
                   help="Weight of the origin in given origin group for load balancing. Must be between 1 and 1000.")
        c.argument('enable_private_link', arg_type=get_three_state_flag(invert=False),
                   help='Indicates whether private link is enanbled on that origin.')
        c.argument('private_link_resource',
                   help="The resource ID of the origin that will be connected to using the private link.")
        c.argument('private_link_location',
                   help="The location of origin that will be connected to using the private link.")
        c.argument(
            'private_link_sub_resource_type',
            help="The sub-resource type of the origin that will be connected to using the private link."
                 'You can use "az network private-link-resource list" to obtain the supported sub-resource types.')
        c.argument('private_link_request_message',
                   help="The message that is shown to the approver of the private link request.")

    with self.argument_context('afd origin list') as c:
        c.argument('profile_name', id_part=None)
        c.argument('origin_group_name', id_part=None)

    # AFD Route #
    with self.argument_context('afd route') as c:
        c.argument('route_name', route_name_type, id_part='child_name_2', help='Name of the route.')
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('endpoint_name', endpoint_name_type, id_part='child_name_1', help='Name of the endpoint.')
        c.argument('origin_group', help='Name or ID of the origin group to be associated with.')
        c.argument('patterns_to_match', nargs='+', help='The route patterns of the rule.')
        c.argument('origin_path',
                   help='A directory path on the origin that AFD can use to retrieve content from. E.g, "/img/*"')
        c.argument('custom_domains', nargs='*', help='Custom domains referenced by this endpoint.')
        c.argument('supported_protocols', nargs='+',
                   arg_type=get_enum_type(AFDEndpointProtocols),
                   help="List of supported protocols for this route.")
        c.argument('link_to_default_domain',
                   arg_type=get_enum_type(LinkToDefaultDomain),
                   help="Whether this route will be linked to the default endpoint domain.")
        c.argument('forwarding_protocol',
                   arg_type=get_enum_type(ForwardingProtocol),
                   help="Protocol this rule will use when forwarding traffic to backends.")
        c.argument('https_redirect',
                   arg_type=get_enum_type(HttpsRedirect),
                   help='Whether to automatically redirect HTTP traffic to HTTPS traffic.')
        c.argument('rule_sets', nargs='*', help='Collection of ID or name of rule set referenced by the route.')
        c.argument('content_types_to_compress', nargs='+',
                   help='List of content types on which compression applies. The value should be a valid MIME type.')
        c.argument('query_string_caching_behavior',
                   arg_type=get_enum_type(QueryStringCachingBehavior),
                   help="Defines how CDN caches requests that include query strings. "
                        "You can ignore any query strings when caching, "
                        "bypass caching to prevent requests that contain query strings from being cached, "
                        "or cache every request with a unique URL.")
        c.argument(
            'is_compression_enabled',
            arg_type=get_three_state_flag(),
            options_list='--enable-compression',
            help='Indicates whether content compression is enabled on AzureFrontDoor. Default value is false. '
                 'If compression is enabled, content will be served as compressed if user requests for a '
                 "compressed version. Content won't be compressed on AzureFrontDoor when requested content is "
                 'smaller than 1 byte or larger than 1 MB.')

    with self.argument_context('afd route list') as c:
        c.argument('profile_name', id_part=None)
        c.argument('endpoint_name', id_part=None)

    # AFD RuleSets #
    with self.argument_context('afd rule-set') as c:
        c.argument('rule_set_name', rule_set_name_type, id_part='child_name_1', help='Name of the rule set.')
        c.argument('profile_name', help=profile_name_help, id_part='name')

    with self.argument_context('afd rule-set list') as c:
        c.argument('profile_name', id_part=None)

    # AFD Rules #
    with self.argument_context('afd rule') as c:
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('rule_set_name', id_part='child_name_1', help='Name of the rule set.')
        configure_rule_parameters(c)
        c.argument('rule_name', rule_name_type, id_part='child_name_2', help='Name of the rule.')
        c.argument('match_processing_behavior',
                   arg_type=get_enum_type(MatchProcessingBehavior),
                   help='Indicate whether rules engine should continue to run the remaining rules or stop if matched.'
                        ' Defaults to Continue.')

    with self.argument_context('afd rule list') as c:
        c.argument('profile_name', id_part=None)
        c.argument('rule_set_name', id_part=None)

    with self.argument_context('afd rule condition list') as c:
        c.argument('profile_name', id_part=None)
        c.argument('rule_set_name', id_part=None)
        c.argument('rule_name', id_part=None)

    with self.argument_context('afd rule action list') as c:
        c.argument('profile_name', id_part=None)
        c.argument('rule_set_name', id_part=None)
        c.argument('rule_name', id_part=None)

    # AFD Security Policy #
    with self.argument_context('afd security-policy') as c:
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('security_policy_name', id_part='child_name_1', help='Name of the security policy.')
        c.argument('waf_policy', help='The ID of Front Door WAF policy.')
        c.argument(
            'domains',
            nargs='+',
            help='The domains to associate with the WAF policy. Could either be the ID of an endpoint'
                 ' (default domain will be used in that case) or ID of a custom domain.')

    with self.argument_context('afd security-policy list') as c:
        c.argument('profile_name', id_part=None)
        c.argument('security_policy_name', id_part=None)

    # AFD Custom Domain #
    with self.argument_context('afd custom-domain') as c:
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('custom_domain_name', custom_name_arg_type, id_part="child_name_1",
                   help='Name of the custom domain.')
        c.argument('certificate_type', arg_type=get_enum_type(AfdCertificateType),
                   help='Defines the source of the SSL certificate.')
        c.argument('minimum_tls_version', arg_type=get_enum_type(AfdMinimumTlsVersion),
                   help='TLS protocol version that will be used for Https.')
        c.argument('host_name', help='The host name of the domain. Must be a domain name.')
        c.argument('azure_dns_zone', help='ID of the Azure DNS zone.')
        c.argument('secret', help='ID of the Azure key vault certificate.')

    with self.argument_context('afd custom-domain list') as c:
        c.argument('profile_name', id_part=None)
        c.argument('custom_domain_name', custom_name_arg_type, id_part=None, help='Name of the custom domain.')

    # AFD Secret #
    with self.argument_context('afd secret') as c:
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('secret_name', secret_name_arg_type, id_part="child_name_1", help='Name of the custom domain.')
        c.argument('use_latest_version', arg_type=get_three_state_flag(),
                   help="Whether to use the latest version for the certificate.")
        c.argument('secret_source', help='ID of the Azure key vault certificate.')
        c.argument('secret_version', help='Version of the certificate to be used.')

    with self.argument_context('afd secret list') as c:
        c.argument('profile_name', id_part=None)
        c.argument('secret_name', id_part=None)

    # AFD Log Analytic #
    with self.argument_context('afd log-analytic') as c:
        c.argument('group_by', nargs='+',
                   arg_type=get_enum_type(["httpStatusCode", "protocol", "cacheStatus", "country", "customDomain"]),
                   help="Aggregate demensions.")
        c.argument('continents', nargs='+', help="ISO 3316-1 alpha-2 continent code.")
        c.argument('country_or_regions', nargs='+', help="ISO 3316-1 alpha-2 region code.")
        c.argument('custom_domains', nargs='+', help="The domains to be included.")
        c.argument('protocols', nargs='+', help="The protocols to be included.")
        configure_log_analytic_common_parameters(c)

    with self.argument_context('afd log-analytic metric') as c:
        c.argument('metrics', nargs='+',
                   arg_type=get_enum_type(["clientRequestCount", "clientRequestTraffic", "clientRequestBandwidth",
                                           "originRequestTraffic", "originRequestBandwidth", "totalLatency"]),
                   help="Metric types to include.")

    with self.argument_context('afd log-analytic ranking') as c:
        c.argument('metrics', nargs='+',
                   arg_type=get_enum_type(["clientRequestCount", "clientRequestTraffic",
                                           "hitCount", "missCount", "userErrorCount", "errorCount"]),
                   help="Metric types to include.")
        c.argument('rankings', nargs='+', help="The dimemsions to be included for ranking.",
                   arg_type=get_enum_type(["url", "referrer", "browser", "userAgent", "countryOrRegion"]))

    with self.argument_context('afd waf-log-analytic') as c:
        c.argument('metrics', nargs='+', arg_type=get_enum_type(["clientRequestCount"]),
                   help="Metric types to be included.")
        c.argument('group_by', nargs='+', arg_type=get_enum_type(["httpStatusCode", "customDomain"]),
                   help="Aggregate demensions.")
        c.argument('actions', nargs='+', help="The WAF actions to be included.",
                   arg_type=get_enum_type(["allow", "block", "log", "redirect"]))
        c.argument('rule_types', nargs='+', help="The WAF rule types to be included.",
                   arg_type=get_enum_type(["managed", "custom", "bot"]))
        c.argument('rankings', nargs='+', help="The dimemsions to be included for ranking.",
                   arg_type=get_enum_type(["action", "ruleGroup", "ruleId", "userAgent",
                                           "clientIp", "url", "country", "ruleType"]))
        configure_log_analytic_common_parameters(c)
Exemplo n.º 5
0
def load_arguments(self, _):

    with self.argument_context('managed-network mn list') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('top', help='May be used to limit the number of results in a page for list queries.')
        c.argument('skiptoken', help='Skiptoken is only used if a previous operation returned a partial result. If a pr'
                   'evious response contains a nextLink element, the value of the nextLink element will include a skipt'
                   'oken parameter that specifies a starting point to use for subsequent calls.')

    with self.argument_context('managed-network mn create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', options_list=['--name', '-n'], help='The name of the Managed Network.')
        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('properties', arg_type=CLIArgumentType(options_list=['--properties'], help='The MNC properties Expec'
                   'ted value: json-string/@json-file.'))

    with self.argument_context('managed-network mn update') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', options_list=['--name', '-n'], help='The name of the Managed Network.',
                   id_part='name')
        c.argument('tags', tags_type)

    with self.argument_context('managed-network mn delete') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', options_list=['--name', '-n'], help='The name of the Managed Network.',
                   id_part='name')

    with self.argument_context('managed-network mn get-modify') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', options_list=['--name', '-n'], help='The name of the Managed Network.',
                   id_part='name')

    with self.argument_context('managed-network mn scope-assignment list') as c:
        c.argument('scope', help='The base resource of the scope assignment.')

    with self.argument_context('managed-network mn scope-assignment show') as c:
        c.argument('scope', help='The base resource of the scope assignment.')
        c.argument('scope_assignment_name', options_list=['--name', '-n'], help='The name of the scope assignment to ge'
                   't.')

    with self.argument_context('managed-network mn scope-assignment create') as c:
        c.argument('scope', help='The base resource of the scope assignment to create. The scope can be any REST resour'
                   'ce instance. For example, use \'subscriptions/{subscription-id}\' for a subscription, \'subscriptio'
                   'ns/{subscription-id}/resourceGroups/{resource-group-name}\' for a resource group, and \'subscriptio'
                   'ns/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-t'
                   'ype}/{resource-name}\' for a resource.')
        c.argument('scope_assignment_name', options_list=['--name', '-n'], help='The name of the scope assignment to cr'
                   'eate.')
        c.argument('location', arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('assigned_managed_network', help='The managed network ID with scope will be assigned to.')

    with self.argument_context('managed-network mn scope-assignment update') as c:
        c.argument('scope', help='The base resource of the scope assignment to create. The scope can be any REST resour'
                   'ce instance. For example, use \'subscriptions/{subscription-id}\' for a subscription, \'subscriptio'
                   'ns/{subscription-id}/resourceGroups/{resource-group-name}\' for a resource group, and \'subscriptio'
                   'ns/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-t'
                   'ype}/{resource-name}\' for a resource.')
        c.argument('scope_assignment_name', options_list=['--name', '-n'], help='The name of the scope assignment to cr'
                   'eate.')
        c.argument('location', arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('assigned_managed_network', help='The managed network ID with scope will be assigned to.')

    with self.argument_context('managed-network mn scope-assignment delete') as c:
        c.argument('scope', help='The scope of the scope assignment to delete.')
        c.argument('scope_assignment_name', options_list=['--name', '-n'], help='The name of the scope assignment to de'
                   'lete.')

    with self.argument_context('managed-network mn group list') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.')
        c.argument('top', help='May be used to limit the number of results in a page for list queries.')
        c.argument('skiptoken', help='Skiptoken is only used if a previous operation returned a partial result. If a pr'
                   'evious response contains a nextLink element, the value of the nextLink element will include a skipt'
                   'oken parameter that specifies a starting point to use for subsequent calls.')

    with self.argument_context('managed-network mn group show') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.', id_part='name')
        c.argument('group_name', help='The name of the Managed Network Group.', id_part='child_name_1')

    with self.argument_context('managed-network mn group create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.')
        c.argument('group_name', help='The name of the Managed Network Group.')
        c.argument('location', arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('management_groups', arg_type=CLIArgumentType(options_list=['--management-groups'], help='The collec'
                   'tion of management groups covered by the Managed Network Expected value: json-string/@json-file.'))
        c.argument('subscriptions', action=AddSubscriptions, nargs='+', help='The collection of subscriptions covered b'
                   'y the Managed Network')
        c.argument('virtual_networks', action=AddVirtualNetworks, nargs='+', help='The collection of virtual nets cover'
                   'ed by the Managed Network')
        c.argument('subnets', action=AddSubnets, nargs='+', help='The collection of  subnets covered by the Managed Net'
                   'work')

    with self.argument_context('managed-network mn group update') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.', id_part='name')
        c.argument('group_name', help='The name of the Managed Network Group.', id_part='child_name_1')
        c.argument('location', arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('management_groups', arg_type=CLIArgumentType(options_list=['--management-groups'], help='The collec'
                   'tion of management groups covered by the Managed Network Expected value: json-string/@json-file.'))
        c.argument('subscriptions', action=AddSubscriptions, nargs='+', help='The collection of subscriptions covered b'
                   'y the Managed Network')
        c.argument('virtual_networks', action=AddVirtualNetworks, nargs='+', help='The collection of virtual nets cover'
                   'ed by the Managed Network')
        c.argument('subnets', action=AddSubnets, nargs='+', help='The collection of  subnets covered by the Managed Net'
                   'work')

    with self.argument_context('managed-network mn group delete') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.', id_part='name')
        c.argument('group_name', help='The name of the Managed Network Group.', id_part='child_name_1')

    with self.argument_context('managed-network mn group wait') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.', id_part='name')
        c.argument('group_name', help='The name of the Managed Network Group.', id_part='child_name_1')

    with self.argument_context('managed-network managed-network-peering-policy list') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.')
        c.argument('top', help='May be used to limit the number of results in a page for list queries.')
        c.argument('skiptoken', help='Skiptoken is only used if a previous operation returned a partial result. If a pr'
                   'evious response contains a nextLink element, the value of the nextLink element will include a skipt'
                   'oken parameter that specifies a starting point to use for subsequent calls.')

    with self.argument_context('managed-network managed-network-peering-policy show') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.', id_part='name')
        c.argument('policy_name', help='The name of the Managed Network Peering Policy.', id_part='child_name_1')

    with self.argument_context('managed-network managed-network-peering-policy hub-and-spoke-topology create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.')
        c.argument('policy_name', help='The name of the Managed Network Peering Policy.')
        c.argument('location', arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('hub', action=AddHub, nargs='+', help='Gets or sets the hub virtual network ID')
        c.argument('spokes', action=AddSpokes, nargs='+', help='Gets or sets the spokes group IDs')
        c.argument('mesh', action=AddMesh, nargs='+', help='Gets or sets the mesh group IDs')

    with self.argument_context('managed-network managed-network-peering-policy hub-and-spoke-topology update') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.', id_part='name')
        c.argument('policy_name', help='The name of the Managed Network Peering Policy.', id_part='child_name_1')
        c.argument('location', arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('hub', action=AddHub, nargs='+', help='Gets or sets the hub virtual network ID')
        c.argument('spokes', action=AddSpokes, nargs='+', help='Gets or sets the spokes group IDs')
        c.argument('mesh', action=AddMesh, nargs='+', help='Gets or sets the mesh group IDs')
        c.ignore('managed_network_peering_policy_name', 'properties')

    with self.argument_context('managed-network managed-network-peering-policy mesh-topology create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.')
        c.argument('policy_name', help='The name of the Managed Network Peering Policy.')
        c.argument('location', arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('hub', action=AddHub, nargs='+', help='Gets or sets the hub virtual network ID')
        c.argument('spokes', action=AddSpokes, nargs='+', help='Gets or sets the spokes group IDs')
        c.argument('mesh', action=AddMesh, nargs='+', help='Gets or sets the mesh group IDs')

    with self.argument_context('managed-network managed-network-peering-policy mesh-topology update') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.', id_part='name')
        c.argument('policy_name', help='The name of the Managed Network Peering Policy.', id_part='child_name_1')
        c.argument('location', arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('hub', action=AddHub, nargs='+', help='Gets or sets the hub virtual network ID')
        c.argument('spokes', action=AddSpokes, nargs='+', help='Gets or sets the spokes group IDs')
        c.argument('mesh', action=AddMesh, nargs='+', help='Gets or sets the mesh group IDs')
        c.ignore('managed_network_peering_policy_name', 'properties')

    with self.argument_context('managed-network managed-network-peering-policy delete') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.', id_part='name')
        c.argument('policy_name', help='The name of the Managed Network Peering Policy.', id_part='child_name_1')

    with self.argument_context('managed-network managed-network-peering-policy wait') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('managed_network_name', help='The name of the Managed Network.', id_part='name')
        c.argument('policy_name', help='The name of the Managed Network Peering Policy.', id_part='child_name_1')
Exemplo n.º 6
0
def load_arguments(self, _):  # pylint: disable=too-many-locals, too-many-statements
    from argcomplete.completers import FilesCompleter
    from six import u as unicode_string

    from knack.arguments import ignore_type, CLIArgumentType

    from azure.cli.core.commands.parameters import get_resource_name_completion_list

    from .sdkutil import get_table_data_type
    from .completers import get_storage_name_completion_list, get_container_name_completions

    t_base_blob_service = self.get_sdk('blob.baseblobservice#BaseBlobService')
    t_file_service = self.get_sdk('file#FileService')
    t_queue_service = self.get_sdk('queue#QueueService')
    t_table_service = get_table_data_type(self.cli_ctx, 'table',
                                          'TableService')

    acct_name_type = CLIArgumentType(
        options_list=['--account-name', '-n'],
        help='The storage account name.',
        id_part='name',
        completer=get_resource_name_completion_list(
            'Microsoft.Storage/storageAccounts'))
    blob_name_type = CLIArgumentType(
        options_list=['--blob-name', '-b'],
        help='The blob name.',
        completer=get_storage_name_completion_list(t_base_blob_service,
                                                   'list_blobs',
                                                   parent='container_name'))

    container_name_type = CLIArgumentType(
        options_list=['--container-name', '-c'],
        help='The container name.',
        completer=get_container_name_completions)
    directory_type = CLIArgumentType(
        options_list=['--directory-name', '-d'],
        help='The directory name.',
        completer=get_storage_name_completion_list(
            t_file_service, 'list_directories_and_files', parent='share_name'))
    file_name_type = CLIArgumentType(
        options_list=['--file-name', '-f'],
        completer=get_storage_name_completion_list(
            t_file_service, '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(t_file_service,
                                                   'list_shares'))
    table_name_type = CLIArgumentType(
        options_list=['--table-name', '-t'],
        completer=get_storage_name_completion_list(t_table_service,
                                                   'list_tables'))
    queue_name_type = CLIArgumentType(
        options_list=['--queue-name', '-q'],
        help='The queue name.',
        completer=get_storage_name_completion_list(t_queue_service,
                                                   'list_queues'))
    progress_type = CLIArgumentType(
        help='Include this flag to disable progress reporting for the command.',
        action='store_true',
        validator=add_progress_callback)
    socket_timeout_type = CLIArgumentType(
        help=
        'The socket timeout(secs), used by the service to regulate data flow.',
        type=int)

    sas_help = 'The permissions the SAS grants. Allowed values: {}. Do not use if a stored access policy is ' \
               'referenced with --id that specifies this value. Can be combined.'

    with self.argument_context('storage') as c:
        c.argument('container_name', container_name_type)
        c.argument('directory_name', directory_type)
        c.argument('share_name', share_name_type)
        c.argument('table_name', table_name_type)
        c.argument('retry_wait', options_list=('--retry-interval', ))
        c.ignore('progress_callback')
        c.argument(
            'metadata',
            nargs='+',
            help=
            'Metadata in space-separated key=value pairs. This overwrites any existing metadata.',
            validator=validate_metadata)
        c.argument(
            'timeout',
            help=
            'Request timeout in seconds. Applies to each call to the service.',
            type=int)

    with self.argument_context('storage', arg_group='Precondition') as c:
        c.argument(
            'if_modified_since',
            help=
            'Alter only if modified since supplied UTC datetime (Y-m-d\'T\'H:M\'Z\')',
            type=get_datetime_type(False))
        c.argument(
            'if_unmodified_since',
            help=
            'Alter only if unmodified since supplied UTC datetime (Y-m-d\'T\'H:M\'Z\')',
            type=get_datetime_type(False))
        c.argument('if_match')
        c.argument('if_none_match')

    for item in ['delete', 'list', 'show', 'update', 'keys']:
        with self.argument_context('storage account {}'.format(item)) as c:
            c.argument('account_name',
                       acct_name_type,
                       options_list=['--name', '-n'])

    with self.argument_context('storage account check-name') as c:
        c.argument('name', options_list=['--name', '-n'])

    with self.argument_context('storage account create') as c:
        t_account_type, t_sku_name, t_kind = self.get_models(
            'AccountType',
            'SkuName',
            'Kind',
            resource_type=CUSTOM_MGMT_STORAGE)
        c.register_common_storage_account_options()
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('account_type',
                   help='The storage account type',
                   arg_type=get_enum_type(t_account_type))
        c.argument('account_name',
                   acct_name_type,
                   options_list=['--name', '-n'],
                   completer=None)
        c.argument('kind',
                   help='Indicates the type of storage account.',
                   arg_type=get_enum_type(t_kind, default='storage'))
        c.argument('tags', tags_type)
        c.argument(
            'custom_domain',
            help=
            'User domain assigned to the storage account. Name is the CNAME source.'
        )
        c.argument('sku',
                   help='The storage account SKU.',
                   arg_type=get_enum_type(t_sku_name,
                                          default='standard_ragrs'))

    with self.argument_context('storage account update') as c:
        c.register_common_storage_account_options()
        c.argument(
            'custom_domain',
            help=
            'User domain assigned to the storage account. Name is the CNAME source. Use "" to clear '
            'existing value.',
            validator=validate_custom_domain)
        c.argument('use_subdomain',
                   help='Specify whether to use indirect CNAME validation.',
                   arg_type=get_enum_type(['true', 'false']))
        c.argument('tags', tags_type, default=None)

    with self.argument_context('storage account update',
                               arg_group='Customer managed key',
                               min_api='2017-06-01') as c:
        c.extra(
            'encryption_key_name',
            help='The name of the KeyVault key',
        )
        c.extra('encryption_key_vault', help='The Uri of the KeyVault')
        c.extra('encryption_key_version',
                help='The version of the KeyVault key')
        c.argument(
            'encryption_key_source',
            arg_type=get_enum_type(['Microsoft.Storage', 'Microsoft.Keyvault'],
                                   'Microsoft.Storage'),
            help='The default encryption service',
            validator=validate_encryption_source)
        c.ignore('encryption_key_vault_properties')

    for scope in ['storage account create', 'storage account update']:
        with self.argument_context(scope,
                                   resource_type=CUSTOM_MGMT_STORAGE,
                                   min_api='2017-06-01',
                                   arg_group='Network Rule') as c:
            t_bypass, t_default_action = self.get_models(
                'Bypass', 'DefaultAction', resource_type=CUSTOM_MGMT_STORAGE)

            c.argument('bypass',
                       nargs='+',
                       validator=validate_bypass,
                       arg_type=get_enum_type(t_bypass),
                       help='Bypass traffic for space-separated uses.')
            c.argument('default_action',
                       arg_type=get_enum_type(t_default_action),
                       help='Default action to apply when no rule matches.')

    with self.argument_context('storage account show-connection-string') as c:
        c.argument('account_name',
                   acct_name_type,
                   options_list=['--name', '-n'])
        c.argument('protocol',
                   help='The default endpoint protocol.',
                   arg_type=get_enum_type(['http', 'https']))
        c.argument('key_name',
                   options_list=['--key'],
                   help='The key to use.',
                   arg_type=get_enum_type(
                       list(storage_account_key_options.keys())))
        for item in ['blob', 'file', 'queue', 'table']:
            c.argument('{}_endpoint'.format(item),
                       help='Custom endpoint for {}s.'.format(item))

    with self.argument_context('storage account keys renew') as c:
        c.argument('key_name',
                   options_list=['--key'],
                   help='The key to regenerate.',
                   validator=validate_key,
                   arg_type=get_enum_type(
                       list(storage_account_key_options.keys())))
        c.argument('account_name', acct_name_type, id_part=None)

    with self.argument_context('storage account keys list') as c:
        c.argument('account_name', acct_name_type, id_part=None)

    with self.argument_context('storage account network-rule') as c:
        from ._validators import validate_subnet
        c.argument('storage_account_name', acct_name_type, id_part=None)
        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)

    with self.argument_context('storage account generate-sas') as c:
        t_account_permissions = self.get_sdk(
            'common.models#AccountPermissions')
        c.register_sas_arguments()
        c.argument('services', type=services_type(self))
        c.argument('resource_types', type=resource_type_type(self))
        c.argument('expiry', type=get_datetime_type(True))
        c.argument('start', type=get_datetime_type(True))
        c.argument('account_name',
                   acct_name_type,
                   options_list=('--account-name', ))
        c.argument(
            'permission',
            options_list=('--permissions', ),
            help=
            'The permissions the SAS grants. Allowed values: {}. Can be combined.'
            .format(get_permission_help_string(t_account_permissions)),
            validator=get_permission_validator(t_account_permissions))
        c.ignore('sas_token')

    with self.argument_context(
            'storage account management-policy create') as c:
        c.argument(
            'policy',
            type=file_type,
            completer=FilesCompleter(),
            help=
            'The Storage Account ManagementPolicies Rules, in JSON format. See more details in: '
            'https://docs.microsoft.com/en-us/azure/storage/common/storage-lifecycle-managment-concepts.'
        )
        c.argument(
            'account_name',
            help=
            'The name of the storage account within the specified resource group.'
        )

    with self.argument_context('storage logging show') as c:
        c.extra('services',
                validator=get_char_options_validator('bqt', 'services'),
                default='bqt')

    with self.argument_context('storage logging update') as c:
        c.extra('services',
                validator=get_char_options_validator('bqt', 'services'),
                options_list='--services',
                required=True)
        c.argument('log', validator=get_char_options_validator('rwd', 'log'))
        c.argument('retention', type=int)

    with self.argument_context('storage metrics show') as c:
        c.extra('services',
                validator=get_char_options_validator('bfqt', 'services'),
                default='bfqt')
        c.argument('interval',
                   arg_type=get_enum_type(['hour', 'minute', 'both']))

    with self.argument_context('storage metrics update') as c:
        c.extra('services',
                validator=get_char_options_validator('bfqt', 'services'),
                options_list='--services',
                required=True)
        c.argument('hour',
                   validator=process_metric_update_namespace,
                   arg_type=get_enum_type(['true', 'false']))
        c.argument('minute', arg_type=get_enum_type(['true', 'false']))
        c.argument('api', arg_type=get_enum_type(['true', 'false']))
        c.argument('retention', type=int)

    with self.argument_context('storage blob') as c:
        c.argument('blob_name',
                   options_list=('--name', '-n'),
                   arg_type=blob_name_type)
        c.argument(
            'destination_path',
            help='The destination path that will be appended to the blob name.'
        )

    with self.argument_context('storage blob list') as c:
        c.argument('include', validator=validate_included_datasets)
        c.argument('num_results', type=int)
        c.ignore('marker')  # https://github.com/Azure/azure-cli/issues/3745

    with self.argument_context('storage blob generate-sas') as c:
        from .completers import get_storage_acl_name_completion_list

        t_blob_permissions = self.get_sdk('blob.models#BlobPermissions')
        c.register_sas_arguments()
        c.argument(
            'id',
            options_list='--policy-name',
            help=
            'The name of a stored access policy within the container\'s ACL.',
            completer=get_storage_acl_name_completion_list(
                t_base_blob_service, 'container_name', 'get_container_acl'))
        c.argument('permission',
                   options_list='--permissions',
                   help=sas_help.format(
                       get_permission_help_string(t_blob_permissions)),
                   validator=get_permission_validator(t_blob_permissions))

    with self.argument_context('storage blob update') as c:
        t_blob_content_settings = self.get_sdk('blob.models#ContentSettings')
        c.register_content_settings_argument(t_blob_content_settings,
                                             update=True)

    with self.argument_context('storage blob exists') as c:
        c.argument('blob_name', required=True)

    with self.argument_context('storage blob url') as c:
        c.argument('protocol',
                   arg_type=get_enum_type(['http', 'https'], 'https'),
                   help='Protocol to use.')

    with self.argument_context('storage blob set-tier') as c:
        from ._validators import blob_tier_validator

        c.argument('blob_type',
                   options_list=('--type', '-t'),
                   arg_type=get_enum_type(('block', 'page')))
        c.argument('tier', validator=blob_tier_validator)
        c.argument('timeout', type=int)

    with self.argument_context(
            'storage blob service-properties delete-policy update') as c:
        c.argument('enable',
                   arg_type=get_enum_type(['true', 'false']),
                   help='Enables/disables soft-delete.')
        c.argument(
            'days_retained',
            type=int,
            help=
            'Number of days that soft-deleted blob will be retained. Must be in range [1,365].'
        )

    with self.argument_context('storage blob upload') as c:
        from ._validators import page_blob_tier_validator
        from .sdkutil import get_blob_types, get_blob_tier_names

        t_blob_content_settings = self.get_sdk('blob.models#ContentSettings')
        c.register_content_settings_argument(t_blob_content_settings,
                                             update=False)

        c.argument('file_path',
                   options_list=('--file', '-f'),
                   type=file_type,
                   completer=FilesCompleter())
        c.argument('max_connections', type=int)
        c.argument('blob_type',
                   options_list=('--type', '-t'),
                   validator=validate_blob_type,
                   arg_type=get_enum_type(get_blob_types()))
        c.argument('validate_content',
                   action='store_true',
                   min_api='2016-05-31')
        c.extra('no_progress', progress_type)
        c.extra('socket_timeout', socket_timeout_type)
        # TODO: Remove once #807 is complete. Smart Create Generation requires this parameter.
        # register_extra_cli_argument('storage blob upload', '_subscription_id', options_list=('--subscription',),
        #                              help=argparse.SUPPRESS)
        c.argument('tier',
                   validator=page_blob_tier_validator,
                   arg_type=get_enum_type(
                       get_blob_tier_names(self.cli_ctx,
                                           'PremiumPageBlobTier')),
                   min_api='2017-04-17')

    with self.argument_context('storage blob upload-batch') as c:
        from .sdkutil import get_blob_types
        from ._validators import process_blob_upload_batch_parameters

        t_blob_content_settings = self.get_sdk('blob.models#ContentSettings')
        c.register_content_settings_argument(t_blob_content_settings,
                                             update=False,
                                             arg_group='Content Control')
        c.ignore('source_files', 'destination_container_name')

        c.argument('source',
                   options_list=('--source', '-s'),
                   validator=process_blob_upload_batch_parameters)
        c.argument('destination', options_list=('--destination', '-d'))
        c.argument('max_connections', type=int)
        c.argument('maxsize_condition', arg_group='Content Control')
        c.argument('validate_content',
                   action='store_true',
                   min_api='2016-05-31',
                   arg_group='Content Control')
        c.argument('blob_type',
                   options_list=('--type', '-t'),
                   arg_type=get_enum_type(get_blob_types()))
        c.extra('no_progress', progress_type)
        c.extra('socket_timeout', socket_timeout_type)

    with self.argument_context('storage blob download') as c:
        c.argument('file_path',
                   options_list=('--file', '-f'),
                   type=file_type,
                   completer=FilesCompleter())
        c.argument('max_connections', type=int)
        c.argument('start_range', type=int)
        c.argument('end_range', type=int)
        c.argument('validate_content',
                   action='store_true',
                   min_api='2016-05-31')
        c.extra('no_progress', progress_type)
        c.extra('socket_timeout', socket_timeout_type)

    with self.argument_context('storage blob download-batch') as c:
        from ._validators import process_blob_download_batch_parameters

        c.ignore('source_container_name')
        c.argument('destination', options_list=('--destination', '-d'))
        c.argument('source',
                   options_list=('--source', '-s'),
                   validator=process_blob_download_batch_parameters)
        c.extra('no_progress', progress_type)
        c.extra('socket_timeout', socket_timeout_type)
        c.argument('max_connections', type=int)

    with self.argument_context('storage blob delete') as c:
        from .sdkutil import get_delete_blob_snapshot_type_names
        c.argument('delete_snapshots',
                   arg_type=get_enum_type(
                       get_delete_blob_snapshot_type_names()))

    with self.argument_context('storage blob delete-batch') as c:
        from ._validators import process_blob_batch_source_parameters

        c.ignore('source_container_name')
        c.argument('source',
                   options_list=('--source', '-s'),
                   validator=process_blob_batch_source_parameters)
        c.argument('delete_snapshots',
                   arg_type=get_enum_type(
                       get_delete_blob_snapshot_type_names()))

    with self.argument_context('storage blob lease') as c:
        c.argument('lease_duration', type=int)
        c.argument('lease_break_period', type=int)
        c.argument('blob_name', arg_type=blob_name_type)

    with self.argument_context('storage blob copy') as c:
        for item in ['destination', 'source']:
            c.argument('{}_if_modified_since'.format(item),
                       arg_group='Pre-condition')
            c.argument('{}_if_unmodified_since'.format(item),
                       arg_group='Pre-condition')
            c.argument('{}_if_match'.format(item), arg_group='Pre-condition')
            c.argument('{}_if_none_match'.format(item),
                       arg_group='Pre-condition')
        c.argument('container_name',
                   container_name_type,
                   options_list=('--destination-container', '-c'))
        c.argument(
            'blob_name',
            blob_name_type,
            options_list=('--destination-blob', '-b'),
            help=
            'Name of the destination blob. If the exists, it will be overwritten.'
        )
        c.argument('source_lease_id', arg_group='Copy Source')

    with self.argument_context('storage blob copy start') as c:
        from ._validators import validate_source_uri

        c.register_source_uri_arguments(validator=validate_source_uri)

    with self.argument_context('storage blob copy start-batch',
                               arg_group='Copy Source') as c:
        from ._validators import (get_source_file_or_blob_service_client,
                                  process_blob_copy_batch_namespace)

        c.argument('source_client',
                   ignore_type,
                   validator=get_source_file_or_blob_service_client)

        c.extra('source_account_name')
        c.extra('source_account_key')
        c.extra('source_uri')
        c.argument('source_sas')
        c.argument('source_container')
        c.argument('source_share')
        c.argument('prefix', validator=process_blob_copy_batch_namespace)

    with self.argument_context('storage blob incremental-copy start') as c:
        from ._validators import process_blob_source_uri

        c.register_source_uri_arguments(validator=process_blob_source_uri,
                                        blob_only=True)
        c.argument('destination_if_modified_since', arg_group='Pre-condition')
        c.argument('destination_if_unmodified_since',
                   arg_group='Pre-condition')
        c.argument('destination_if_match', arg_group='Pre-condition')
        c.argument('destination_if_none_match', arg_group='Pre-condition')
        c.argument('container_name',
                   container_name_type,
                   options_list=('--destination-container', '-c'))
        c.argument(
            'blob_name',
            blob_name_type,
            options_list=('--destination-blob', '-b'),
            help=
            'Name of the destination blob. If the exists, it will be overwritten.'
        )
        c.argument('source_lease_id', arg_group='Copy Source')

    with self.argument_context('storage container') as c:
        from .sdkutil import get_container_access_type_names
        c.argument('container_name',
                   container_name_type,
                   options_list=('--name', '-n'))
        c.argument(
            'public_access',
            validator=validate_container_public_access,
            arg_type=get_enum_type(get_container_access_type_names()),
            help=
            'Specifies whether data in the container may be accessed publically. By default, container '
            'data is private ("off") to the account owner. Use "blob" to allow public read access for '
            'blobs. Use "container" to allow public read and list access to the entire container.'
        )

    with self.argument_context('storage container create') as c:
        c.argument('container_name',
                   container_name_type,
                   options_list=('--name', '-n'),
                   completer=None)
        c.argument('fail_on_exist',
                   help='Throw an exception if the container already exists.')

    with self.argument_context('storage container delete') as c:
        c.argument('fail_not_exist',
                   help='Throw an exception if the container does not exist.')

    with self.argument_context('storage container exists') as c:
        c.ignore('blob_name', 'snapshot')

    with self.argument_context('storage container set-permission') as c:
        c.ignore('signed_identifiers')

    with self.argument_context('storage container lease') as c:
        c.argument('container_name', container_name_type)

    with self.argument_context('storage container list') as c:
        c.ignore('marker')  # https://github.com/Azure/azure-cli/issues/3745

    with self.argument_context('storage container policy') as c:
        from .completers import get_storage_acl_name_completion_list
        t_container_permissions = self.get_sdk(
            'blob.models#ContainerPermissions')

        c.argument('container_name', container_name_type)
        c.argument('policy_name',
                   options_list=('--name', '-n'),
                   help='The stored access policy name.',
                   completer=get_storage_acl_name_completion_list(
                       t_base_blob_service, 'container_name',
                       'get_container_acl'))
        help_str = 'Allowed values: {}. Can be combined'.format(
            get_permission_help_string(t_container_permissions))
        c.argument('permission',
                   options_list='--permissions',
                   help=help_str,
                   validator=get_permission_validator(t_container_permissions))

        c.argument(
            'start',
            type=get_datetime_type(True),
            help=
            'start UTC datetime (Y-m-d\'T\'H:M:S\'Z\'). Defaults to time of request.'
        )
        c.argument('expiry',
                   type=get_datetime_type(True),
                   help='expiration UTC datetime in (Y-m-d\'T\'H:M:S\'Z\')')

    for item in ['create', 'delete', 'list', 'show', 'update']:
        with self.argument_context(
                'storage container policy {}'.format(item)) as c:
            c.extra('lease_id',
                    options_list='--lease-id',
                    help='The container lease ID.')

    with self.argument_context('storage container generate-sas') as c:
        from .completers import get_storage_acl_name_completion_list
        t_container_permissions = self.get_sdk(
            'blob.models#ContainerPermissions')
        c.register_sas_arguments()
        c.argument(
            'id',
            options_list='--policy-name',
            help=
            'The name of a stored access policy within the container\'s ACL.',
            completer=get_storage_acl_name_completion_list(
                t_container_permissions, 'container_name',
                'get_container_acl'))
        c.argument('permission',
                   options_list='--permissions',
                   help=sas_help.format(
                       get_permission_help_string(t_container_permissions)),
                   validator=get_permission_validator(t_container_permissions))

    with self.argument_context('storage container lease') as c:
        c.argument('lease_duration', type=int)
        c.argument('lease_break_period', type=int)

    with self.argument_context('storage container immutability-policy') as c:
        c.argument('immutability_period_since_creation_in_days',
                   options_list='--period')
        c.argument('container_name', container_name_type)
        c.argument('account_name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Storage/storageAccounts'))

    with self.argument_context('storage container legal-hold') as c:
        c.argument('container_name', container_name_type)
        c.argument('account_name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Storage/storageAccounts'))
        c.argument(
            'tags',
            nargs='+',
            help='Each tag should be 3 to 23 alphanumeric characters and is '
            'normalized to lower case')

    with self.argument_context('storage share') as c:
        c.argument('share_name',
                   share_name_type,
                   options_list=('--name', '-n'))

    with self.argument_context('storage share list') as c:
        c.ignore('marker')  # https://github.com/Azure/azure-cli/issues/3745

    with self.argument_context('storage share exists') as c:
        c.ignore('directory_name', 'file_name')

    with self.argument_context('storage share policy') as c:
        from .completers import get_storage_acl_name_completion_list

        t_file_svc = self.get_sdk('file#FileService')
        t_share_permissions = self.get_sdk('file.models#SharePermissions')

        c.argument('container_name', share_name_type)
        c.argument('policy_name',
                   options_list=('--name', '-n'),
                   help='The stored access policy name.',
                   completer=get_storage_acl_name_completion_list(
                       t_file_svc, 'container_name', 'get_share_acl'))

        help_str = 'Allowed values: {}. Can be combined'.format(
            get_permission_help_string(t_share_permissions))
        c.argument('permission',
                   options_list='--permissions',
                   help=help_str,
                   validator=get_permission_validator(t_share_permissions))

        c.argument(
            'start',
            type=get_datetime_type(True),
            help=
            'start UTC datetime (Y-m-d\'T\'H:M:S\'Z\'). Defaults to time of request.'
        )
        c.argument('expiry',
                   type=get_datetime_type(True),
                   help='expiration UTC datetime in (Y-m-d\'T\'H:M:S\'Z\')')

    with self.argument_context('storage share delete') as c:
        from .sdkutil import get_delete_file_snapshot_type_names
        c.argument(
            'delete_snapshots',
            arg_type=get_enum_type(get_delete_file_snapshot_type_names()),
            help='Specify the deletion strategy when the share has snapshots.')

    with self.argument_context('storage share generate-sas') as c:
        from .completers import get_storage_acl_name_completion_list

        t_share_permissions = self.get_sdk('file.models#SharePermissions')
        c.register_sas_arguments()
        c.argument(
            'id',
            options_list='--policy-name',
            help='The name of a stored access policy within the share\'s ACL.',
            completer=get_storage_acl_name_completion_list(
                t_share_permissions, 'share_name', 'get_share_acl'))
        c.argument('permission',
                   options_list='--permissions',
                   help=sas_help.format(
                       get_permission_help_string(t_share_permissions)),
                   validator=get_permission_validator(t_share_permissions))

    with self.argument_context('storage directory') as c:
        c.argument('directory_name',
                   directory_type,
                   options_list=('--name', '-n'))

    with self.argument_context('storage directory exists') as c:
        c.ignore('file_name')
        c.argument('directory_name', required=True)

    with self.argument_context('storage file') as c:
        c.argument('file_name', file_name_type, options_list=('--name', '-n'))
        c.argument('directory_name', directory_type, required=False)

    with self.argument_context('storage file copy') as c:
        c.argument('share_name',
                   share_name_type,
                   options_list=('--destination-share', '-s'),
                   help='Name of the destination share. The share must exist.')

    with self.argument_context('storage file copy start') as c:
        c.register_path_argument(options_list=('--destination-path', '-p'))

    with self.argument_context('storage file copy cancel') as c:
        c.register_path_argument(options_list=('--destination-path', '-p'))

    with self.argument_context('storage file delete') as c:
        c.register_path_argument()

    with self.argument_context('storage file download') as c:
        c.register_path_argument()
        c.argument(
            'file_path',
            options_list=('--dest', ),
            type=file_type,
            required=False,
            help=
            'Path of the file to write to. The source filename will be used if not specified.',
            validator=process_file_download_namespace,
            completer=FilesCompleter())
        c.argument(
            'path', validator=None
        )  # validator called manually from process_file_download_namespace
        c.extra('no_progress', progress_type)
        c.argument('max_connections', type=int)
        c.argument('start_range', type=int)
        c.argument('end_range', type=int)

    with self.argument_context('storage file exists') as c:
        c.register_path_argument()

    with self.argument_context('storage file generate-sas') as c:
        from .completers import get_storage_acl_name_completion_list

        c.register_path_argument()
        c.register_sas_arguments()

        t_file_svc = self.get_sdk('file.fileservice#FileService')
        t_file_permissions = self.get_sdk('file.models#FilePermissions')
        c.argument(
            'id',
            options_list='--policy-name',
            help=
            'The name of a stored access policy within the container\'s ACL.',
            completer=get_storage_acl_name_completion_list(
                t_file_svc, 'container_name', 'get_container_acl'))
        c.argument('permission',
                   options_list='--permissions',
                   help=sas_help.format(
                       get_permission_help_string(t_file_permissions)),
                   validator=get_permission_validator(t_file_permissions))

    with self.argument_context('storage file list') as c:
        from .completers import dir_path_completer
        c.argument('directory_name',
                   options_list=('--path', '-p'),
                   help='The directory path within the file share.',
                   completer=dir_path_completer)

    with self.argument_context('storage file metadata show') as c:
        c.register_path_argument()

    with self.argument_context('storage file metadata update') as c:
        c.register_path_argument()

    with self.argument_context('storage file resize') as c:
        c.register_path_argument()
        c.argument('content_length', options_list='--size')

    with self.argument_context('storage file show') as c:
        c.register_path_argument()

    with self.argument_context('storage file update') as c:
        t_file_content_settings = self.get_sdk('file.models#ContentSettings')

        c.register_path_argument()
        c.register_content_settings_argument(t_file_content_settings,
                                             update=True)

    with self.argument_context('storage file upload') as c:
        t_file_content_settings = self.get_sdk('file.models#ContentSettings')

        c.register_path_argument(default_file_param='local_file_path')
        c.register_content_settings_argument(t_file_content_settings,
                                             update=False,
                                             guess_from_file='local_file_path')
        c.argument('local_file_path',
                   options_list='--source',
                   type=file_type,
                   completer=FilesCompleter())
        c.extra('no_progress', progress_type)
        c.argument('max_connections', type=int)

    with self.argument_context('storage file url') as c:
        c.register_path_argument()
        c.argument('protocol',
                   arg_type=get_enum_type(['http', 'https'], 'https'),
                   help='Protocol to use.')

    with self.argument_context('storage file upload-batch') as c:
        from ._validators import process_file_upload_batch_parameters
        c.argument('source',
                   options_list=('--source', '-s'),
                   validator=process_file_upload_batch_parameters)
        c.argument('destination', options_list=('--destination', '-d'))
        c.argument('max_connections', arg_group='Download Control', type=int)
        c.argument('validate_content',
                   action='store_true',
                   min_api='2016-05-31')
        c.register_content_settings_argument(t_file_content_settings,
                                             update=False,
                                             arg_group='Content Settings')
        c.extra('no_progress', progress_type)

    with self.argument_context('storage file download-batch') as c:
        from ._validators import process_file_download_batch_parameters
        c.argument('source',
                   options_list=('--source', '-s'),
                   validator=process_file_download_batch_parameters)
        c.argument('destination', options_list=('--destination', '-d'))
        c.argument('max_connections', arg_group='Download Control', type=int)
        c.argument('validate_content',
                   action='store_true',
                   min_api='2016-05-31')
        c.extra('no_progress', progress_type)

    with self.argument_context('storage file delete-batch') as c:
        from ._validators import process_file_batch_source_parameters
        c.argument('source',
                   options_list=('--source', '-s'),
                   validator=process_file_batch_source_parameters)

    with self.argument_context('storage file copy start') as c:
        from ._validators import validate_source_uri

        c.register_source_uri_arguments(validator=validate_source_uri)

    with self.argument_context('storage file copy start-batch',
                               arg_group='Copy Source') as c:
        from ._validators import get_source_file_or_blob_service_client
        c.argument('source_client',
                   ignore_type,
                   validator=get_source_file_or_blob_service_client)
        c.extra('source_account_name')
        c.extra('source_account_key')
        c.extra('source_uri')
        c.argument('source_sas')
        c.argument('source_container')
        c.argument('source_share')

    with self.argument_context('storage cors list') as c:
        c.extra('services',
                validator=get_char_options_validator('bfqt', 'services'),
                default='bqft',
                options_list='--services',
                required=False)

    with self.argument_context('storage cors add') as c:
        c.extra('services',
                validator=get_char_options_validator('bfqt', 'services'),
                required=True,
                options_list='--services')
        c.argument('max_age')
        c.argument('origins', nargs='+')
        c.argument('methods',
                   nargs='+',
                   arg_type=get_enum_type([
                       'DELETE', 'GET', 'HEAD', 'MERGE', 'POST', 'OPTIONS',
                       'PUT'
                   ]))
        c.argument('allowed_headers', nargs='+')
        c.argument('exposed_headers', nargs='+')

    with self.argument_context('storage cors clear') as c:
        c.extra('services',
                validator=get_char_options_validator('bfqt', 'services'),
                required=True,
                options_list='--services')

    with self.argument_context('storage queue generate-sas') as c:
        from .completers import get_storage_acl_name_completion_list

        t_queue_permissions = self.get_sdk('queue.models#QueuePermissions')

        c.register_sas_arguments()

        c.argument(
            'id',
            options_list='--policy-name',
            help='The name of a stored access policy within the share\'s ACL.',
            completer=get_storage_acl_name_completion_list(
                t_queue_permissions, 'queue_name', 'get_queue_acl'))
        c.argument('permission',
                   options_list='--permissions',
                   help=sas_help.format(
                       get_permission_help_string(t_queue_permissions)),
                   validator=get_permission_validator(t_queue_permissions))

    with self.argument_context('storage queue') as c:
        c.argument('queue_name',
                   queue_name_type,
                   options_list=('--name', '-n'))

    with self.argument_context('storage queue create') as c:
        c.argument('queue_name',
                   queue_name_type,
                   options_list=('--name', '-n'),
                   completer=None)

    with self.argument_context('storage queue policy') as c:
        from .completers import get_storage_acl_name_completion_list

        t_queue_permissions = self.get_sdk('queue.models#QueuePermissions')

        c.argument('container_name', queue_name_type)
        c.argument('policy_name',
                   options_list=('--name', '-n'),
                   help='The stored access policy name.',
                   completer=get_storage_acl_name_completion_list(
                       t_queue_service, 'container_name', 'get_queue_acl'))

        help_str = 'Allowed values: {}. Can be combined'.format(
            get_permission_help_string(t_queue_permissions))
        c.argument('permission',
                   options_list='--permissions',
                   help=help_str,
                   validator=get_permission_validator(t_queue_permissions))

        c.argument(
            'start',
            type=get_datetime_type(True),
            help=
            'start UTC datetime (Y-m-d\'T\'H:M:S\'Z\'). Defaults to time of request.'
        )
        c.argument('expiry',
                   type=get_datetime_type(True),
                   help='expiration UTC datetime in (Y-m-d\'T\'H:M:S\'Z\')')

    with self.argument_context('storage message') as c:
        c.argument('queue_name', queue_name_type)
        c.argument('message_id', options_list='--id')
        c.argument('content',
                   type=unicode_string,
                   help='Message content, up to 64KB in size.')

    with self.argument_context('storage table') as c:
        c.argument('table_name',
                   table_name_type,
                   options_list=('--name', '-n'))

    with self.argument_context('storage table create') as c:
        c.argument('table_name',
                   table_name_type,
                   options_list=('--name', '-n'),
                   completer=None)
        c.argument('fail_on_exist',
                   help='Throw an exception if the table already exists.')

    with self.argument_context('storage table policy') as c:
        from ._validators import table_permission_validator
        from .completers import get_storage_acl_name_completion_list

        c.argument('container_name', table_name_type)
        c.argument('policy_name',
                   options_list=('--name', '-n'),
                   help='The stored access policy name.',
                   completer=get_storage_acl_name_completion_list(
                       t_table_service, 'table_name', 'get_table_acl'))

        help_str = 'Allowed values: (r)ead/query (a)dd (u)pdate (d)elete. Can be combined.'
        c.argument('permission',
                   options_list='--permissions',
                   help=help_str,
                   validator=table_permission_validator)

        c.argument(
            'start',
            type=get_datetime_type(True),
            help=
            'start UTC datetime (Y-m-d\'T\'H:M:S\'Z\'). Defaults to time of request.'
        )
        c.argument('expiry',
                   type=get_datetime_type(True),
                   help='expiration UTC datetime in (Y-m-d\'T\'H:M:S\'Z\')')

    with self.argument_context('storage table generate-sas') as c:
        from .completers import get_storage_acl_name_completion_list

        c.register_sas_arguments()
        c.argument(
            'id',
            options_list='--policy-name',
            help='The name of a stored access policy within the table\'s ACL.',
            completer=get_storage_acl_name_completion_list(
                t_table_service, 'table_name', 'get_table_acl'))
        c.argument(
            'permission',
            options_list='--permissions',
            help=sas_help.format('(r)ead/query (a)dd (u)pdate (d)elete'),
            validator=table_permission_validator)

    with self.argument_context('storage entity') as c:
        c.ignore('property_resolver')
        c.argument('entity',
                   options_list=('--entity', '-e'),
                   validator=validate_entity,
                   nargs='+')
        c.argument(
            'select',
            nargs='+',
            validator=validate_select,
            help='Space-separated list of properties to return for each entity.'
        )

    with self.argument_context('storage entity insert') as c:
        c.argument('if_exists',
                   arg_type=get_enum_type(['fail', 'merge', 'replace']))

    with self.argument_context('storage entity query') as c:
        c.argument(
            'accept',
            default='minimal',
            validator=validate_table_payload_format,
            arg_type=get_enum_type(['none', 'minimal', 'full']),
            help=
            'Specifies how much metadata to include in the response payload.')
Exemplo n.º 7
0
def load_arguments(self, _):
    from azure.mgmt.monitor.models import ConditionOperator, TimeAggregationOperator, EventData

    name_arg_type = CLIArgumentType(options_list=['--name', '-n'],
                                    metavar='NAME')
    webhook_prop_type = CLIArgumentType(validator=process_webhook_prop,
                                        nargs='*')

    autoscale_name_type = CLIArgumentType(
        options_list=['--autoscale-name'],
        help='Name of the autoscale settings.',
        id_part='name')
    autoscale_profile_name_type = CLIArgumentType(
        options_list=['--profile-name'], help='Name of the autoscale profile.')
    autoscale_rule_name_type = CLIArgumentType(
        options_list=['--rule-name'], help='Name of the autoscale rule.')
    scope_name_type = CLIArgumentType(
        help='Name of the Azure Monitor Private Link Scope.')

    with self.argument_context('monitor') as c:
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('tags', tags_type)

    # region Alerts
    with self.argument_context('monitor alert') as c:
        c.argument('rule_name',
                   name_arg_type,
                   id_part='name',
                   help='Name of the alert rule.')

    with self.argument_context('monitor alert create') as c:
        c.resource_parameter('target',
                             arg_group='Target Resource',
                             alias='target',
                             preserve_resource_group_parameter=True)
        c.argument('rule_name',
                   name_arg_type,
                   id_part='name',
                   help='Name of the alert rule.')
        c.argument('disabled', arg_type=get_three_state_flag())
        c.argument('condition', action=ConditionAction, nargs='+')

    with self.argument_context('monitor alert create',
                               arg_group='Action') as c:
        c.argument('custom_emails', nargs='+')
        c.argument('email_service_owners', arg_type=get_three_state_flag())
        c.argument('actions',
                   options_list=['--action', '-a'],
                   action=AlertAddAction,
                   nargs='+')

    with self.argument_context('monitor alert create',
                               arg_group='Condition') as c:
        c.argument('metric_name')
        c.argument('operator', arg_type=get_enum_type(ConditionOperator))
        c.argument('threshold')
        c.argument('time_aggregation',
                   arg_type=get_enum_type(TimeAggregationOperator))
        c.argument('window_size')

    with self.argument_context('monitor alert update') as c:
        c.argument('rule_name',
                   name_arg_type,
                   id_part='name',
                   help='Name of the alert rule.')
        c.resource_parameter('target',
                             arg_group='Target Resource',
                             required=False,
                             preserve_resource_group_parameter=True)

    with self.argument_context('monitor alert update',
                               arg_group='Action') as c:
        c.argument('email_service_owners', arg_type=get_three_state_flag())
        c.argument('add_actions',
                   options_list=['--add-action', '-a'],
                   nargs='+',
                   action=AlertAddAction)
        c.argument('remove_actions',
                   options_list=['--remove-action', '-r'],
                   nargs='+',
                   action=AlertRemoveAction)

    with self.argument_context('monitor alert update',
                               arg_group='Condition') as c:
        c.argument('condition', action=ConditionAction, nargs='+')
        c.argument('metric')
        c.argument('operator',
                   arg_type=get_enum_type(get_operator_map().keys()))
        c.argument('threshold')
        c.argument('aggregation',
                   arg_type=get_enum_type(get_aggregation_map().keys()))
        c.argument('period', type=get_period_type())

    for scope in [
            'monitor alert show-incident', 'monitor alert list-incidents'
    ]:
        with self.argument_context(scope) as c:
            c.argument('rule_name',
                       options_list=['--rule-name'],
                       id_part='name')
            c.argument('incident_name', name_arg_type, id_part='child_name_1')

    with self.argument_context('monitor alert list-incidents') as c:
        c.argument('rule_name', options_list=['--rule-name'], id_part=None)
    # endregion

    # region Metrics
    with self.argument_context('monitor metrics') as c:
        c.argument('metricnamespace',
                   options_list=['--namespace'],
                   help='Namespace to query metric definitions for.')

    with self.argument_context('monitor metrics list-definitions') as c:
        c.resource_parameter('resource_uri', arg_group='Target Resource')

    with self.argument_context('monitor metrics list') as c:
        from azure.mgmt.monitor.models import AggregationType
        c.resource_parameter('resource', arg_group='Target Resource')
        c.argument('metadata', action='store_true')
        c.argument('dimension', nargs='*', validator=validate_metric_dimension)
        c.argument('aggregation',
                   arg_type=get_enum_type(t for t in AggregationType
                                          if t.name != 'none'),
                   nargs='*')
        c.argument('metrics', nargs='+')
        c.argument(
            'orderby',
            help=
            'Aggregation to use for sorting results and the direction of the sort. Only one order can be specificed. Examples: sum asc'
        )
        c.argument(
            'top',
            help=
            'Max number of records to retrieve. Valid only if --filter used.')
        c.argument('filters', options_list='--filter')
        c.argument('metric_namespace', options_list='--namespace')

    with self.argument_context('monitor metrics list', arg_group='Time') as c:
        c.argument('start_time',
                   arg_type=get_datetime_type(help='Start time of the query.'))
        c.argument(
            'end_time',
            arg_type=get_datetime_type(
                help='End time of the query. Defaults to the current time.'))
        c.argument('offset', type=get_period_type(as_timedelta=True))
        c.argument('interval', arg_group='Time', type=get_period_type())
    # endregion

    # region MetricAlerts
    with self.argument_context('monitor metrics alert') as c:
        c.argument('rule_name',
                   name_arg_type,
                   id_part='name',
                   help='Name of the alert rule.')
        c.argument(
            'severity',
            type=int,
            help='Severity of the alert from 0 (critical) to 4 (verbose).')
        c.argument(
            'window_size',
            type=get_period_type(),
            help='Time over which to aggregate metrics in "##h##m##s" format.')
        c.argument(
            'evaluation_frequency',
            type=get_period_type(),
            help=
            'Frequency with which to evaluate the rule in "##h##m##s" format.')
        c.argument('auto_mitigate',
                   arg_type=get_three_state_flag(),
                   help='Automatically resolve the alert.')
        c.argument('condition',
                   options_list=['--condition'],
                   action=MetricAlertConditionAction,
                   nargs='+')
        c.argument('description', help='Free-text description of the rule.')
        c.argument('scopes',
                   nargs='+',
                   help='Space-separated list of scopes the rule applies to.')
        c.argument('disabled', arg_type=get_three_state_flag())
        c.argument('enabled',
                   arg_type=get_three_state_flag(),
                   help='Whether the metric alert rule is enabled.')

    with self.argument_context('monitor metrics alert create',
                               arg_group=None) as c:
        c.argument('actions',
                   options_list=['--action', '-a'],
                   action=MetricAlertAddAction,
                   nargs='+',
                   validator=get_action_group_validator('actions'))

    with self.argument_context('monitor metrics alert update',
                               arg_group='Action') as c:
        c.argument('add_actions',
                   options_list='--add-action',
                   action=MetricAlertAddAction,
                   nargs='+',
                   validator=get_action_group_validator('add_actions'))
        c.argument('remove_actions',
                   nargs='+',
                   validator=get_action_group_id_validator('remove_actions'))

    with self.argument_context('monitor metrics alert update',
                               arg_group='Condition') as c:
        c.argument('add_conditions',
                   options_list='--add-condition',
                   action=MetricAlertConditionAction,
                   nargs='+')
        c.argument('remove_conditions', nargs='+')
    # endregion

    # region Autoscale
    with self.argument_context('monitor autoscale') as c:
        c.argument('autoscale_name',
                   arg_type=autoscale_name_type,
                   options_list=['--name', '-n'])
        c.argument('autoscale_setting_name',
                   arg_type=autoscale_name_type,
                   options_list=['--name', '-n'])
        c.argument('profile_name', arg_type=autoscale_profile_name_type)
        c.argument('rule_name', arg_type=autoscale_rule_name_type)
        c.argument('enabled',
                   arg_type=get_three_state_flag(),
                   help='Autoscale settings enabled status.')

    with self.argument_context('monitor autoscale',
                               arg_group='Notification') as c:
        c.argument('actions',
                   options_list=['--action', '-a'],
                   action=AutoscaleAddAction,
                   nargs='+')
        c.argument('add_actions',
                   options_list=['--add-action', '-a'],
                   action=AutoscaleAddAction,
                   nargs='+')
        c.argument('remove_actions',
                   options_list=['--remove-action', '-r'],
                   action=AutoscaleRemoveAction,
                   nargs='+')
        c.argument('email_administrator',
                   arg_type=get_three_state_flag(),
                   help='Send email to subscription administrator on scaling.')
        c.argument(
            'email_coadministrators',
            arg_type=get_three_state_flag(),
            help='Send email to subscription co-administrators on scaling.')

    with self.argument_context('monitor autoscale create') as c:
        c.resource_parameter('resource', arg_group='Target Resource')
        c.argument('disabled',
                   arg_type=get_three_state_flag(),
                   help='Create the autoscale settings in a disabled state.')

    with self.argument_context('monitor autoscale',
                               arg_group='Instance Limit') as c:
        c.argument(
            'count',
            type=int,
            help=
            'The numer of instances to use. If used with --min/max-count, the default number of instances to use.'
        )
        c.argument('min_count',
                   type=int,
                   help='The minimum number of instances.')
        c.argument('max_count',
                   type=int,
                   help='The maximum number of instances.')

    with self.argument_context('monitor autoscale profile') as c:
        c.argument('autoscale_name',
                   arg_type=autoscale_name_type,
                   id_part=None)
        c.argument('profile_name',
                   arg_type=autoscale_profile_name_type,
                   options_list=['--name', '-n'])
        c.argument(
            'copy_rules',
            help=
            'Name of an existing schedule from which to copy the scaling rules for the new schedule.'
        )

    with self.argument_context(
            'monitor autoscale profile list-timezones') as c:
        c.argument('search_query',
                   options_list=['--search-query', '-q'],
                   help='Query text to find.')
        c.argument('offset',
                   help='Filter results based on UTC hour offset.',
                   type=timezone_offset_type)

    with self.argument_context('monitor autoscale profile',
                               arg_group='Schedule') as c:
        c.argument('timezone', type=timezone_name_type)
        c.argument('start',
                   arg_type=get_datetime_type(help='Start time.',
                                              timezone=False))
        c.argument('end',
                   arg_type=get_datetime_type(help='End time.',
                                              timezone=False))
        c.argument('recurrence',
                   options_list=['--recurrence', '-r'],
                   nargs='+',
                   validator=validate_autoscale_recurrence)

    with self.argument_context('monitor autoscale rule') as c:
        c.argument('autoscale_name',
                   arg_type=autoscale_name_type,
                   id_part=None)
        c.argument('rule_name',
                   arg_type=autoscale_rule_name_type,
                   options_list=['--name', '-n'])
        c.argument('scale',
                   help='The direction and amount to scale.',
                   action=AutoscaleScaleAction,
                   nargs='+')
        c.argument('condition',
                   help='Condition on which to scale.',
                   action=AutoscaleConditionAction,
                   nargs='+')
        c.argument('timegrain',
                   validator=validate_autoscale_timegrain,
                   nargs='+')
        c.argument(
            'cooldown',
            type=int,
            help=
            'The number of minutes that must elapse before another scaling event can occur.'
        )

    with self.argument_context('monitor autoscale rule delete') as c:
        c.argument(
            'index',
            nargs='+',
            help=
            "Space-separated list of rule indices to remove, or '*' to clear all rules."
        )

    with self.argument_context('monitor autoscale rule copy') as c:
        c.argument(
            'index',
            nargs='+',
            help=
            "Space-separated list of rule indices to copy, or '*' to copy all rules."
        )
        c.argument('source_profile',
                   options_list=['--source-schedule'],
                   help='Name of the profile to copy rules from.')
        c.argument('dest_profile',
                   options_list=['--dest-schedule'],
                   help='Name of the profile to copy rules to.')

    with self.argument_context('monitor autoscale rule create') as c:
        c.resource_parameter('source',
                             arg_group='Source',
                             required=False,
                             preserve_resource_group_parameter=True)
    # endregion

    # region Autoscale (OLD)
    with self.argument_context('monitor autoscale-settings') as c:
        c.argument('name', options_list=['--azure-resource-name'])
        c.argument('autoscale_setting_name', options_list=['--name', '-n'])

    with self.argument_context('monitor autoscale-settings create') as c:
        c.argument(
            'parameters',
            type=get_json_object,
            help=
            'JSON encoded parameters configuration. Use @{file} to load from a file. Use az autoscale-settings get-parameters-template to export json template.'
        )

    for scope in [
            'monitor autoscale-settings show',
            'monitor autoscale-settings delete'
    ]:
        with self.argument_context(scope) as c:
            c.argument('autoscale_setting_name', id_part='name')

    #  https://github.com/Azure/azure-rest-api-specs/issues/1017
    with self.argument_context('monitor autoscale-settings list') as c:
        c.ignore('filter')
    # endregion

    # region Diagnostic
    with self.argument_context('monitor diagnostic-settings') as c:
        c.argument('name', options_list=('--name', '-n'))

    with self.argument_context('monitor diagnostic-settings show') as c:
        c.resource_parameter('resource_uri',
                             required=True,
                             arg_group='Target Resource')

    with self.argument_context('monitor diagnostic-settings list') as c:
        c.resource_parameter('resource_uri', required=True)

    with self.argument_context('monitor diagnostic-settings delete') as c:
        c.resource_parameter('resource_uri',
                             required=True,
                             arg_group='Target Resource')

    with self.argument_context('monitor diagnostic-settings update') as c:
        c.resource_parameter('resource_uri',
                             required=True,
                             arg_group='Target Resource')

    with self.argument_context('monitor diagnostic-settings create') as c:
        c.resource_parameter('resource_uri',
                             required=True,
                             arg_group='Target Resource',
                             skip_validator=True)
        c.argument('logs', type=get_json_object)
        c.argument('metrics', type=get_json_object)

    with self.argument_context(
            'monitor diagnostic-settings categories list') as c:
        c.resource_parameter('resource_uri', required=True)

    with self.argument_context(
            'monitor diagnostic-settings categories show') as c:
        c.resource_parameter('resource_uri', required=True)
    # endregion

    # region LogProfiles
    with self.argument_context('monitor log-profiles') as c:
        c.argument('log_profile_name', options_list=['--name', '-n'])

    with self.argument_context('monitor log-profiles create') as c:
        c.argument('name', options_list=['--name', '-n'])
        c.argument('categories', nargs='+')
        c.argument('locations', nargs='+')
        c.argument('days', type=int, arg_group='Retention Policy')
        c.argument('enabled',
                   arg_type=get_three_state_flag(),
                   arg_group='Retention Policy')
    # endregion

    # region ActivityLog
    with self.argument_context('monitor activity-log list') as c:
        activity_log_props = [
            x['key'] for x in EventData()._attribute_map.values()
        ]  # pylint: disable=protected-access
        c.argument('select',
                   nargs='+',
                   arg_type=get_enum_type(activity_log_props))
        c.argument('max_events', type=int)

    with self.argument_context('monitor activity-log list',
                               arg_group='Time') as c:
        c.argument('start_time',
                   arg_type=get_datetime_type(help='Start time of the query.'))
        c.argument(
            'end_time',
            arg_type=get_datetime_type(
                help='End time of the query. Defaults to the current time.'))
        c.argument('offset', type=get_period_type(as_timedelta=True))

    with self.argument_context('monitor activity-log list',
                               arg_group='Filter') as c:
        c.argument('filters',
                   deprecate_info=c.deprecate(target='--filters',
                                              hide=True,
                                              expiration='3.0.0'),
                   help='OData filters. Will ignore other filter arguments.')
        c.argument('correlation_id')
        c.argument('resource_group', resource_group_name_type)
        c.argument('resource_id')
        c.argument('resource_provider',
                   options_list=[
                       '--namespace',
                       c.deprecate(target='--resource-provider',
                                   redirect='--namespace',
                                   hide=True,
                                   expiration='3.0.0')
                   ])
        c.argument('caller')
        c.argument('status')
    # endregion

    # region ActionGroup
    with self.argument_context('monitor action-group') as c:
        c.argument('action_group_name',
                   options_list=['--name', '-n'],
                   id_part='name')

    with self.argument_context('monitor action-group create') as c:
        from .validators import process_action_group_detail_for_creation
        from .actions import ActionGroupReceiverParameterAction
        c.extra('receivers',
                options_list=['--action', '-a'],
                nargs='+',
                arg_group='Actions',
                action=ActionGroupReceiverParameterAction,
                validator=process_action_group_detail_for_creation)
        c.extra('short_name')
        c.extra('tags')
        c.ignore('action_group')

    with self.argument_context('monitor action-group update',
                               arg_group='Actions') as c:
        c.extra('add_receivers',
                options_list=['--add-action', '-a'],
                nargs='+',
                action=ActionGroupReceiverParameterAction)
        c.extra('remove_receivers',
                options_list=['--remove-action', '-r'],
                nargs='+')
        c.ignore('action_group')

    with self.argument_context('monitor action-group enable-receiver') as c:
        c.argument('receiver_name', options_list=['--name', '-n'])
        c.argument('action_group_name', options_list=['--action-group'])
    # endregion

    # region ActivityLog Alerts
    with self.argument_context('monitor activity-log alert') as c:
        c.argument('activity_log_alert_name',
                   options_list=['--name', '-n'],
                   id_part='name')

    with self.argument_context('monitor activity-log alert create') as c:
        from .operations.activity_log_alerts import process_condition_parameter
        c.argument('disable', action='store_true')
        c.argument('scopes', options_list=['--scope', '-s'], nargs='+')
        c.argument('condition',
                   options_list=['--condition', '-c'],
                   nargs='+',
                   validator=process_condition_parameter)
        c.argument('action_groups',
                   options_list=['--action-group', '-a'],
                   nargs='+')
        c.argument('webhook_properties',
                   options_list=['--webhook-properties', '-w'],
                   arg_type=webhook_prop_type)

    with self.argument_context(
            'monitor activity-log alert update-condition') as c:
        c.argument('reset', action='store_true')
        c.argument('add_conditions',
                   options_list=['--add-condition', '-a'],
                   nargs='+')
        c.argument('remove_conditions',
                   options_list=['--remove-condition', '-r'],
                   nargs='+')

    with self.argument_context('monitor activity-log alert update') as c:
        from .operations.activity_log_alerts import process_condition_parameter
        c.argument('condition',
                   options_list=['--condition', '-c'],
                   nargs='+',
                   validator=process_condition_parameter)
        c.argument('enabled', arg_type=get_three_state_flag())

    with self.argument_context(
            'monitor activity-log alert action-group add') as c:
        c.argument('reset', action='store_true')
        c.argument('action_group_ids',
                   options_list=['--action-group', '-a'],
                   nargs='+')
        c.argument('webhook_properties',
                   options_list=['--webhook-properties', '-w'],
                   arg_type=webhook_prop_type)

    with self.argument_context(
            'monitor activity-log alert action-group remove') as c:
        c.argument('action_group_ids',
                   options_list=['--action-group', '-a'],
                   nargs='+')

    with self.argument_context('monitor activity-log alert scope add') as c:
        c.argument('scopes', options_list=['--scope', '-s'], nargs='+')
        c.argument('reset', action='store_true')

    with self.argument_context('monitor activity-log alert scope remove') as c:
        c.argument('scopes', options_list=['--scope', '-s'], nargs='+')
    # endregion

    # region Log Analytics Workspace
    with self.argument_context('monitor log-analytics workspace') as c:
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('workspace_name',
                   options_list=['--workspace-name', '-n'],
                   help="Name of the Log Analytics Workspace.")
        c.ignore('sku')
        c.argument('retention_time',
                   help="The workspace data retention in days.",
                   type=int,
                   default=30)
        from azure.mgmt.loganalytics.models import PublicNetworkAccessType
        c.argument(
            'public_network_access_for_ingestion',
            options_list=['--ingestion-access'],
            help=
            'The public network access type to access workspace ingestion.',
            arg_type=get_enum_type(PublicNetworkAccessType))
        c.argument(
            'public_network_access_for_query',
            options_list=['--query-access'],
            help='The public network access type to access workspace query.',
            arg_type=get_enum_type(PublicNetworkAccessType))

    with self.argument_context('monitor log-analytics workspace pack') as c:
        c.argument('intelligence_pack_name', options_list=['--name', '-n'])
        c.argument('workspace_name', options_list='--workspace-name')
    # endregion

    # region Log Analytics Workspace Linked Service
    with self.argument_context(
            'monitor log-analytics workspace linked-service') as c:
        c.argument(
            'linked_service_name',
            name_arg_type,
            help=
            'Name of the linkedServices resource. Supported values: cluster, automation.'
        )
        c.argument('workspace_name', options_list='--workspace-name')
        c.argument(
            'resource_id',
            help=
            'The resource id of the resource that will be linked to the workspace. This '
            'should be used for linking resources which require read access.')
        c.argument(
            'write_access_resource_id',
            help='The resource id of the resource that will be linked to the '
            'workspace. This should be used for linking resources which '
            'require write access.')
    # endregion

    # region Log Analytics Cluster
    with self.argument_context('monitor log-analytics cluster') as c:
        c.argument('cluster_name',
                   name_arg_type,
                   help='The name of the Log Analytics cluster.')
        c.argument(
            'sku_name',
            help=
            "The name of the SKU. Currently only support 'CapacityReservation'"
        )
        c.argument(
            'sku_capacity',
            help=
            'The capacity of the SKU. It must be in the range of 1000-2000 per day and must'
            ' be in multiples of 100. If you want to increase the limit, please contact'
            ' [email protected]. It can be decreased only after 31 days.'
        )
        c.argument('identity_type',
                   help='The identity type. Supported values: SystemAssigned')

    with self.argument_context('monitor log-analytics cluster update') as c:
        c.argument(
            'key_vault_uri',
            help=
            'The Key Vault uri which holds the key associated with the Log Analytics cluster.'
        )
        c.argument(
            'key_name',
            help=
            'The name of the key associated with the Log Analytics cluster.')
        c.argument(
            'key_version',
            help=
            'The version of the key associated with the Log Analytics cluster.'
        )
    # endregion

    # region Log Analytics Linked Storage Account
    with self.argument_context(
            'monitor log-analytics workspace linked-storage') as c:
        from azure.mgmt.loganalytics.models import DataSourceType
        c.argument('data_source_type',
                   help='Data source type for the linked storage account.',
                   options_list=['--type'],
                   arg_type=get_enum_type(DataSourceType))
        c.argument('storage_account_ids',
                   nargs='+',
                   options_list=['--storage-accounts'],
                   help='List of Name or ID of Azure Storage Account.',
                   validator=validate_storage_accounts_name_or_id)
    # endregion

    # region monitor clone
    with self.argument_context('monitor clone') as c:
        c.argument('source_resource',
                   help="Resource ID of the source resource.")
        c.argument('target_resource',
                   help="Resource ID of the target resource.")
        c.argument(
            'always_clone',
            action='store_true',
            help="If this argument is applied, "
            "all monitor settings would be cloned instead of expanding its scope."
        )
        c.argument(
            'monitor_types',
            options_list=['--types', '-t'],
            arg_type=get_enum_type(['metricsAlert']),
            nargs='+',
            help='List of types of monitor settings which would be cloned.',
            default=['metricsAlert'])

    # region Private Link Resources
    for item in ['create', 'update', 'show', 'delete', 'list']:
        with self.argument_context(
                'monitor private-link-scope {}'.format(item)) as c:
            c.argument('scope_name',
                       scope_name_type,
                       options_list=['--name', '-n'])
    with self.argument_context('monitor private-link-scope create') as c:
        c.ignore('location')

    with self.argument_context(
            'monitor private-link-scope scoped-resource') as c:
        c.argument('scope_name', scope_name_type)
        c.argument('resource_name',
                   options_list=['--name', '-n'],
                   help='Name of the assigned resource.')
        c.argument(
            'linked_resource_id',
            options_list=['--linked-resource'],
            help=
            'ARM resource ID of the linked resource. It should be one of log analytics workspace or application insights component.'
        )

    with self.argument_context(
            'monitor private-link-scope private-link-resource') as c:
        c.argument('scope_name', scope_name_type)
        c.argument('group_name',
                   options_list=['--name', '-n'],
                   help='Name of the private link resource.')

    with self.argument_context(
            'monitor private-link-scope private-endpoint-connection') as c:
        c.argument('scope_name', scope_name_type)
        c.argument(
            'private_endpoint_connection_name',
            options_list=['--name', '-n'],
            help=
            'The name of the private endpoint connection associated with the private link scope.'
        )
    for item in ['approve', 'reject', 'show', 'delete']:
        with self.argument_context(
                'monitor private-link-scope private-endpoint-connection {}'.
                format(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 private link scope.'
            )
            c.extra(
                'connection_id',
                options_list=['--id'],
                help=
                'The ID of the private endpoint connection associated with the private link scope. You can get '
                'it using `az monitor private-link-scope show`.')
            c.argument('scope_name',
                       help='Name of the Azure Monitor Private Link Scope.',
                       required=False)
            c.argument(
                'resource_group_name',
                help='The resource group name of specified private link scope.',
                required=False)
            c.argument('description',
                       help='Comments for {} operation.'.format(item))
Exemplo n.º 8
0
def load_arguments(self, _):

    acr_arg_type = CLIArgumentType(metavar='ACR_NAME_OR_RESOURCE_ID')

    # 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('enable_ahub', options_list=['--enable-ahub'])
        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(
            'nodepool_tags',
            nargs='*',
            validator=validate_nodepool_tags,
            help=
            'space-separated tags: key[=value] [key[=value] ...]. Use "" to clear existing tags.'
        )
        c.argument(
            'nodepool_labels',
            nargs='*',
            validator=validate_nodepool_labels,
            help=
            'space-separated labels: key[=value] [key[=value] ...]. You can not change the node labels through CLI after creation. See https://aka.ms/node-labels for syntax of labels.'
        )
        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',
                   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([
                       CONST_OUTBOUND_TYPE_LOAD_BALANCER,
                       CONST_OUTBOUND_TYPE_USER_DEFINED_ROUTING
                   ]))
        c.argument('enable_addons',
                   options_list=['--enable-addons', '-a'],
                   validator=validate_addons)
        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(['azure', 'kubenet']))
        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',
                   type=str,
                   validator=validate_vnet_subnet_id)
        c.argument('pod_subnet_id', type=str, validator=validate_pod_subnet_id)
        c.argument('ppg')
        c.argument('workspace_resource_id')
        c.argument('skip_subnet_role_assignment', action='store_true')
        c.argument('enable_fips_image', action='store_true', is_preview=True)
        c.argument('enable_cluster_autoscaler', action='store_true')
        c.argument('uptime_sla', action='store_true')
        c.argument('cluster_autoscaler_profile',
                   nargs='+',
                   validator=validate_cluster_autoscaler_profile)
        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',
                   help='To be deprecated. Use vm_set_type instead.')
        c.argument('vm_set_type', type=str, validator=validate_vm_set_type)
        c.argument(
            'node_zones',
            zones_type,
            options_list=['--node-zones', '--zones', '-z'],
            help=
            '(--node-zones will be deprecated, use --zones) Space-separated list of availability zones where agent nodes will be placed.'
        )
        c.argument('enable_node_public_ip', action='store_true')
        c.argument('node_public_ip_prefix_id', type=str)
        c.argument('enable_pod_security_policy', action='store_true')
        c.argument('node_resource_group')
        c.argument('attach_acr', acr_arg_type)
        c.argument('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)
        c.argument('enable_ahub', options_list=['--enable-ahub'])
        c.argument('disable_ahub', options_list=['--disable-ahub'])
        c.argument('aks_custom_headers')
        c.argument('enable_private_cluster', action='store_true')
        c.argument('private_dns_zone')
        c.argument('fqdn_subdomain')
        c.argument('enable_managed_identity', action='store_true')
        c.argument('assign_identity',
                   type=str,
                   validator=validate_assign_identity)
        c.argument('enable_sgxquotehelper', action='store_true')
        c.argument('auto_upgrade_channel',
                   arg_type=get_enum_type([
                       CONST_RAPID_UPGRADE_CHANNEL,
                       CONST_STABLE_UPGRADE_CHANNEL,
                       CONST_PATCH_UPGRADE_CHANNEL,
                       CONST_NODE_IMAGE_UPGRADE_CHANNEL,
                       CONST_NONE_UPGRADE_CHANNEL
                   ]))
        c.argument('kubelet_config', type=str)
        c.argument('linux_os_config', type=str)
        c.argument('enable_pod_identity', action='store_true')
        c.argument('appgw_name',
                   options_list=['--appgw-name'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_prefix',
                   options_list=['--appgw-subnet-prefix'],
                   arg_group='Application Gateway',
                   deprecate_info=c.deprecate(redirect='--appgw-subnet-cidr',
                                              hide=True))
        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('aci_subnet_name', type=str)
        c.argument('enable_encryption_at_host',
                   arg_type=get_three_state_flag(),
                   help='Enable EncryptionAtHost.')
        c.argument('enable_secret_rotation', action='store_true')
        c.argument('assign_kubelet_identity',
                   type=str,
                   validator=validate_assign_kubelet_identity)
        c.argument('disable_local_accounts', action='store_true')
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.',
                   action='store_true')

    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='+',
                   validator=validate_cluster_autoscaler_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('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('attach_acr', acr_arg_type, validator=validate_acr)
        c.argument('detach_acr', acr_arg_type, validator=validate_acr)
        c.argument('aks_custom_headers')
        c.argument('auto_upgrade_channel',
                   arg_type=get_enum_type([
                       CONST_RAPID_UPGRADE_CHANNEL,
                       CONST_STABLE_UPGRADE_CHANNEL,
                       CONST_PATCH_UPGRADE_CHANNEL,
                       CONST_NODE_IMAGE_UPGRADE_CHANNEL,
                       CONST_NONE_UPGRADE_CHANNEL
                   ]))
        c.argument('enable_managed_identity', action='store_true')
        c.argument('assign_identity',
                   type=str,
                   validator=validate_assign_identity)
        c.argument('enable_pod_identity', action='store_true')
        c.argument('disable_pod_identity', action='store_true')
        c.argument('enable_secret_rotation', action='store_true')
        c.argument('disable_secret_rotation', action='store_true')
        c.argument('windows_admin_password',
                   options_list=['--windows-admin-password'])
        c.argument('disable_local_accounts', action='store_true')
        c.argument('enable_local_accounts', action='store_true')
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.',
                   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)
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.',
                   action='store_true')

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

    for scope in [
            'aks maintenanceconfiguration add',
            'aks maintenanceconfiguration update'
    ]:
        with self.argument_context(scope) as c:
            c.argument('config_name',
                       type=str,
                       options_list=['--name', '-n'],
                       help='The config name.')
            c.argument('config_file',
                       type=str,
                       options_list=['--config-file'],
                       help='The config json file.',
                       required=False)
            c.argument(
                'weekday',
                type=str,
                options_list=['--weekday'],
                help='weekday on which maintenance can happen. e.g. Monday',
                required=False)
            c.argument(
                'start_hour',
                type=int,
                options_list=['--start-hour'],
                help=
                'maintenance start hour of 1 hour window on the weekday. e.g. 1 means 1:00am - 2:00am',
                required=False)

    for scope in [
            'aks maintenanceconfiguration show',
            'aks maintenanceconfiguration delete'
    ]:
        with self.argument_context(scope) as c:
            c.argument('config_name',
                       type=str,
                       options_list=['--name', '-n'],
                       help='The config name.')

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

    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"')

    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('tags', tags_type)
            c.argument(
                'node_zones',
                zones_type,
                options_list=['--node-zones', '--zones', '-z'],
                help=
                '(--node-zones will be deprecated) Space-separated list of availability zones where agent nodes will be placed.'
            )
            c.argument('enable_node_public_ip', action='store_true')
            c.argument('node_public_ip_prefix_id', type=str)
            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('enable_fips_image',
                       action='store_true',
                       is_preview=True)
            c.argument('enable_cluster_autoscaler',
                       options_list=["--enable-cluster-autoscaler", "-e"],
                       action='store_true')
            c.argument('node_taints', type=str, validator=validate_taints)
            c.argument('priority',
                       arg_type=get_enum_type([
                           CONST_SCALE_SET_PRIORITY_REGULAR,
                           CONST_SCALE_SET_PRIORITY_SPOT
                       ]),
                       validator=validate_priority)
            c.argument('eviction_policy',
                       arg_type=get_enum_type([
                           CONST_SPOT_EVICTION_POLICY_DELETE,
                           CONST_SPOT_EVICTION_POLICY_DEALLOCATE
                       ]),
                       validator=validate_eviction_policy)
            c.argument('spot_max_price',
                       type=float,
                       validator=validate_spot_max_price)
            c.argument('labels', nargs='*', validator=validate_nodepool_labels)
            c.argument('mode',
                       arg_type=get_enum_type([
                           CONST_NODEPOOL_MODE_SYSTEM, CONST_NODEPOOL_MODE_USER
                       ]))
            c.argument('aks_custom_headers')
            c.argument('ppg')
            c.argument('max_surge', type=str, validator=validate_max_surge)
            c.argument('node_os_disk_type',
                       arg_type=get_enum_type([
                           CONST_OS_DISK_TYPE_MANAGED,
                           CONST_OS_DISK_TYPE_EPHEMERAL
                       ]))
            c.argument('vnet_subnet_id',
                       type=str,
                       validator=validate_vnet_subnet_id)
            c.argument('pod_subnet_id',
                       type=str,
                       validator=validate_pod_subnet_id)
            c.argument('kubelet_config', type=str)
            c.argument('linux_os_config', type=str)
            c.argument('enable_encryption_at_host',
                       options_list=['--enable-encryption-at-host'],
                       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 upgrade') as c:
        c.argument('max_surge', type=str, validator=validate_max_surge)

    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')
        c.argument('tags', tags_type)
        c.argument('mode',
                   arg_type=get_enum_type(
                       [CONST_NODEPOOL_MODE_SYSTEM, CONST_NODEPOOL_MODE_USER]))
        c.argument('max_surge', type=str, validator=validate_max_surge)

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

    with self.argument_context('aks enable-addons') as c:
        c.argument('addons',
                   options_list=['--addons', '-a'],
                   validator=validate_addons)
        c.argument('subnet_name', options_list=['--subnet-name', '-s'])
        c.argument('enable_sgxquotehelper', action='store_true')
        c.argument('osm_mesh_name', options_list=['--osm-mesh-name'])
        c.argument('appgw_name',
                   options_list=['--appgw-name'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_prefix',
                   options_list=['--appgw-subnet-prefix'],
                   arg_group='Application Gateway',
                   deprecate_info=c.deprecate(redirect='--appgw-subnet-cidr',
                                              hide=True))
        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_secret_rotation', action='store_true')

    with self.argument_context('aks get-credentials') 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.')
        c.argument('user',
                   options_list=['--user', '-u'],
                   default='clusterUser',
                   validator=validate_user)
        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 pod-identity') as c:
        c.argument('cluster_name', type=str, help='The cluster name.')

    with self.argument_context('aks pod-identity add') as c:
        c.argument('identity_name',
                   type=str,
                   options_list=['--name', '-n'],
                   default=None,
                   required=False,
                   help='The pod identity name. Generate if not specified.',
                   validator=validate_pod_identity_resource_name(
                       'identity_name', required=False))
        c.argument('identity_namespace',
                   type=str,
                   options_list=['--namespace'],
                   help='The pod identity namespace.')
        c.argument('identity_resource_id',
                   type=str,
                   options_list=['--identity-resource-id'],
                   help='Resource id of the identity to use.')
        c.argument('binding_selector',
                   type=str,
                   options_list=['--binding-selector'],
                   help='Optional binding selector to use.')

    with self.argument_context('aks pod-identity delete') as c:
        c.argument('identity_name',
                   type=str,
                   options_list=['--name', '-n'],
                   default=None,
                   required=True,
                   help='The pod identity name.',
                   validator=validate_pod_identity_resource_name(
                       'identity_name', required=True))
        c.argument('identity_namespace',
                   type=str,
                   options_list=['--namespace'],
                   help='The pod identity namespace.')

    with self.argument_context('aks pod-identity exception add') as c:
        c.argument(
            'exc_name',
            type=str,
            options_list=['--name', '-n'],
            default=None,
            required=False,
            help='The pod identity exception name. Generate if not specified.',
            validator=validate_pod_identity_resource_name('exc_name',
                                                          required=False))
        c.argument('exc_namespace',
                   type=str,
                   options_list=['--namespace'],
                   required=True,
                   help='The pod identity exception namespace.',
                   validator=validate_pod_identity_resource_namespace)
        c.argument('pod_labels',
                   nargs='*',
                   required=True,
                   help='space-separated labels: key=value [key=value ...].',
                   validator=validate_pod_identity_pod_labels)

    with self.argument_context('aks pod-identity exception delete') as c:
        c.argument('exc_name',
                   type=str,
                   options_list=['--name', '-n'],
                   required=True,
                   help='The pod identity exception name to remove.',
                   validator=validate_pod_identity_resource_name(
                       'exc_name', required=True))
        c.argument('exc_namespace',
                   type=str,
                   options_list=['--namespace'],
                   required=True,
                   help='The pod identity exception namespace to remove.',
                   validator=validate_pod_identity_resource_namespace)

    with self.argument_context('aks pod-identity exception update') as c:
        c.argument('exc_name',
                   type=str,
                   options_list=['--name', '-n'],
                   required=True,
                   help='The pod identity exception name to remove.',
                   validator=validate_pod_identity_resource_name(
                       'exc_name', required=True))
        c.argument('exc_namespace',
                   type=str,
                   options_list=['--namespace'],
                   required=True,
                   help='The pod identity exception namespace to remove.',
                   validator=validate_pod_identity_resource_namespace)
        c.argument('pod_labels',
                   nargs='*',
                   required=True,
                   help='pod labels in key=value [key=value ...].',
                   validator=validate_pod_identity_pod_labels)
Exemplo n.º 9
0
def load_arguments(self, _):

    # 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), P1V2(Premium V2 Small), PC2 (Premium Container Small), PC3 (Premium Container Medium), PC4 (Premium Container Large)',
        arg_type=get_enum_type([
            'F1', 'FREE', 'D1', 'SHARED', 'B1', 'B2', 'B3', 'S1', 'S2', 'S3',
            'P1', 'P2', 'P3', 'P1V2', 'P2V2', 'P3V2', 'PC2', 'PC3', 'PC4'
        ]))
    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 webapp. 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
    with self.argument_context('webapp') as c:
        c.ignore('app_instance')
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location', arg_type=get_location_type(self.cli_ctx))
        c.argument(
            'slot',
            options_list=['--slot', '-s'],
            help=
            "the name of the slot. Default to the productions slot if not specified"
        )
        c.argument(
            'name',
            configured_default='web',
            arg_type=name_arg_type,
            completer=get_resource_name_completion_list('Microsoft.Web/sites'),
            id_part='name',
            help=
            "name of the webapp. You can configure the default using 'az configure --defaults web=<name>'"
        )

    with self.argument_context('appservice') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location', arg_type=get_location_type(self.cli_ctx))

    with self.argument_context('appservice list-locations') as c:
        c.argument(
            'linux_workers_enabled',
            action='store_true',
            help='get regions which support hosting webapps on Linux workers')
        c.argument('sku', arg_type=sku_arg_type)

    with self.argument_context('appservice plan') as c:
        c.argument('name',
                   arg_type=name_arg_type,
                   help='The name of the app service plan',
                   completer=get_resource_name_completion_list(
                       'Microsoft.Web/serverFarms'),
                   configured_default='appserviceplan',
                   id_part='name')
        c.argument('number_of_workers',
                   help='Number of workers to be allocated.',
                   type=int,
                   default=1)
        c.argument('admin_site_name', help='The name of the admin web app.')

    with self.argument_context('appservice plan create') as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help="Name of the new app service plan",
                   completer=None)
        c.argument('sku', arg_type=sku_arg_type)
        c.argument('is_linux',
                   action='store_true',
                   required=False,
                   help='host webapp on Linux worker')
        c.argument('hyper_v',
                   action='store_true',
                   required=False,
                   help='(Preview) host webapp on Windows container')
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('appservice plan update') as c:
        c.argument('sku', arg_type=sku_arg_type)
        c.ignore('allow_pending_state')

    with self.argument_context('webapp create') as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='name of the new webapp')
        c.argument('startup_file', help="Linux only. The web's startup file")
        c.argument('multicontainer_config_type',
                   options_list=['--multicontainer-config-type'],
                   help="Linux only.",
                   arg_type=get_enum_type(MULTI_CONTAINER_TYPES))
        c.argument(
            'multicontainer_config_file',
            options_list=['--multicontainer-config-file'],
            help=
            "Linux only. Config file for multicontainer apps. (local or remote)"
        )
        c.argument(
            'runtime',
            options_list=['--runtime', '-r'],
            help=
            "canonicalized web runtime in the format of Framework|Version, e.g. \"PHP|5.6\". Use 'az webapp list-runtimes' for available list"
        )  # TODO ADD completer
        c.argument(
            'plan',
            options_list=['--plan', '-p'],
            configured_default='appserviceplan',
            completer=get_resource_name_completion_list(
                'Microsoft.Web/serverFarms'),
            help=
            "name or resource id of the app service plan. Use 'appservice plan create' to get one"
        )

    with self.argument_context('webapp show') as c:
        c.argument('name', arg_type=webapp_name_arg_type)

    with self.argument_context('webapp list-runtimes') as c:
        c.argument('linux',
                   action='store_true',
                   help='list runtime stacks for linux based webapps')

    with self.argument_context('webapp deleted list') as c:
        c.argument('name', arg_type=webapp_name_arg_type, id_part=None)
        c.argument('slot',
                   options_list=['--slot', '-s'],
                   help='Name of the deleted web app slot.')

    with self.argument_context('webapp deleted restore') as c:
        c.argument('deleted_id',
                   options_list=['--deleted-id'],
                   help='Resource ID of the deleted web app')
        c.argument(
            'name',
            options_list=['--name', '-n'],
            help='name of the web app to restore the deleted content to')
        c.argument('slot',
                   options_list=['--slot', '-s'],
                   help='slot to restore the deleted content to')
        c.argument('restore_content_only',
                   action='store_true',
                   help='restore only deleted files without web app settings')

    with self.argument_context('webapp traffic-routing') as c:
        c.argument(
            'distribution',
            options_list=['--distribution', '-d'],
            nargs='+',
            help=
            'space-separated slot routings in a format of <slot-name>=<percentage> e.g. staging=50. Unused traffic percentage will go to the Production slot'
        )

    with self.argument_context('webapp update') as c:
        c.argument('client_affinity_enabled',
                   help="Enables sending session affinity cookies.",
                   arg_type=get_three_state_flag(return_label=True))
        c.argument(
            'https_only',
            help="Redirect all traffic made to an app using HTTP to HTTPS.",
            arg_type=get_three_state_flag(return_label=True))
        c.argument(
            'force_dns_registration',
            help="If true, web app hostname is force registered with DNS",
            arg_type=get_three_state_flag(return_label=True))
        c.argument(
            'skip_custom_domain_verification',
            help=
            "If true, custom (non *.azurewebsites.net) domains associated with web app are not verified",
            arg_type=get_three_state_flag(return_label=True))
        c.argument(
            'ttl_in_seconds',
            help="Time to live in seconds for web app's default domain name",
            arg_type=get_three_state_flag(return_label=True))
        c.argument(
            'skip_dns_registration',
            help=
            "If true web app hostname is not registered with DNS on creation",
            arg_type=get_three_state_flag(return_label=True))

    with self.argument_context('webapp browse') as c:
        c.argument(
            'logs',
            options_list=['--logs', '-l'],
            action='store_true',
            help=
            'Enable viewing the log stream immediately after launching the web app'
        )
    with self.argument_context('webapp delete') as c:
        c.argument('keep_empty_plan',
                   action='store_true',
                   help='keep empty app service plan')
        c.argument('keep_metrics',
                   action='store_true',
                   help='keep app metrics')
        c.argument('keep_dns_registration',
                   action='store_true',
                   help='keep DNS registration')

    with self.argument_context('webapp webjob') as c:
        c.argument('webjob_name',
                   help='The name of the webjob',
                   options_list=['--webjob-name', '-w'])
    with self.argument_context('webapp webjob continuous list') as c:
        c.argument('name', arg_type=webapp_name_arg_type, id_part=None)
    with self.argument_context('webapp webjob triggered list') as c:
        c.argument('name', arg_type=webapp_name_arg_type, id_part=None)

    for scope in ['webapp', 'functionapp']:
        with self.argument_context(scope + ' create') as c:
            c.argument(
                'deployment_container_image_name',
                options_list=['--deployment-container-image-name', '-i'],
                help=
                'Linux only. Container image name from Docker Hub, e.g. publisher/image-name:tag'
            )
            c.argument('deployment_local_git',
                       action='store_true',
                       options_list=['--deployment-local-git', '-l'],
                       help='enable local git')
            c.argument('deployment_zip',
                       options_list=['--deployment-zip', '-z'],
                       help='perform deployment using zip file')
            c.argument(
                'deployment_source_url',
                options_list=['--deployment-source-url', '-u'],
                help='Git repository URL to link with manual integration')
            c.argument('deployment_source_branch',
                       options_list=['--deployment-source-branch', '-b'],
                       help='the branch to deploy')
            c.argument('tags', arg_type=tags_type)

        with self.argument_context(scope + ' config ssl bind') as c:
            c.argument('ssl_type',
                       help='The ssl cert type',
                       arg_type=get_enum_type(['SNI', 'IP']))
        with self.argument_context(scope + ' config ssl upload') as c:
            c.argument('certificate_password', help='The ssl cert password')
            c.argument('certificate_file',
                       type=file_type,
                       help='The filepath for the .pfx file')
        with self.argument_context(scope + ' config ssl') as c:
            c.argument('certificate_thumbprint',
                       help='The ssl cert thumbprint')
        with self.argument_context(scope + ' config appsettings') as c:
            c.argument(
                'settings',
                nargs='+',
                help=
                "space-separated app settings in a format of <name>=<value>")
            c.argument('setting_names',
                       nargs='+',
                       help="space-separated app setting names")

        with self.argument_context(scope + ' config hostname') as c:
            c.argument(
                'hostname',
                completer=get_hostname_completion_list,
                help="hostname assigned to the site, such as custom domains",
                id_part='child_name_1')
        with self.argument_context(scope + ' deployment user') as c:
            c.argument('user_name', help='user name')
            c.argument('password',
                       help='password, will prompt if not specified')
        with self.argument_context(scope + ' deployment source') as c:
            c.argument(
                'manual_integration',
                action='store_true',
                help='disable automatic sync between source control and web')
            c.argument(
                'repo_url',
                options_list=['--repo-url', '-u'],
                help=
                'repository url to pull the latest source from, e.g. https://github.com/foo/foo-web'
            )
            c.argument('branch', help='the branch name of the repository')
            c.argument('private_repo_username',
                       arg_group='VSTS CD Provider',
                       help='Username for the private repository')
            c.argument('private_repo_password',
                       arg_group='VSTS CD Provider',
                       help='Password for the private repository')
            c.argument(
                'cd_app_type',
                arg_group='VSTS CD Provider',
                help=
                'Web application framework you used to develop your app. Default is AspNet.',
                arg_type=get_enum_type(
                    ['AspNet', 'AspNetCore', 'NodeJS', 'PHP', 'Python']))
            c.argument(
                'app_working_dir',
                arg_group='VSTS CD Provider',
                help=
                'Working directory of the application. Default will be root of the repo'
            )
            c.argument('nodejs_task_runner',
                       arg_group='VSTS CD Provider',
                       help='Task runner for nodejs. Default is None',
                       arg_type=get_enum_type(['None', 'Gulp', 'Grunt']))
            c.argument(
                'python_framework',
                arg_group='VSTS CD Provider',
                help='Framework used for Python application. Default is Django',
                arg_type=get_enum_type(['Bottle', 'Django', 'Flask']))
            c.argument(
                'python_version',
                arg_group='VSTS CD Provider',
                help=
                'Python version used for application. Default is Python 3.5.3 x86',
                arg_type=get_enum_type([
                    'Python 2.7.12 x64', 'Python 2.7.12 x86',
                    'Python 2.7.13 x64', 'Python 2.7.13 x86',
                    'Python 3.5.3 x64', 'Python 3.5.3 x86', 'Python 3.6.0 x64',
                    'Python 3.6.0 x86', 'Python 3.6.2 x64', 'Python 3.6.1 x86'
                ]))
            c.argument(
                'cd_project_url',
                arg_group='VSTS CD Provider',
                help=
                'URL of the Visual Studio Team Services (VSTS) project to use for continuous delivery. URL should be in format https://<accountname>.visualstudio.com/<projectname>'
            )
            c.argument(
                'cd_account_create',
                arg_group='VSTS CD Provider',
                help=
                "To create a new Visual Studio Team Services (VSTS) account if it doesn't exist already",
                action='store_true')
            c.argument(
                'test',
                arg_group='VSTS CD Provider',
                help=
                'Name of the web app to be used for load testing. If web app is not available, it will be created. Default: Disable'
            )
            c.argument(
                'slot_swap',
                arg_group='VSTS CD Provider',
                help=
                'Name of the slot to be used for deployment and later promote to production. If slot is not available, it will be created. Default: Not configured'
            )
            c.argument('repository_type',
                       help='repository type',
                       arg_type=get_enum_type([
                           'git', 'mercurial', 'vsts', 'github', 'externalgit',
                           'localgit'
                       ]))
            c.argument('git_token',
                       help='Git access token required for auto sync')
        with self.argument_context(scope + ' identity') as c:
            c.argument('scope',
                       help="The scope the managed identity has access to")
            c.argument(
                'role',
                help="Role name or id the managed identity will be assigned")

        with self.argument_context(scope +
                                   ' deployment source config-zip') as c:
            c.argument('src', help='a zip file path for deployment')
            c.argument(
                'timeout',
                type=int,
                options_list=['--timeout', '-t'],
                help=
                'Configurable timeout in seconds for checking the status of deployment',
                validator=validate_timeout_value)

        with self.argument_context(scope + ' config appsettings list') as c:
            c.argument('name', arg_type=webapp_name_arg_type, id_part=None)

        with self.argument_context(scope + ' config hostname list') as c:
            c.argument('webapp_name',
                       arg_type=webapp_name_arg_type,
                       id_part=None,
                       options_list='--webapp-name')

        with self.argument_context(scope + ' cors') 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 "*" and remove all other origins from the list'
            )

        with self.argument_context(scope + ' config set') as c:
            c.argument('remote_debugging_enabled',
                       help='enable or disable remote debugging',
                       arg_type=get_three_state_flag(return_label=True))
            c.argument('web_sockets_enabled',
                       help='enable or disable web sockets',
                       arg_type=get_three_state_flag(return_label=True))
            c.argument(
                'always_on',
                help=
                'ensure webapp gets loaded all the time, rather unloaded after been idle. Recommended when you have continuous web jobs running',
                arg_type=get_three_state_flag(return_label=True))
            c.argument('auto_heal_enabled',
                       help='enable or disable auto heal',
                       arg_type=get_three_state_flag(return_label=True))
            c.argument('use32_bit_worker_process',
                       options_list=['--use-32bit-worker-process'],
                       help='use 32 bits worker process or not',
                       arg_type=get_three_state_flag(return_label=True))
            c.argument(
                'php_version',
                help=
                'The version used to run your web app if using PHP, e.g., 5.5, 5.6, 7.0'
            )
            c.argument(
                'python_version',
                help=
                'The version used to run your web app if using Python, e.g., 2.7, 3.4'
            )
            c.argument(
                'net_framework_version',
                help=
                "The version used to run your web app if using .NET Framework, e.g., 'v4.0' for .NET 4.6 and 'v3.0' for .NET 3.5"
            )
            c.argument(
                'linux_fx_version',
                help=
                "The runtime stack used for your linux-based webapp, e.g., \"RUBY|2.3\", \"NODE|6.6\", \"PHP|5.6\", \"DOTNETCORE|1.1.0\". See https://aka.ms/linux-stacks for more info."
            )
            c.argument(
                'windows_fx_version',
                help=
                "(Preview) a docker image name used for your windows ontainer webapp, e.g., microsoft/nanoserver:ltsc2016"
            )
            if scope == 'functionapp':
                c.ignore('windows_fx_version')
            c.argument(
                'java_version',
                help=
                "The version used to run your web app if using Java, e.g., '1.7' for Java 7, '1.8' for Java 8"
            )
            c.argument('java_container',
                       help="The java container, e.g., Tomcat, Jetty")
            c.argument(
                'java_container_version',
                help=
                "The version of the java container, e.g., '8.0.23' for Tomcat")
            c.argument(
                'min_tls_version',
                help=
                "The minimum version of TLS required for SSL requests, e.g., '1.0', '1.1', '1.2'"
            )
            c.argument(
                'http20_enabled',
                help=
                "configures a web site to allow clients to connect over http2.0.",
                arg_type=get_three_state_flag(return_label=True))
            c.argument(
                'app_command_line',
                options_list=['--startup-file'],
                help=
                "The startup file for linux hosted web apps, e.g. 'process.json' for Node.js web"
            )
            c.argument(
                'ftps_state',
                help=
                "Set the Ftps state value for an app. Default value is 'AllAllowed'.",
                arg_type=get_enum_type(FTPS_STATE_TYPES))

    with self.argument_context('webapp config connection-string list') as c:
        c.argument('name', arg_type=webapp_name_arg_type, id_part=None)

    with self.argument_context('webapp config storage-account list') as c:
        c.argument('name', arg_type=webapp_name_arg_type, id_part=None)

    with self.argument_context('webapp config hostname') as c:
        c.argument(
            'webapp_name',
            help=
            "webapp name. You can configure the default using 'az configure --defaults web=<name>'",
            configured_default='web',
            completer=get_resource_name_completion_list('Microsoft.Web/sites'),
            id_part='name')
    with self.argument_context('webapp deployment container config') as c:
        c.argument('enable',
                   options_list=['--enable-cd', '-e'],
                   help='enable/disable continuous deployment',
                   arg_type=get_enum_type(['true', 'false']))
    with self.argument_context('webapp deployment slot') as c:
        c.argument('slot', help='the name of the slot')
        c.argument(
            'webapp',
            arg_type=name_arg_type,
            completer=get_resource_name_completion_list('Microsoft.Web/sites'),
            help='Name of the webapp',
            id_part='name')
        c.argument('auto_swap_slot',
                   help='target slot to auto swap',
                   default='production')
        c.argument('disable', help='disable auto swap', action='store_true')
        c.argument('target_slot',
                   help="target slot to swap, default to 'production'")
    with self.argument_context('webapp deployment slot create') as c:
        c.argument(
            'configuration_source',
            help=
            "source slot to clone configurations from. Use webapp's name to refer to the production slot"
        )
    with self.argument_context('webapp deployment slot swap') as c:
        c.argument(
            'action',
            help=
            "swap types. use 'preview' to apply target slot's settings on the source slot first; use 'swap' to complete it; use 'reset' to reset the swap",
            arg_type=get_enum_type(['swap', 'preview', 'reset']))
    with self.argument_context('webapp log config') as c:
        c.argument('application_logging',
                   help='configure application logging to file system',
                   arg_type=get_three_state_flag(return_label=True))
        c.argument('detailed_error_messages',
                   help='configure detailed error messages',
                   arg_type=get_three_state_flag(return_label=True))
        c.argument('failed_request_tracing',
                   help='configure failed request tracing',
                   arg_type=get_three_state_flag(return_label=True))
        c.argument('level',
                   help='logging level',
                   arg_type=get_enum_type(
                       ['error', 'warning', 'information', 'verbose']))
        c.argument('web_server_logging',
                   help='configure Web server logging',
                   arg_type=get_enum_type(['off', 'filesystem']))
        c.argument(
            'docker_container_logging',
            help='configure gathering STDOUT and STDERR output from container',
            arg_type=get_enum_type(['off', 'filesystem']))

    with self.argument_context('webapp log tail') as c:
        c.argument(
            'provider',
            help=
            "By default all live traces configured by 'az webapp log config' will be shown, but you can scope to certain providers/folders, e.g. 'application', 'http', etc. For details, check out https://github.com/projectkudu/kudu/wiki/Diagnostic-Log-Stream"
        )
    with self.argument_context('webapp log download') as c:
        c.argument('log_file',
                   default='webapp_logs.zip',
                   type=file_type,
                   completer=FilesCompleter(),
                   help='the downloaded zipped log file path')

    for scope in ['appsettings', 'connection-string']:
        with self.argument_context('webapp config ' + scope) as c:
            c.argument(
                'settings',
                nargs='+',
                help="space-separated {} in a format of <name>=<value>".format(
                    scope))
            c.argument(
                'slot_settings',
                nargs='+',
                help="space-separated slot {} in a format of <name>=<value>".
                format(scope))
            c.argument('setting_names',
                       nargs='+',
                       help="space-separated {} names".format(scope))

    with self.argument_context('webapp config connection-string') as c:
        c.argument('connection_string_type',
                   options_list=['--connection-string-type', '-t'],
                   help='connection string type',
                   arg_type=get_enum_type(ConnectionStringType))

    with self.argument_context('webapp config storage-account') as c:
        c.argument('custom_id',
                   options_list=['--custom-id', '-i'],
                   help='custom identifier')
        c.argument('storage_type',
                   options_list=['--storage-type', '-t'],
                   help='storage type',
                   arg_type=get_enum_type(AzureStorageType))
        c.argument('account_name',
                   options_list=['--account-name', '-a'],
                   help='storage account name')
        c.argument(
            'share_name',
            options_list=['--share-name', '--sn'],
            help=
            'share name (Azure Files) or container name (Azure Blob Storage)')
        c.argument('access_key',
                   options_list=['--access-key', '-k'],
                   help='storage account access key')
        c.argument('mount_path',
                   options_list=['--mount-path', '-m'],
                   help='path to mount storage volume within web app')
        c.argument(
            'slot',
            options_list=['--slot', '-s'],
            help=
            "the name of the slot. Default to the productions slot if not specified"
        )
    with self.argument_context('webapp config storage-account add') as c:
        c.argument('slot_setting',
                   options_list=['--slot-setting'],
                   help="slot setting")
    with self.argument_context('webapp config storage-account update') as c:
        c.argument('slot_setting',
                   options_list=['--slot-setting'],
                   help="slot setting")

    with self.argument_context('webapp config container') as c:
        c.argument('docker_registry_server_url',
                   options_list=['--docker-registry-server-url', '-r'],
                   help='the container registry server url')
        c.argument(
            'docker_custom_image_name',
            options_list=['--docker-custom-image-name', '-c', '-i'],
            help='the container custom image name and optionally the tag name')
        c.argument('docker_registry_server_user',
                   options_list=['--docker-registry-server-user', '-u'],
                   help='the container registry server username')
        c.argument('docker_registry_server_password',
                   options_list=['--docker-registry-server-password', '-p'],
                   help='the container registry server password')
        c.argument('websites_enable_app_service_storage',
                   options_list=['--enable-app-service-storage', '-t'],
                   help='enables platform storage (custom container only)',
                   arg_type=get_three_state_flag(return_label=True))
        c.argument('multicontainer_config_type',
                   options_list=['--multicontainer-config-type'],
                   help='config type',
                   arg_type=get_enum_type(MULTI_CONTAINER_TYPES))
        c.argument('multicontainer_config_file',
                   options_list=['--multicontainer-config-file'],
                   help="config file for multicontainer apps")
        c.argument(
            'show_multicontainer_config',
            action='store_true',
            help='shows decoded config if a multicontainer config is set')

    with self.argument_context('webapp config backup') as c:
        c.argument('storage_account_url',
                   help='URL with SAS token to the blob storage container',
                   options_list=['--container-url'])
        c.argument('webapp_name', help='The name of the webapp')
        c.argument('db_name',
                   help='Name of the database in the backup',
                   arg_group='Database')
        c.argument('db_connection_string',
                   help='Connection string for the database in the backup',
                   arg_group='Database')
        c.argument('db_type',
                   help='Type of database in the backup',
                   arg_group='Database',
                   arg_type=get_enum_type(DatabaseType))

    with self.argument_context('webapp config backup create') as c:
        c.argument(
            'backup_name',
            help=
            'Name of the backup. If unspecified, the backup will be named with the webapp name and a timestamp'
        )

    with self.argument_context('webapp config backup update') as c:
        c.argument(
            'backup_name',
            help=
            'Name of the backup. If unspecified, the backup will be named with the webapp name and a timestamp'
        )
        c.argument(
            'frequency',
            help=
            'How often to backup. Use a number followed by d or h, e.g. 5d = 5 days, 2h = 2 hours'
        )
        c.argument('keep_at_least_one_backup',
                   help='Always keep one backup, regardless of how old it is',
                   options_list=['--retain-one'],
                   arg_type=get_three_state_flag(return_label=True))
        c.argument(
            'retention_period_in_days',
            help=
            'How many days to keep a backup before automatically deleting it. Set to 0 for indefinite retention',
            options_list=['--retention'])

    with self.argument_context('webapp config backup restore') as c:
        c.argument('backup_name', help='Name of the backup to restore')
        c.argument(
            'target_name',
            help=
            'The name to use for the restored webapp. If unspecified, will default to the name that was used when the backup was created'
        )
        c.argument(
            'overwrite',
            help=
            'Overwrite the source webapp, if --target-name is not specified',
            action='store_true')
        c.argument('ignore_hostname_conflict',
                   help='Ignores custom hostnames stored in the backup',
                   action='store_true')

    with self.argument_context('webapp auth update') as c:
        c.argument('enabled', arg_type=get_three_state_flag(return_label=True))
        c.argument('token_store_enabled',
                   options_list=['--token-store'],
                   arg_type=get_three_state_flag(return_label=True),
                   help='use App Service Token Store')
        c.argument('action', arg_type=get_enum_type(AUTH_TYPES))
        c.argument(
            'runtime_version',
            help=
            'Runtime version of the Authentication/Authorization feature in use for the current app'
        )
        c.argument('token_refresh_extension_hours',
                   type=float,
                   help="Hours, must be formattable into a float")
        c.argument('allowed_external_redirect_urls',
                   nargs='+',
                   help="One or more urls (space-delimited).")
        c.argument(
            'client_id',
            options_list=['--aad-client-id'],
            arg_group='Azure Active Directory',
            help=
            'Application ID to integrate AAD organization account Sign-in into your web app'
        )
        c.argument('client_secret',
                   options_list=['--aad-client-secret'],
                   arg_group='Azure Active Directory',
                   help='AAD application secret')
        c.argument('allowed_audiences',
                   nargs='+',
                   options_list=['--aad-allowed-token-audiences'],
                   arg_group='Azure Active Directory',
                   help="One or more token audiences (space-delimited).")
        c.argument(
            'issuer',
            options_list=['--aad-token-issuer-url'],
            help=
            'This url can be found in the JSON output returned from your active directory endpoint using your tenantID. The endpoint can be queried from \'az cloud show\' at \"endpoints.activeDirectory\". '
            'The tenantID can be found using \'az account show\'. Get the \"issuer\" from the JSON at <active directory endpoint>/<tenantId>/.well-known/openid-configuration.',
            arg_group='Azure Active Directory')
        c.argument(
            'facebook_app_id',
            arg_group='Facebook',
            help=
            "Application ID to integrate Facebook Sign-in into your web app")
        c.argument('facebook_app_secret',
                   arg_group='Facebook',
                   help='Facebook Application client secret')
        c.argument(
            'facebook_oauth_scopes',
            nargs='+',
            help=
            "One or more facebook authentication scopes (space-delimited).",
            arg_group='Facebook')
        c.argument(
            'twitter_consumer_key',
            arg_group='Twitter',
            help='Application ID to integrate Twitter Sign-in into your web app'
        )
        c.argument('twitter_consumer_secret',
                   arg_group='Twitter',
                   help='Twitter Application client secret')
        c.argument(
            'google_client_id',
            arg_group='Google',
            help='Application ID to integrate Google Sign-in into your web app'
        )
        c.argument('google_client_secret',
                   arg_group='Google',
                   help='Google Application client secret')
        c.argument(
            'google_oauth_scopes',
            nargs='+',
            help="One or more Google authentication scopes (space-delimited).",
            arg_group='Google')
        c.argument(
            'microsoft_account_client_id',
            arg_group='Microsoft',
            help=
            "AAD V2 Application ID to integrate Microsoft account Sign-in into your web app"
        )
        c.argument('microsoft_account_client_secret',
                   arg_group='Microsoft',
                   help='AAD V2 Application client secret')
        c.argument(
            'microsoft_account_oauth_scopes',
            nargs='+',
            help=
            "One or more Microsoft authentification scopes (space-delimited).",
            arg_group='Microsoft')

    with self.argument_context('webapp up') as c:
        c.argument('name', arg_type=webapp_name_arg_type)
        c.argument('sku', arg_type=sku_arg_type)
        c.argument(
            'dryrun',
            help=
            "show summary of the create and deploy operation instead of executing it",
            default=False,
            action='store_true')

    with self.argument_context('functionapp') as c:
        c.ignore('app_instance', 'slot')
        c.argument('name',
                   arg_type=name_arg_type,
                   id_part='name',
                   help='name of the function app')
    with self.argument_context('functionapp config hostname') as c:
        c.argument('webapp_name',
                   arg_type=name_arg_type,
                   id_part='name',
                   help='name of the function app')
    with self.argument_context('functionapp create') as c:
        c.argument(
            'plan',
            options_list=['--plan', '-p'],
            configured_default='appserviceplan',
            completer=get_resource_name_completion_list(
                'Microsoft.Web/serverFarms'),
            help=
            "name or resource id of the function app service plan. Use 'appservice plan create' to get one"
        )
        c.argument('new_app_name',
                   options_list=['--name', '-n'],
                   help='name of the new function app')
        c.argument(
            'storage_account',
            options_list=['--storage-account', '-s'],
            help=
            'Provide a string value of a Storage Account in the provided Resource Group. Or Resource ID of a Storage Account in a different Resource Group'
        )
        c.argument(
            'consumption_plan_location',
            options_list=['--consumption-plan-location', '-c'],
            help=
            "Geographic location where Function App will be hosted. Use 'functionapp list-consumption-locations' to view available locations."
        )
        c.argument(
            'runtime',
            help=
            'The function runtime stack. Currently supported for Linux apps only',
            arg_type=get_enum_type(['dotnet', 'node', 'python']))
        c.argument('os_type',
                   arg_type=get_enum_type(OS_TYPES),
                   help="Set the OS type for the app to be created.")

    # For commands with shared impl between webapp and functionapp and has output, we apply type validation to avoid confusions
    with self.argument_context('functionapp show') as c:
        c.argument('name', arg_type=name_arg_type)
    with self.argument_context('functionapp config appsettings') as c:
        c.argument(
            'slot_settings',
            nargs='+',
            help=
            "space-separated slot app settings in a format of <name>=<value>")
Exemplo n.º 10
0
def load_arguments(self, _):
    from argcomplete.completers import FilesCompleter

    from azure.mgmt.resource.resources.models import DeploymentMode
    from azure.mgmt.resource.locks.models import LockLevel
    from azure.mgmt.resource.managedapplications.models import ApplicationLockLevel

    from azure.cli.core.commands.parameters import (
        resource_group_name_type, tag_type, tags_type, get_resource_group_completion_list, no_wait_type, file_type,
        get_enum_type, get_three_state_flag)
    from azure.cli.core.profiles import ResourceType

    from knack.arguments import ignore_type, CLIArgumentType

    from azure.cli.command_modules.resource._completers import (
        get_policy_completion_list, get_policy_set_completion_list, get_policy_assignment_completion_list,
        get_resource_types_completion_list, get_providers_completion_list)
    from azure.cli.command_modules.resource._validators import (
        validate_lock_parameters, validate_resource_lock, validate_group_lock, validate_subscription_lock, validate_metadata)

    # BASIC PARAMETER CONFIGURATION

    resource_name_type = CLIArgumentType(options_list=('--name', '-n'), help='The resource name. (Ex: myC)')
    resource_type_type = CLIArgumentType(help="The resource type (Ex: 'resC'). Can also accept namespace/type format (Ex: 'Microsoft.Provider/resC')")
    resource_namespace_type = CLIArgumentType(options_list=('--namespace',), completer=get_providers_completion_list, help="Provider namespace (Ex: 'Microsoft.Provider')")
    resource_parent_type = CLIArgumentType(required=False, options_list=['--parent'], help="The parent path (Ex: 'resA/myA/resB/myB')")
    existing_policy_definition_name_type = CLIArgumentType(options_list=('--name', '-n'), completer=get_policy_completion_list, help='The policy definition name')
    existing_policy_set_definition_name_type = CLIArgumentType(options_list=('--name', '-n'), completer=get_policy_set_completion_list, help='The policy set definition name')
    _PROVIDER_HELP_TEXT = 'the resource namespace, aka \'provider\''

    with self.argument_context('resource') as c:
        c.argument('no_wait', no_wait_type)
        c.argument('resource_group_name', resource_group_name_type, arg_group='Resource Id')
        c.ignore('resource_id')
        c.argument('resource_name', resource_name_type, arg_group='Resource Id')
        c.argument('api_version', help='The api version of the resource (omit for latest)', required=False, arg_group='Resource Id')
        c.argument('resource_provider_namespace', resource_namespace_type, arg_group='Resource Id')
        c.argument('resource_type', arg_type=resource_type_type, completer=get_resource_types_completion_list, arg_group='Resource Id')
        c.argument('parent_resource_path', resource_parent_type, arg_group='Resource Id')
        c.argument('tag', tag_type)
        c.argument('tags', tags_type)
        c.argument('resource_ids', nargs='+', options_list=['--ids'], help='One or more resource IDs (space-delimited). If provided, no other "Resource Id" arguments should be specified.', arg_group='Resource Id')
        c.argument('include_response_body', arg_type=get_three_state_flag(), help='Use if the default command output doesn\'t capture all of the property data.')

    with self.argument_context('resource list') as c:
        c.argument('name', resource_name_type)

    with self.argument_context('resource move') as c:
        c.argument('ids', nargs='+')

    with self.argument_context('resource invoke-action') as c:
        c.argument('action', help='The action that will be invoked on the specified resource')
        c.argument('request_body', help='JSON encoded parameter arguments for the action that will be passed along in the post request body. Use @{file} to load from a file.')

    with self.argument_context('resource create') as c:
        c.argument('resource_id', options_list=['--id'], help='Resource ID.', action=None)
        c.argument('properties', options_list=('--properties', '-p'), help='a JSON-formatted string containing resource properties')
        c.argument('is_full_object', action='store_true', help='Indicates that the properties object includes other options such as location, tags, sku, and/or plan.')

    with self.argument_context('provider') as c:
        c.ignore('top')
        c.argument('resource_provider_namespace', options_list=('--namespace', '-n'), completer=get_providers_completion_list, help=_PROVIDER_HELP_TEXT)

    with self.argument_context('provider register') as c:
        c.argument('wait', action='store_true', help='wait for the registration to finish')

    with self.argument_context('provider unregister') as c:
        c.argument('wait', action='store_true', help='wait for unregistration to finish')

    with self.argument_context('provider operation') as c:
        c.argument('api_version', help="The api version of the 'Microsoft.Authorization/providerOperations' resource (omit for latest)")

    with self.argument_context('feature') as c:
        c.argument('resource_provider_namespace', options_list=('--namespace',), required=True, help=_PROVIDER_HELP_TEXT)
        c.argument('feature_name', options_list=('--name', '-n'), help='the feature name')

    with self.argument_context('feature list') as c:
        c.argument('resource_provider_namespace', options_list=('--namespace',), required=False, help=_PROVIDER_HELP_TEXT)

    with self.argument_context('policy') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type, help='the resource group where the policy will be applied')

    with self.argument_context('policy definition', resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('policy_definition_name', arg_type=existing_policy_definition_name_type)
        c.argument('rules', help='JSON formatted string or a path to a file with such content', type=file_type, completer=FilesCompleter())
        c.argument('display_name', help='display name of policy definition')
        c.argument('description', help='description of policy definition')
        c.argument('params', help='JSON formatted string or a path to a file or uri with parameter definitions', type=file_type, completer=FilesCompleter(), min_api='2016-12-01')
        c.argument('metadata', min_api='2017-06-01-preview', nargs='+', validator=validate_metadata, help='Metadata in space-separated key=value pairs.')

    with self.argument_context('policy definition create', resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        from azure.mgmt.resource.policy.models import PolicyMode
        c.argument('name', options_list=('--name', '-n'), help='name of the new policy definition')
        c.argument('mode', arg_type=get_enum_type(PolicyMode), options_list=('--mode', '-m'), help='mode of the new policy definition.', min_api='2016-12-01')

    with self.argument_context('policy assignment', resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('name', options_list=('--name', '-n'), completer=get_policy_assignment_completion_list, help='name of the assignment')
        c.argument('scope', help='scope at which this policy assignment applies to, e.g., /subscriptions/0b1f6471-1bf0-4dda-aec3-111122223333, /subscriptions/0b1f6471-1bf0-4dda-aec3-111122223333/resourceGroups/myGroup, or /subscriptions/0b1f6471-1bf0-4dda-aec3-111122223333/resourceGroups/myGroup/providers/Microsoft.Compute/virtualMachines/myVM')
        c.argument('disable_scope_strict_match', action='store_true', help='include assignment either inherited from parent scope or at child scope')
        c.argument('display_name', help='display name of the assignment')
        c.argument('policy', help='name or id of the policy definition.', completer=get_policy_completion_list)

    with self.argument_context('policy assignment create', resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('name', options_list=('--name', '-n'), help='name of the new assignment')
        c.argument('params', options_list=('--params', '-p'), help='JSON formatted string or path to file with parameter values of policy rule', min_api='2016-12-01')

    with self.argument_context('policy assignment create', resource_type=ResourceType.MGMT_RESOURCE_POLICY, min_api='2017-06-01-preview') as c:
        c.argument('policy_set_definition', options_list=('--policy-set-definition', '-d'), help='name or id of the policy set definition.')
        c.argument('sku', options_list=('--sku', '-s'), help='policy sku.', arg_type=get_enum_type(['free', 'standard']))
        c.argument('notscopes', options_list=('--not-scopes'), nargs='+')

    with self.argument_context('policy set-definition', min_api='2017-06-01-preview', resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('policy_set_definition_name', arg_type=existing_policy_set_definition_name_type)
        c.argument('name', options_list=('--name', '-n'), help='name of the new policy set definition')
        c.argument('display_name', help='display name of policy set definition')
        c.argument('description', help='description of policy set definition')
        c.argument('params', help='JSON formatted string or a path to a file or uri with parameter definitions', type=file_type, completer=FilesCompleter())
        c.argument('definitions', help='JSON formatted string or a path to a file or uri with such content', type=file_type, completer=FilesCompleter())

    with self.argument_context('group') as c:
        c.argument('tag', tag_type)
        c.argument('tags', tags_type)
        c.argument('resource_group_name', resource_group_name_type, options_list=['--name', '-n', '--resource-group', '-g'])

    with self.argument_context('group deployment') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type, completer=get_resource_group_completion_list)
        c.argument('deployment_name', options_list=('--name', '-n'), required=True, help='The deployment name.')
        c.argument('template_file', completer=FilesCompleter(), type=file_type, help="a template file path in the file system")
        c.argument('template_uri', help='a uri to a remote template file')
        c.argument('mode', arg_type=get_enum_type(DeploymentMode, default='incremental'), help='Incremental (only add resources to resource group) or Complete (remove extra resources from resource group)')
        c.argument('parameters', action='append', nargs='+', completer=FilesCompleter())

    with self.argument_context('group deployment create') as c:
        c.argument('deployment_name', options_list=('--name', '-n'), required=False,
                   help='The deployment name. Default to template file base name')

    with self.argument_context('group deployment operation show') as c:
        c.argument('operation_ids', nargs='+', help='A list of operation ids to show')

    with self.argument_context('group export') as c:
        c.argument('include_comments', action='store_true')
        c.argument('include_parameter_default_value', action='store_true')

    with self.argument_context('group create') as c:
        c.argument('rg_name', options_list=['--name', '--resource-group', '-n', '-g'], help='name of the new resource group', completer=None)

    with self.argument_context('tag') as c:
        c.argument('tag_name', options_list=('--name', '-n'))
        c.argument('tag_value', options_list=('--value',))

    with self.argument_context('lock') as c:
        c.argument('lock_name', options_list=('--name', '-n'), validator=validate_lock_parameters)
        c.argument('level', arg_type=get_enum_type(LockLevel), options_list=('--lock-type', '-t'))
        c.argument('parent_resource_path', resource_parent_type)
        c.argument('resource_provider_namespace', resource_namespace_type)
        c.argument('resource_type', arg_type=resource_type_type, completer=get_resource_types_completion_list)
        c.argument('resource_name', options_list=['--resource', '--resource-name'], help='Name or ID of the resource being locked. If an ID is given, other resource arguments should not be given.')
        c.argument('ids', nargs='+', options_list=('--ids'), help='One or more resource IDs (space-delimited). If provided, no other "Resource Id" arguments should be specified.')
        c.argument('resource_group', resource_group_name_type, validator=validate_lock_parameters)

    with self.argument_context('resource lock') as c:
        c.argument('resource_group', resource_group_name_type)
        c.argument('resource_name', options_list=['--resource', '--resource-name'], help='If an ID is given, other resource arguments should not be given.', validator=validate_resource_lock)

    with self.argument_context('group lock') as c:
        c.argument('resource_group', resource_group_name_type, validator=validate_group_lock, id_part=None)

    with self.argument_context('group lock create') as c:
        c.argument('resource_group', required=True)

    with self.argument_context('account lock') as c:
        c.argument('resource_group', ignore_type, validator=validate_subscription_lock)

    for scope in ['account', 'group']:
        with self.argument_context('{} lock'.format(scope)) as c:
            c.ignore('resource_provider_namespace', 'parent_resource_path', 'resource_type', 'resource_name')

    for scope in ['lock', 'account lock', 'group lock', 'resource lock']:
        with self.argument_context(scope) as c:
            c.argument('lock_name', options_list=('--name', '-n'), help='Name of the lock')
            c.argument('level', options_list=('--lock-type', '-t'), arg_type=get_enum_type([LockLevel.can_not_delete, LockLevel.read_only]))
            c.argument('ids', nargs='+', options_list=('--ids'), help='One or more resource IDs (space-delimited). If provided, no other "Resource Id" arguments should be specified.')
            c.argument('notes', help='Notes about this lock.')

    with self.argument_context('managedapp') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type, help='the resource group of the managed application', id_part='resource_group')
        c.argument('application_name', options_list=('--name', '-n'), id_part='name')

    with self.argument_context('managedapp definition') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type, help='the resource group of the managed application definition', id_part='resource_group')
        c.argument('application_definition_name', options_list=('--name', '-n'), id_part='name')

    with self.argument_context('managedapp create') as c:
        c.argument('name', options_list=('--name', '-n'), help='name of the new managed application', completer=None)
        c.argument('location', help='the managed application location')
        c.argument('managedapp_definition_id', options_list=('--managedapp-definition-id', '-d'), help='the full qualified managed application definition id')
        c.argument('managedby_resource_group_id', options_list=('--managed-rg-id', '-m'), help='the resource group managed by the managed application')
        c.argument('parameters', help='JSON formatted string or a path to a file with such content', type=file_type)

    with self.argument_context('managedapp definition create') as c:
        c.argument('lock_level', arg_type=get_enum_type(ApplicationLockLevel))
        c.argument('authorizations', options_list=('--authorizations', '-a'), nargs='+', help="space-separated authorization pairs in a format of <principalId>:<roleDefinitionId>")
        c.argument('createUiDefinition', options_list=('--create-ui-definition', '-c'), help='JSON formatted string or a path to a file with such content', type=file_type)
        c.argument('mainTemplate', options_list=('--main-template', '-t'), help='JSON formatted string or a path to a file with such content', type=file_type)
Exemplo n.º 11
0
def load_arguments(self, _):  # pylint: disable=too-many-locals, too-many-statements
    from argcomplete.completers import FilesCompleter
    from knack.arguments import CLIArgumentType
    from azure.cli.core.commands.parameters import get_resource_name_completion_list

    from .sdkutil import get_table_data_type
    from .completers import get_storage_name_completion_list, get_container_name_completions

    t_base_blob_service = self.get_sdk('blob.baseblobservice#BaseBlobService')
    t_file_service = self.get_sdk('file#FileService')
    t_table_service = get_table_data_type(self.cli_ctx, 'table', 'TableService')

    acct_name_type = CLIArgumentType(options_list=['--account-name', '-n'], help='The storage account name.',
                                     id_part='name',
                                     completer=get_resource_name_completion_list('Microsoft.Storage/storageAccounts'),
                                     local_context_attribute=LocalContextAttribute(
                                         name='storage_account_name', actions=[LocalContextAction.GET]))
    blob_name_type = CLIArgumentType(options_list=['--blob-name', '-b'], help='The blob name.',
                                     completer=get_storage_name_completion_list(t_base_blob_service, 'list_blobs',
                                                                                parent='container_name'))
    container_name_type = CLIArgumentType(options_list=['--container-name', '-c'], help='The container name.',
                                          completer=get_container_name_completions)
    directory_path_type = CLIArgumentType(options_list=['--directory-path', '-d'], help='The directory path name.',
                                          parent='container_name')
    share_name_type = CLIArgumentType(options_list=['--share-name', '-s'], help='The file share name.',
                                      completer=get_storage_name_completion_list(t_file_service, 'list_shares'))
    table_name_type = CLIArgumentType(options_list=['--table-name', '-t'],
                                      completer=get_storage_name_completion_list(t_table_service, 'list_tables'))
    num_results_type = CLIArgumentType(
        default=5000, help='Specifies the maximum number of results to return. Provide "*" to return all.',
        validator=validate_storage_data_plane_list)
    acl_type = CLIArgumentType(options_list=['--acl-spec', '-a'],
                               help='The ACL specification to set on the path in the format '
                                    '"[default:]user|group|other|mask:[entity id or UPN]:r|-w|-x|-,'
                                    '[default:]user|group|other|mask:[entity id or UPN]:r|-w|-x|-,...". '
                                    'e.g."user::rwx,user:john.doe@contoso:rwx,group::r--,other::---,mask::rwx".')
    progress_type = CLIArgumentType(help='Include this flag to disable progress reporting for the command.',
                                    action='store_true', validator=add_upload_progress_callback)

    with self.argument_context('storage') as c:
        c.argument('container_name', container_name_type)
        c.argument('share_name', share_name_type)
        c.argument('table_name', table_name_type)
        c.argument('retry_wait', options_list=('--retry-interval',))
        c.ignore('progress_callback')
        c.argument('metadata', nargs='+',
                   help='Metadata in space-separated key=value pairs. This overwrites any existing metadata.',
                   validator=validate_metadata)
        c.argument('timeout', help='Request timeout in seconds. Applies to each call to the service.', type=int)

    with self.argument_context('storage', arg_group='Precondition') as c:
        c.argument('if_modified_since', help='Alter only if modified since supplied UTC datetime (Y-m-d\'T\'H:M\'Z\')',
                   type=get_datetime_type(False))
        c.argument('if_unmodified_since',
                   help='Alter only if unmodified since supplied UTC datetime (Y-m-d\'T\'H:M\'Z\')',
                   type=get_datetime_type(False))
        c.argument('if_match')
        c.argument('if_none_match')

    with self.argument_context('storage account blob-inventory-policy') as c:
        c.ignore('blob_inventory_policy_name')
        c.argument('resource_group_name', required=False, validator=process_resource_group)
        c.argument('account_name',
                   help='The name of the storage account within the specified resource group. Storage account names '
                        'must be between 3 and 24 characters in length and use numbers and lower-case letters only.')

    with self.argument_context('storage account blob-inventory-policy create') as c:
        # t_inventory_rule_type = self.get_models('InventoryRuleType', resource_type=CUSTOM_MGMT_PREVIEW_STORAGE)
        c.argument('policy', type=file_type, completer=FilesCompleter(),
                   help='The Storage Account Blob Inventory Policy, string in JSON format or json file path. '
                        'See more details in: {https://review.docs.microsoft.com/en-us/azure/storage/blobs/'
                        'blob-inventory?branch=pr-en-us-135665}.')
        # c.argument('destination',
        #            help='Container name where blob inventory files are stored. Must be pre-created.')
        # c.argument('enabled', arg_type=get_three_state_flag(), help='Policy is enabled if set to true.')
        # c.argument('type', arg_type=get_enum_type(t_inventory_rule_type), default='Inventory', required=False,
        #            help='The valid value is Inventory. Possible values include: "Inventory".')
        # c.argument('rule_name', arg_group='Blob Inventory Policy Rule',
        #            help='A rule name can contain any combination of alpha numeric characters. Rule name is '
        #            'case-sensitive. It must be unique within a policy.')
        # c.argument('prefix_match', arg_group='Blob Inventory Policy Rule', nargs='+',
        #            help='An array of strings for blob prefixes to be matched.')
        # c.argument('blob_types', arg_group='Blob Inventory Policy Rule', nargs='+',
        #            help='An array of predefined enum values. Valid values include blockBlob, appendBlob, pageBlob. '
        #                 'Hns accounts does not support pageBlobs.')
        # c.argument('include_blob_versions', arg_group='Blob Inventory Policy Rule', arg_type=get_three_state_flag(),
        #            help='Include blob versions in blob inventory when value set to true.')
        # c.argument('include_snapshots', arg_group='Blob Inventory Policy Rule', arg_type=get_three_state_flag(),
        #            help='Include blob snapshots in blob inventory when value set to true.')

    # with self.argument_context('storage account blob-inventory-policy rule') as c:
    #     c.argument('destination', help='')
    #     c.argument('enabled', help='')
    #     c.argument('type', help='')

    with self.argument_context('storage account file-service-properties show',
                               resource_type=CUSTOM_MGMT_PREVIEW_STORAGE) as c:
        c.argument('account_name', acct_name_type, id_part=None)
        c.argument('resource_group_name', required=False, validator=process_resource_group)

    with self.argument_context('storage account file-service-properties update',
                               resource_type=CUSTOM_MGMT_PREVIEW_STORAGE) as c:
        from azure.cli.command_modules.storage._validators import validate_file_delete_retention_days
        c.argument('account_name', acct_name_type, id_part=None)
        c.argument('resource_group_name', required=False, validator=process_resource_group)
        c.argument('enable_delete_retention', arg_type=get_three_state_flag(), arg_group='Delete Retention Policy',
                   min_api='2019-06-01', help='Enable file service properties for share soft delete.')
        c.argument('delete_retention_days', type=int, arg_group='Delete Retention Policy',
                   validator=validate_file_delete_retention_days, min_api='2019-06-01',
                   help=' Indicate the number of days that the deleted item should be retained. The minimum specified '
                        'value can be 1 and the maximum value can be 365.')
        c.argument('enable_smb_multichannel', options_list=['--enable-smb-multichannel', '--mc'],
                   arg_type=get_three_state_flag(), min_api='2020-08-01-preview', arg_group='SMB Setting',
                   help='Set SMB Multichannel setting for file service. Applies to Premium FileStorage only.')
        c.argument('versions', arg_group='SMB Setting', min_api='2020-08-01-preview',
                   help="SMB protocol versions supported by server. Valid values are SMB2.1, SMB3.0, "
                        "SMB3.1.1. Should be passed as a string with delimiter ';'.")
        c.argument('authentication_methods', options_list='--auth-methods', arg_group='SMB Setting',
                   min_api='2020-08-01-preview',
                   help="SMB authentication methods supported by server. Valid values are NTLMv2, Kerberos. "
                        "Should be passed as a string with delimiter ';'.")
        c.argument('kerberos_ticket_encryption', options_list=['--kerb-ticket-encryption', '-k'],
                   arg_group='SMB Setting', min_api='2020-08-01-preview',
                   help="Kerberos ticket encryption supported by server. Valid values are RC4-HMAC, AES-256. "
                        "Should be passed as a string with delimiter ';'.")
        c.argument('channel_encryption', arg_group='SMB Setting', min_api='2020-08-01-preview',
                   help="SMB channel encryption supported by server. Valid values are AES-CCM-128, AES-GCM-128, "
                        "AES-GCM-256. Should be passed as a string with delimiter ';'.")

    with self.argument_context('storage account network-rule') as c:
        from ._validators import validate_subnet
        c.argument('account_name', acct_name_type, id_part=None)
        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)
        c.argument('action', help='The action of virtual network rule.')
        c.argument('resource_id', help='The resource id to add in network rule.')
        c.argument('tenant_id', help='The tenant id to add in network rule.')

    with self.argument_context('storage blob service-properties update') as c:
        c.argument('delete_retention', arg_type=get_three_state_flag(), arg_group='Soft Delete',
                   help='Enables soft-delete.')
        c.argument('days_retained', type=int, arg_group='Soft Delete',
                   help='Number of days that soft-deleted blob will be retained. Must be in range [1,365].')
        c.argument('static_website', arg_group='Static Website', arg_type=get_three_state_flag(),
                   help='Enables static-website.')
        c.argument('index_document', help='Represents the name of the index document. This is commonly "index.html".',
                   arg_group='Static Website')
        c.argument('error_document_404_path', options_list=['--404-document'], arg_group='Static Website',
                   help='Represents the path to the error document that should be shown when an error 404 is issued,'
                        ' in other words, when a browser requests a page that does not exist.')

    with self.argument_context('storage azcopy blob upload') as c:
        c.extra('destination_container', options_list=['--container', '-c'], required=True,
                help='The upload destination container.')
        c.extra('destination_path', options_list=['--destination', '-d'],
                validator=validate_azcopy_upload_destination_url,
                help='The upload destination path.')
        c.argument('source', options_list=['--source', '-s'],
                   help='The source file path to upload from.')
        c.argument('recursive', options_list=['--recursive', '-r'], action='store_true',
                   help='Recursively upload blobs.')
        c.ignore('destination')

    with self.argument_context('storage azcopy blob download') as c:
        c.extra('source_container', options_list=['--container', '-c'], required=True,
                help='The download source container.')
        c.extra('source_path', options_list=['--source', '-s'],
                validator=validate_azcopy_download_source_url,
                help='The download source path.')
        c.argument('destination', options_list=['--destination', '-d'],
                   help='The destination file path to download to.')
        c.argument('recursive', options_list=['--recursive', '-r'], action='store_true',
                   help='Recursively download blobs.')
        c.ignore('source')

    with self.argument_context('storage azcopy blob delete') as c:
        c.extra('target_container', options_list=['--container', '-c'], required=True,
                help='The delete target container.')
        c.extra('target_path', options_list=['--target', '-t'],
                validator=validate_azcopy_target_url,
                help='The delete target path.')
        c.argument('recursive', options_list=['--recursive', '-r'], action='store_true',
                   help='Recursively delete blobs.')
        c.ignore('target')

    with self.argument_context('storage azcopy blob sync') as c:
        c.extra('destination_container', options_list=['--container', '-c'], required=True,
                help='The sync destination container.')
        c.extra('destination_path', options_list=['--destination', '-d'],
                validator=validate_azcopy_upload_destination_url,
                help='The sync destination path.')
        c.argument('source', options_list=['--source', '-s'],
                   help='The source file path to sync from.')
        c.ignore('destination')

    with self.argument_context('storage azcopy run-command') as c:
        c.positional('command_args', help='Command to run using azcopy. Please start commands with "azcopy ".')

    with self.argument_context('storage blob access') as c:
        c.argument('path', blob_name_type)

    with self.argument_context('storage blob access set') as c:
        c.argument('acl', acl_type, required=True,)
        c.ignore('owner', 'group', 'permissions')

    with self.argument_context('storage blob access update') as c:
        c.argument('acl', acl_type)
        c.argument('owner', help='The owning user for the directory.')
        c.argument('group', help='The owning group for the directory.')
        c.argument('permissions', help='The POSIX access permissions for the file owner,'
                   'the file owning group, and others. Both symbolic (rwxrw-rw-) and 4-digit '
                   'octal notation (e.g. 0766) are supported.')

    with self.argument_context('storage blob list') as c:
        c.argument('include', validator=validate_included_datasets, default='mc')
        c.argument('num_results', arg_type=num_results_type)

    with self.argument_context('storage blob move') as c:
        from ._validators import validate_move_file
        c.argument('source_path', options_list=['--source-blob', '-s'], validator=validate_move_file,
                   help="The source blob name. It should be an absolute path under the container. e.g."
                        "'topdir1/dirsubfoo'.")
        c.argument('new_path', options_list=['--destination-blob', '-d'],
                   help="The destination blob name. It should be an absolute path under the container. e.g."
                        "'topdir1/dirbar'.")
        c.argument('container_name', container_name_type)
        c.ignore('mode')
        c.ignore('marker')

    with self.argument_context('storage blob directory') as c:
        c.argument('directory_path', directory_path_type)
        c.argument('container_name', container_name_type)

    with self.argument_context('storage blob directory access') as c:
        c.argument('path', directory_path_type)

    with self.argument_context('storage blob directory access set') as c:
        c.argument('acl', acl_type, required=True)
        c.ignore('owner', 'group', 'permissions')

    with self.argument_context('storage blob directory access update') as c:
        c.argument('acl', acl_type)
        c.argument('owner', help='The owning user for the directory.')
        c.argument('group', help='The owning group for the directory.')
        c.argument('permissions', help='The POSIX access permissions for the file owner,'
                   'the file owning group, and others. Both symbolic (rwxrw-rw-) and 4-digit '
                   'octal notation (e.g. 0766) are supported.')

    with self.argument_context('storage blob directory create') as c:
        from ._validators import validate_directory_name
        c.argument('posix_permissions', options_list=['--permissions'])
        c.argument('posix_umask', options_list=['--umask'], default='0027',
                   help='Optional and only valid if Hierarchical Namespace is enabled for the account. '
                        'The umask restricts permission settings for file and directory, and will only be applied when '
                        'default Acl does not exist in parent directory. If the umask bit has set, it means that the '
                        'corresponding permission will be disabled. In this way, the resulting permission is given by '
                        'p & ^u, where p is the permission and u is the umask. Only 4-digit octal notation (e.g. 0022) '
                        'is supported here.')
        c.argument('directory_path', directory_path_type, validator=validate_directory_name)

    with self.argument_context('storage blob directory download') as c:
        c.extra('source_container', options_list=['--container', '-c'], required=True,
                help='The download source container.')
        c.extra('source_path', options_list=['--source-path', '-s'], required=True,
                validator=validate_blob_directory_download_source_url,
                help='The download source directory path. It should be an absolute path to container.')
        c.argument('destination', options_list=['--destination-path', '-d'],
                   help='The destination local directory path to download.')
        c.argument('recursive', options_list=['--recursive', '-r'], action='store_true',
                   help='Recursively download blobs. If enabled, all the blobs including the blobs in subdirectories '
                        'will be downloaded.')
        c.ignore('source')

    with self.argument_context('storage blob directory exists') as c:
        c.argument('blob_name', directory_path_type, required=True)

    with self.argument_context('storage blob directory list') as c:
        c.argument('include', validator=validate_included_datasets, default='mc')
        c.argument('num_results', arg_type=num_results_type)

    with self.argument_context('storage blob directory metadata') as c:
        c.argument('blob_name', directory_path_type)

    with self.argument_context('storage blob directory move') as c:
        from ._validators import validate_move_directory
        c.argument('new_path', options_list=['--destination-path', '-d'],
                   help='The destination blob directory path. It can be a directory or subdirectory name, e.g. dir, '
                        'dir/subdir. If the destination path exists and is empty, the source will be moved into the '
                        'destination path. If the destination path does not exist, the destination path will be created'
                        ' and overwritten by the source. To control the move operation for nonempty path, you can use '
                        '--move-mode to determine its behavior.')
        c.argument('source_path', options_list=['--source-path', '-s'],
                   help='The source blob directory path.', validator=validate_move_directory)
        c.argument('lease_id', options_list=['--lease-id'],
                   help='A lease ID for destination directory_path. The destination directory_path must have an active '
                        'lease and the lease ID must match.')
        c.argument('mode', options_list=['--move-mode'], arg_type=get_enum_type(["legacy", "posix"]), default="posix",
                   help="Valid only when namespace is enabled. This parameter determines the behavior "
                        "of the move operation. If the destination directory is empty, for both two mode, "
                        "the destination directory will be overwritten. But if the destination directory is not empty, "
                        "in legacy mode the move operation will fail and in posix mode, the source directory will be "
                        "moved into the destination directory. ")

    with self.argument_context('storage blob directory show') as c:
        c.argument('directory_name', directory_path_type)
        c.argument('container_name', container_name_type)
        # c.argument('snapshot', help='The snapshot parameter is an opaque DateTime value that, '
        #                            'when present, specifies the directory snapshot to retrieve.')
        c.ignore('snapshot')
        c.argument('lease_id', help='Required if the blob has an active lease.')
        c.argument('if_match', help="An ETag value, or the wildcard character (*). Specify this header to perform the"
                   "operation only if the resource's ETag matches the value specified")
        c.argument('if_none_match', help="An ETag value, or the wildcard character (*). Specify this header to perform"
                   "the operation only if the resource's ETag does not match the value specified. Specify the wildcard"
                   "character (*) to perform the operation only if the resource does not exist, and fail the operation"
                   "if it does exist.")

    with self.argument_context('storage blob directory upload') as c:
        c.extra('destination_container', options_list=['--container', '-c'], required=True,
                help='The upload destination container.')
        c.extra('destination_path', options_list=['--destination-path', '-d'], required=True,
                validator=validate_blob_directory_upload_destination_url,
                help='The upload destination directory path. It should be an absolute path to container. If the '
                     'specified destination path does not exist, a new directory path will be created.')
        c.argument('source', options_list=['--source', '-s'],
                   help='The source file path to upload from.')
        c.argument('recursive', options_list=['--recursive', '-r'], action='store_true',
                   help='Recursively upload blobs. If enabled, all the blobs including the blobs in subdirectories will'
                        ' be uploaded.')
        c.ignore('destination')

    with self.argument_context('storage file upload') as c:
        t_file_content_settings = self.get_sdk('file.models#ContentSettings')

        c.register_path_argument(default_file_param='local_file_path')
        c.register_content_settings_argument(t_file_content_settings, update=False, guess_from_file='local_file_path',
                                             process_md5=True)
        c.argument('local_file_path', options_list='--source', type=file_type, completer=FilesCompleter(),
                   help='Path of the local file to upload as the file content.')
        c.extra('no_progress', progress_type)
        c.argument('max_connections', type=int, help='Maximum number of parallel connections to use.')
        c.extra('share_name', share_name_type, required=True)
        c.argument('validate_content', action='store_true', min_api='2016-05-31',
                   help='If true, calculates an MD5 hash for each range of the file. The storage service checks the '
                        'hash of the content that has arrived with the hash that was sent. This is primarily valuable '
                        'for detecting bitflips on the wire if using http instead of https as https (the default) will '
                        'already validate. Note that this MD5 hash is not stored with the file.')

    with self.argument_context('storage file upload-batch') as c:
        from ._validators import process_file_upload_batch_parameters
        c.argument('source', options_list=('--source', '-s'), validator=process_file_upload_batch_parameters)
        c.argument('destination', options_list=('--destination', '-d'))
        c.argument('max_connections', arg_group='Upload Control', type=int)
        c.argument('validate_content', action='store_true', min_api='2016-05-31')
        c.register_content_settings_argument(t_file_content_settings, update=False, arg_group='Content Settings',
                                             process_md5=True)
        c.extra('no_progress', progress_type)
Exemplo n.º 12
0
def load_arguments(self, _):

    acr_arg_type = CLIArgumentType(metavar='ACR_NAME_OR_RESOURCE_ID')

    # 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('nodepool_tags', nargs='*', validator=validate_nodepool_tags, help='space-separated tags: key[=value] [key[=value] ...]. Use "" to clear existing tags.')
        c.argument('nodepool_labels', nargs='*', validator=validate_nodepool_labels, help='space-separated labels: key[=value] [key[=value] ...]. You can not change the node labels through CLI after creation. See https://aka.ms/node-labels for syntax of labels.')
        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', 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([CONST_OUTBOUND_TYPE_LOAD_BALANCER,
                                                            CONST_OUTBOUND_TYPE_USER_DEFINED_ROUTING]))
        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('cluster_autoscaler_profile', nargs='+', validator=validate_cluster_autoscaler_profile)
        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', help='To be deprecated. Use vm_set_type instead.')
        c.argument('vm_set_type', type=str, validator=validate_vm_set_type)
        c.argument('node_zones', zones_type, options_list=['--node-zones', '--zones', '-z'], help='(--node-zones will be deprecated, use --zones) 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('attach_acr', acr_arg_type)
        c.argument('api_server_authorized_ip_ranges', type=str, validator=validate_ip_ranges)
        c.argument('aks_custom_headers')
        c.argument('enable_private_cluster', action='store_true')
        c.argument('enable_managed_identity', action='store_true')

    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='+', validator=validate_cluster_autoscaler_profile)
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        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('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('attach_acr', acr_arg_type, validator=validate_acr)
        c.argument('detach_acr', acr_arg_type, validator=validate_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('tags', tags_type)
            c.argument('node_zones', zones_type, options_list=['--node-zones', '--zones', '-z'], help='(--node-zones will be deprecated) 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')
            c.argument('node_taints', type=str, validator=validate_taints)
            c.argument('priority', arg_type=get_enum_type([CONST_SCALE_SET_PRIORITY_REGULAR, CONST_SCALE_SET_PRIORITY_SPOT]), validator=validate_priority)
            c.argument('eviction_policy', arg_type=get_enum_type([CONST_SPOT_EVICTION_POLICY_DELETE, CONST_SPOT_EVICTION_POLICY_DEALLOCATE]), validator=validate_eviction_policy)
            c.argument('spot_max_price', type=float, validator=validate_spot_max_price)
            c.argument('labels', nargs='*', validator=validate_nodepool_labels)

    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')
        c.argument('tags', tags_type)

    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('context_name', options_list=['--context'],
                   help='If specified, overwrite the default context name.')
        c.argument('user', options_list=['--user', '-u'], default='clusterUser', validator=validate_user)
        c.argument('path', options_list=['--file', '-f'], type=file_type, completer=FilesCompleter(),
                   default=os.path.join(os.path.expanduser('~'), '.kube', 'config'))
Exemplo n.º 13
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)
        c.argument('key_uri', help="The URI of the key vault", 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='+',
                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).')
Exemplo n.º 14
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)

    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'
        )
        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='+')

    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.')

    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)
Exemplo n.º 15
0
 def test_dont_override_existing_option_string(self):
     existing_options_list = ('--something-else', '-s')
     arg = CLIArgumentType(options_list=existing_options_list)
     arg.update()
     self.assertEqual(arg.settings['options_list'], existing_options_list)
Exemplo n.º 16
0
def load_arguments(self, _):  # pylint: disable=too-many-locals, too-many-statements
    name_arg_type = CLIArgumentType(
        options_list=['--name', '-n'],
        id_part='name',
        help='The name of the Azure Media Services account.',
        metavar='NAME')
    account_name_arg_type = CLIArgumentType(
        options_list=['--account-name', '-a'],
        id_part='name',
        help='The name of the Azure Media Services account.',
        metavar='ACCOUNT_NAME')
    storage_account_arg_type = CLIArgumentType(
        options_list=['--storage-account'],
        validator=validate_storage_account_id,
        metavar='STORAGE_NAME')
    password_arg_type = CLIArgumentType(options_list=['--password', '-p'],
                                        metavar='PASSWORD_NAME')
    transform_name_arg_type = CLIArgumentType(
        options_list=['--transform-name', '-t'], metavar='TRANSFORM_NAME')
    expiry_arg_type = CLIArgumentType(options_list=['--expiry'],
                                      type=datetime_format,
                                      metavar='EXPIRY_TIME')
    default_policy_name_arg_type = CLIArgumentType(
        options_list=['--content-policy-name'],
        help=
        'The default content key policy name used by the streaming locator.',
        metavar='DEFAULT_CONTENT_KEY_POLICY_NAME')

    with self.argument_context('ams') as c:
        c.argument('account_name', name_arg_type)

    with self.argument_context('ams account') as c:
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('ams account create') as c:
        c.argument(
            'storage_account',
            storage_account_arg_type,
            help=
            'The name or resource ID of the primary storage account to attach to the Azure Media Services account. Blob only accounts are not allowed as primary.'
        )

    with self.argument_context('ams account storage') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument(
            'storage_account',
            name_arg_type,
            help=
            'The name or resource ID of the secondary storage account to detach from the Azure Media Services account.',
            validator=validate_storage_account_id)

    with self.argument_context('ams account sp') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument(
            'sp_name',
            name_arg_type,
            help=
            "The app name or app URI to associate the RBAC with. If not present, a default name like '{amsaccountname}-access-sp' will be generated."
        )
        c.argument(
            'sp_password',
            password_arg_type,
            help=
            "The password used to log in. Also known as 'Client Secret'. If not present, a random secret will be generated."
        )
        c.argument('role',
                   help='The role of the service principal.',
                   completer=get_role_definition_name_completion_list)
        c.argument('xml',
                   action='store_true',
                   help='Enables xml output format.')
        c.argument(
            'years',
            help=
            'Number of years for which the secret will be valid. Default: 1 year.',
            type=int,
            default=None)

    with self.argument_context('ams transform') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('transform_name',
                   name_arg_type,
                   id_part='child_name_1',
                   help='The name of the transform.')
        c.argument('preset_names',
                   arg_type=get_enum_type(
                       get_presets_definition_name_completion_list()),
                   nargs='+',
                   help='Space-separated list of built-in preset names.')
        c.argument('description', help='The description of the transform.')

    with self.argument_context('ams transform list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams asset') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('asset_name',
                   name_arg_type,
                   id_part='child_name_1',
                   help='The name of the asset.')

    with self.argument_context('ams asset list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams asset create') as c:
        c.argument('alternate_id', help='The alternate id of the asset.')
        c.argument('description', help='The asset description.')
        c.argument('asset_name', name_arg_type, help='The name of the asset.')

    with self.argument_context('ams asset update') as c:
        c.argument('alternate_id', help='The alternate id of the asset.')
        c.argument('description', help='The asset description.')

    with self.argument_context('ams asset get-sas-urls') as c:
        c.argument('permissions',
                   arg_type=get_enum_type(AssetContainerPermission),
                   help='The permissions to set on the SAS URL.')
        c.argument(
            'expiry_time',
            expiry_arg_type,
            help=
            "Specifies the UTC datetime (Y-m-d'T'H:M:S'Z') at which the SAS becomes invalid."
        )

    with self.argument_context('ams job') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('transform_name',
                   transform_name_arg_type,
                   id_part='child_name_1',
                   help='The name of the transform.')
        c.argument('job_name',
                   name_arg_type,
                   id_part='child_name_2',
                   help='The name of the job.')

    with self.argument_context('ams job list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams job start') as c:
        c.argument('priority',
                   arg_type=get_enum_type(Priority),
                   help='The priority with which the job should be processed.')
        c.argument('description', help='The job description.')
        c.argument('input_asset_name',
                   arg_group='Asset Job Input',
                   help='The name of the input asset.')
        c.argument('output_asset_names',
                   nargs='+',
                   help='Space-separated list of output asset names.')
        c.argument(
            'base_uri',
            arg_group='Http Job Input',
            help=
            'Base uri for http job input. It will be concatenated with provided file names. If no base uri is given, then the provided file list is assumed to be fully qualified uris.'
        )
        c.argument(
            'files',
            nargs='+',
            help=
            'Space-separated list of files. It can be used to tell the service to only use the files specified from the input asset.'
        )

    with self.argument_context('ams job cancel') as c:
        c.argument('delete',
                   action='store_true',
                   help='Delete the job being cancelled.')

    with self.argument_context('ams streaming') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('default_content_key_policy_name',
                   default_policy_name_arg_type)

    with self.argument_context('ams streaming locator') as c:
        c.argument('streaming_locator_name',
                   name_arg_type,
                   id_part='child_name_1',
                   help='The name of the streaming locator.')
        c.argument('asset_name',
                   help='The name of the asset used by the streaming locator.')
        c.argument(
            'streaming_policy_name',
            help=
            'The name of the streaming policy used by the streaming locator.')
        c.argument(
            'start_time',
            type=datetime_format,
            help="Start time (Y-m-d'T'H:M:S'Z') of the streaming locator.")
        c.argument(
            'end_time',
            type=datetime_format,
            help="End time (Y-m-d'T'H:M:S'Z') of the streaming locator.")

    with self.argument_context('ams streaming locator list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams streaming policy') as c:
        c.argument('streaming_policy_name',
                   name_arg_type,
                   id_part='child_name_1',
                   help='The name of the streaming policy.')
        c.argument('download',
                   arg_type=get_three_state_flag(),
                   arg_group='Encryption Protocols',
                   help='Enable Download protocol.')
        c.argument('dash',
                   arg_type=get_three_state_flag(),
                   arg_group='Encryption Protocols',
                   help='Enable Dash protocol.')
        c.argument('hls',
                   arg_type=get_three_state_flag(),
                   arg_group='Encryption Protocols',
                   help='Enable HLS protocol.')
        c.argument('smooth_streaming',
                   arg_type=get_three_state_flag(),
                   arg_group='Encryption Protocols',
                   help='Enable SmoothStreaming protocol.')

    with self.argument_context('ams streaming policy list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams streaming endpoint list') as c:
        c.argument('account_name', id_part=None)
Exemplo n.º 17
0
def load_arguments(self, _):

    # PARAMETER REGISTRATION
    fields_arg_type = CLIArgumentType(
        nargs='+',
        help='Space-separated customized output fields.',
        validator=validate_query_fields,
        arg_type=get_enum_type([
            'key', 'value', 'label', 'content_type', 'etag', 'tags', 'locked',
            'last_modified'
        ]))
    feature_fields_arg_type = CLIArgumentType(
        nargs='+',
        help='Customize output fields for Feature Flags.',
        validator=validate_feature_query_fields,
        arg_type=get_enum_type([
            'key', 'label', 'locked', 'last_modified', 'state', 'description',
            'conditions'
        ]))
    filter_parameters_arg_type = CLIArgumentType(
        validator=validate_filter_parameters,
        help="Space-separated filter parameters in 'name[=value]' format.",
        nargs='*')
    datatime_filter_arg_type = CLIArgumentType(
        validator=validate_datetime,
        help=
        'Format: "YYYY-MM-DDThh:mm:ssZ". If no time zone specified, use UTC by default.'
    )
    top_arg_type = CLIArgumentType(
        options_list=['--top', '-t'],
        type=int,
        help=
        'Maximum number of items to return. Must be a positive integer. Default to 100.'
    )
    identities_arg_type = CLIArgumentType(
        nargs='*',
        validator=validate_identity,
        help=
        "Accept system or user assigned identities separated by spaces. Use '[system]' to refer system assigned identity or a resource id to refer user assigned identity. Use system assigned identity if not specified."
    )

    with self.argument_context('appconfig') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument(
            'name',
            options_list=['--name', '-n'],
            id_part='None',
            help=
            'Name of the App Configuration. You can configure the default name using `az configure --defaults app_configuration_store=<name>`',
            configured_default='app_configuration_store')
        c.argument(
            'connection_string',
            validator=validate_connection_string,
            configured_default='appconfig_connection_string',
            help=
            "Combination of access key and endpoint of App Configuration. Can be found using 'az appconfig credential list'. Users can preset it using `az configure --defaults appconfig_connection_string=<connection_string>` or environment variable with the name AZURE_APPCONFIG_CONNECTION_STRING."
        )
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.')
        c.argument('datetime', arg_type=datatime_filter_arg_type)
        c.argument('top', arg_type=top_arg_type)
        c.argument('all_',
                   options_list=['--all'],
                   action='store_true',
                   help="List all items.")
        c.argument('fields', arg_type=fields_arg_type)
        c.argument('sku',
                   help='The sku of App Configuration',
                   arg_type=get_enum_type(['free', 'standard']))

    with self.argument_context('appconfig create') as c:
        c.argument('location',
                   options_list=['--location', '-l'],
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('assign_identity',
                   arg_type=identities_arg_type,
                   is_preview=True)

    with self.argument_context('appconfig update') as c:
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('appconfig update',
                               arg_group='Customer Managed Key',
                               is_preview=True) as c:
        c.argument('encryption_key_name', help='The name of the KeyVault key.')
        c.argument('encryption_key_vault', help='The URI of the KeyVault.')
        c.argument(
            'encryption_key_version',
            help=
            'The version of the KeyVault key. Use the latest version by default.'
        )
        c.argument(
            'identity_client_id',
            help=
            'Client ID of the managed identity with wrap and unwrap access to encryption key. Use system assigned identity by default.'
        )

    with self.argument_context('appconfig identity assign') as c:
        c.argument('identities', arg_type=identities_arg_type)

    with self.argument_context('appconfig identity remove') as c:
        c.argument(
            'identities',
            arg_type=identities_arg_type,
            help=
            "Accept system or user assigned identities separated by spaces. Use '[system]' to refer system assigned identity, '[all]' for all identities or a resource id to refer user assigned identity. Remove system assigned identity if not specified."
        )

    with self.argument_context('appconfig credential regenerate') as c:
        c.argument(
            'id_',
            options_list=['--id'],
            help=
            'Id of the key to be regenerated. Can be found using az appconfig credential list command.'
        )

    with self.argument_context('appconfig kv import') as c:
        c.argument(
            'label',
            help=
            "Imported KVs and feature flags will be assigned with this label. If no label specified, will assign null label."
        )
        c.argument(
            'prefix',
            help=
            "This prefix will be appended to the front of imported keys. Prefix will be ignored for feature flags."
        )
        c.argument(
            'source',
            options_list=['--source', '-s'],
            arg_type=get_enum_type(['file', 'appconfig', 'appservice']),
            validator=validate_import,
            help=
            "The source of importing. Note that importing feature flags from appservice is not supported."
        )
        c.argument('yes', help="Do not prompt for preview.")
        c.argument(
            'skip_features',
            help=
            "Import only key values and exclude all feature flags. By default, all feature flags will be imported from file or appconfig. Not applicable for appservice.",
            arg_type=get_three_state_flag())
        c.argument('content_type', help='Content type of all imported items.')

    with self.argument_context('appconfig kv import', arg_group='File') as c:
        c.argument(
            'path',
            help='Local configuration file path. Required for file arguments.')
        c.argument(
            'format_',
            options_list=['--format'],
            arg_type=get_enum_type(['json', 'yaml', 'properties']),
            help=
            'Imported file format. Required for file arguments. Currently, feature flags are not supported in properties format.'
        )
        c.argument(
            'depth',
            validator=validate_import_depth,
            help=
            "Depth for flattening the json or yaml file to key-value pairs. Flatten to the deepest level by default. Not applicable for property files or feature flags."
        )
        # bypass cli allowed values limition
        c.argument(
            'separator',
            validator=validate_separator,
            help=
            "Delimiter for flattening the json or yaml file to key-value pairs. Required for importing hierarchical structure. Separator will be ignored for property files and feature flags. Supported values: '.', ',', ';', '-', '_', '__', '/', ':' "
        )

    with self.argument_context('appconfig kv import',
                               arg_group='AppConfig') as c:
        c.argument('src_name',
                   help='The name of the source App Configuration.')
        c.argument(
            'src_connection_string',
            validator=validate_connection_string,
            help="Combination of access key and endpoint of the source store.")
        c.argument(
            'src_key',
            help=
            'If no key specified, import all keys by default. Support star sign as filters, for instance abc* means keys with abc as prefix. Key filtering not applicable for feature flags. By default, all feature flags with specified label will be imported.'
        )
        c.argument(
            'src_label',
            help=
            "Only keys with this label in source AppConfig will be imported. If no value specified, import keys with null label by default. Support star sign as filters, for instance * means all labels, abc* means labels with abc as prefix."
        )
        c.argument(
            'preserve_labels',
            arg_type=get_three_state_flag(),
            help=
            "Flag to preserve labels from source AppConfig. This argument should NOT be specified along with --label."
        )

    with self.argument_context('appconfig kv import',
                               arg_group='AppService') as c:
        c.argument(
            'appservice_account',
            validator=validate_appservice_name_or_id,
            help=
            'ARM ID for AppService OR the name of the AppService, assuming it is in the same subscription and resource group as the App Configuration. Required for AppService arguments'
        )

    with self.argument_context('appconfig kv export') as c:
        c.argument(
            'label',
            help=
            "Only keys and feature flags with this label will be exported. If no label specified, export keys and feature flags with null label by default. Only when export destination is appconfig, we support star sign as filters, for instance * means all labels and abc* means labels with abc as prefix. Label filters are not supported when exporting to file or appservice."
        )
        c.argument(
            'prefix',
            help=
            "Prefix to be trimmed from keys. Prefix will be ignored for feature flags."
        )
        c.argument(
            'key',
            help=
            'If no key specified, return all keys by default. Support star sign as filters, for instance abc* means keys with abc as prefix. Key filtering not applicable for feature flags. By default, all feature flags with specified label will be exported.'
        )
        c.argument(
            'destination',
            options_list=['--destination', '-d'],
            arg_type=get_enum_type(['file', 'appconfig', 'appservice']),
            validator=validate_export,
            help=
            "The destination of exporting. Note that exporting feature flags to appservice is not supported."
        )
        c.argument('yes', help="Do not prompt for preview.")
        c.argument(
            'skip_features',
            help=
            "Export items excluding all feature flags. By default, all features with the specified label will be exported to file or appconfig. Not applicable for appservice.",
            arg_type=get_three_state_flag())
        c.argument(
            'skip_keyvault',
            help=
            "Export items excluding all key vault references. By default, all key vault references with the specified label will be exported.",
            arg_type=get_three_state_flag())

    with self.argument_context('appconfig kv export', arg_group='File') as c:
        c.argument(
            'path',
            help='Local configuration file path. Required for file arguments.')
        c.argument(
            'format_',
            options_list=['--format'],
            arg_type=get_enum_type(['json', 'yaml', 'properties']),
            help=
            'File format exporting to. Required for file arguments. Currently, feature flags are not supported in properties format.'
        )
        c.argument(
            'depth',
            validator=validate_import_depth,
            help=
            "Depth for flattening the json or yaml file to key-value pairs. Flatten to the deepest level by default. Not appicable for property files or feature flags."
        )
        # bypass cli allowed values limition
        c.argument(
            'separator',
            validator=validate_separator,
            help=
            "Delimiter for flattening the json or yaml file to key-value pairs. Required for exporting hierarchical structure. Separator will be ignored for property files and feature flags. Supported values: '.', ',', ';', '-', '_', '__', '/', ':' "
        )
        c.argument(
            'naming_convention',
            arg_type=get_enum_type(['pascal', 'camel', 'underscore',
                                    'hyphen']),
            help=
            'Naming convention to be used for "Feature Management" section of file. Example: pascal = FeatureManagement, camel = featureManagement, underscore = feature_management, hyphen = feature-management.'
        )
        c.argument('resolve_keyvault',
                   arg_type=get_three_state_flag(),
                   validator=validate_resolve_keyvault,
                   help="Resolve the content of key vault reference.")

    with self.argument_context('appconfig kv export',
                               arg_group='AppConfig') as c:
        c.argument('dest_name',
                   help='The name of the destination App Configuration.')
        c.argument(
            'dest_connection_string',
            validator=validate_connection_string,
            help=
            "Combination of access key and endpoint of the destination store.")
        c.argument(
            'dest_label',
            help=
            "Exported KVs will be labeled with this destination label. If neither --dest-label nor --preserve-labels is specified, will assign null label."
        )
        c.argument(
            'preserve_labels',
            arg_type=get_three_state_flag(),
            help=
            "Flag to preserve labels from source AppConfig. This argument should NOT be specified along with --dest-label."
        )

    with self.argument_context('appconfig kv export',
                               arg_group='AppService') as c:
        c.argument(
            'appservice_account',
            validator=validate_appservice_name_or_id,
            help=
            'ARM ID for AppService OR the name of the AppService, assuming it is in the same subscription and resource group as the App Configuration. Required for AppService arguments'
        )

    with self.argument_context('appconfig kv set') as c:
        c.argument(
            'key',
            validator=validate_key,
            help=
            "Key to be set. Key cannot be a '.' or '..', or contain the '%' character."
        )
        c.argument(
            'label',
            help="If no label specified, set the key with null label by default"
        )
        c.argument('tags', arg_type=tags_type)
        c.argument('content_type',
                   help='Content type of the keyvalue to be set.')
        c.argument('value', help='Value of the keyvalue to be set.')

    with self.argument_context('appconfig kv set-keyvault') as c:
        c.argument(
            'key',
            validator=validate_key,
            help=
            "Key to be set. Key cannot be a '.' or '..', or contain the '%' character."
        )
        c.argument(
            'label',
            help="If no label specified, set the key with null label by default"
        )
        c.argument('tags', arg_type=tags_type)
        c.argument(
            'secret_identifier',
            validator=validate_secret_identifier,
            help=
            "ID of the Key Vault object. Can be found using 'az keyvault {collection} show' command, where collection is key, secret or certificate. To set reference to the latest version of your secret, remove version information from secret identifier."
        )

    with self.argument_context('appconfig kv delete') as c:
        c.argument(
            'key',
            help=
            'Support star sign as filters, for instance * means all key and abc* means keys with abc as prefix.'
        )
        c.argument(
            'label',
            help=
            "If no label specified, delete entry with null label. Support star sign as filters, for instance * means all label and abc* means labels with abc as prefix."
        )

    with self.argument_context('appconfig kv show') as c:
        c.argument('key', help='Key to be showed.')
        c.argument(
            'label',
            help=
            "If no label specified, show entry with null label. Filtering is not supported."
        )

    with self.argument_context('appconfig kv list') as c:
        c.argument(
            'key',
            help=
            'If no key specified, return all keys by default. Support star sign as filters, for instance abc* means keys with abc as prefix.'
        )
        c.argument(
            'label',
            help=
            "If no label specified, list all labels. Support star sign as filters, for instance abc* means labels with abc as prefix. Use '\\0' for null label."
        )
        c.argument(
            'resolve_keyvault',
            arg_type=get_three_state_flag(),
            help=
            "Resolve the content of key vault reference. This argument should NOT be specified along with --fields. Instead use --query for customized query."
        )

    with self.argument_context('appconfig kv restore') as c:
        c.argument(
            'key',
            help=
            'If no key specified, restore all keys by default. Support star sign as filters, for instance abc* means keys with abc as prefix.'
        )
        c.argument(
            'label',
            help=
            "If no label specified, restore all key-value pairs with all labels. Support star sign as filters, for instance abc* means labels with abc as prefix."
        )

    with self.argument_context('appconfig kv lock') as c:
        c.argument('key', help='Key to be locked.')
        c.argument(
            'label',
            help=
            "If no label specified, lock entry with null label. Filtering is not supported."
        )

    with self.argument_context('appconfig kv unlock') as c:
        c.argument('key', help='Key to be unlocked.')
        c.argument(
            'label',
            help=
            "If no label specified, unlock entry with null label. Filtering is not supported."
        )

    with self.argument_context('appconfig revision list') as c:
        c.argument(
            'key',
            help=
            'If no key specified, return all keys by default. Support star sign as filters, for instance abc* means keys with abc as prefix.'
        )
        c.argument(
            'label',
            help=
            "If no label specified, list all labels. Support star sign as filters, for instance abc* means labels with abc as prefix. Use '\\0' for null label."
        )

    with self.argument_context('appconfig feature show') as c:
        c.argument('feature', help='Name of the feature flag to be retrieved')
        c.argument(
            'label',
            help=
            "If no label specified, show entry with null label. Filtering is not supported."
        )
        c.argument('fields', arg_type=feature_fields_arg_type)

    with self.argument_context('appconfig feature set') as c:
        c.argument(
            'feature',
            validator=validate_feature,
            help=
            "Name of the feature flag to be set. Only alphanumeric characters, '.', '-' and '_' are allowed."
        )
        c.argument(
            'label',
            help=
            "If no label specified, set the feature flag with null label by default"
        )
        c.argument('description',
                   help='Description of the feature flag to be set.')

    with self.argument_context('appconfig feature delete') as c:
        c.argument(
            'feature',
            help=
            'Key of the feature to be deleted. Support star sign as filters, for instance * means all key and abc* means keys with abc as prefix. Comma separated keys are not supported. Please provide escaped string if your feature name contains comma.'
        )
        c.argument(
            'label',
            help=
            "If no label specified, delete the feature flag with null label by default. Support star sign as filters, for instance * means all labels and abc* means labels with abc as prefix."
        )

    with self.argument_context('appconfig feature list') as c:
        c.argument(
            'feature',
            help=
            'Key of the feature to be listed. Support star sign as filters, for instance * means all key and abc* means keys with abc as prefix. Comma separated keys are not supported. Please provide escaped string if your feature name contains comma.'
        )
        c.argument(
            'label',
            help=
            "If no label specified, list all labels. Support star sign as filters, for instance * means all labels and abc* means labels with abc as prefix. Use '\\0' for null label."
        )
        c.argument('fields', arg_type=feature_fields_arg_type)
        c.argument('all_', help="List all feature flags.")

    with self.argument_context('appconfig feature lock') as c:
        c.argument('feature', help='Key of the feature to be locked.')
        c.argument(
            'label',
            help=
            "If no label specified, lock the feature flag with null label by default."
        )

    with self.argument_context('appconfig feature unlock') as c:
        c.argument('feature', help='Key of the feature to be unlocked.')
        c.argument(
            'label',
            help=
            "If no label specified, unlock the feature flag with null label by default."
        )

    with self.argument_context('appconfig feature enable') as c:
        c.argument('feature', help='Key of the feature to be enabled.')
        c.argument(
            'label',
            help=
            "If no label specified, enable the feature flag with null label by default."
        )

    with self.argument_context('appconfig feature disable') as c:
        c.argument('feature', help='Key of the feature to be disabled.')
        c.argument(
            'label',
            help=
            "If no label specified, disable the feature flag with null label by default."
        )

    with self.argument_context('appconfig feature filter add') as c:
        c.argument(
            'feature',
            help='Name of the feature to which you want to add the filter.')
        c.argument(
            'label',
            help=
            "If no label specified, add to the feature flag with null label by default."
        )
        c.argument('filter_name', help='Name of the filter to be added.')
        c.argument('filter_parameters', arg_type=filter_parameters_arg_type)
        c.argument(
            'index',
            type=int,
            help=
            'Zero-based index in the list of filters where you want to insert the new filter. If no index is specified or index is invalid, filter will be added to the end of the list.'
        )

    with self.argument_context('appconfig feature filter delete') as c:
        c.argument(
            'feature',
            help='Name of the feature from which you want to delete the filter.'
        )
        c.argument(
            'label',
            help=
            "If no label specified, delete from the feature flag with null label by default."
        )
        c.argument('filter_name', help='Name of the filter to be deleted.')
        c.argument(
            'index',
            type=int,
            help=
            'Zero-based index of the filter to be deleted in case there are multiple instances with same filter name.'
        )
        c.argument('all_',
                   help="Delete all filters associated with a feature flag.")

    with self.argument_context('appconfig feature filter show') as c:
        c.argument('feature',
                   help='Name of the feature which contains the filter.')
        c.argument(
            'label',
            help=
            "If no label specified, show the feature flag with null label by default."
        )
        c.argument('filter_name', help='Name of the filter to be displayed.')
        c.argument(
            'index',
            type=int,
            help=
            'Zero-based index of the filter to be displayed in case there are multiple instances with same filter name.'
        )

    with self.argument_context('appconfig feature filter list') as c:
        c.argument(
            'feature',
            help='Name of the feature whose filters you want to be displayed.')
        c.argument(
            'label',
            help=
            "If no label specified, display filters from the feature flag with null label by default."
        )
        c.argument('all_',
                   help="List all filters associated with a feature flag.")
Exemplo n.º 18
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 recover') as c:
        c.argument('vault_name', help='Name of the deleted vault', required=True, completer=None,
                   validator=validate_deleted_vault_name)
        c.argument('resource_group_name', resource_group_name_type, id_part=None, required=False,
                   help='Resource group of the deleted vault')
        c.argument('location', help='Location of the deleted vault', required=False)

    with self.argument_context('keyvault purge') as c:
        c.argument('vault_name', help='Name of the deleted vault', required=True, completer=None,
                   validator=validate_deleted_vault_name)
        c.argument('location', help='Location of the deleted vault', required=False)

    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('object_id', validator=validate_principal)
        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:
                try:
                    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))
                except ValueError:
                    pass
                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)

        for cmd in ['list', 'list-deleted']:
            with self.argument_context('keyvault {} {}'.format(item, cmd)) as c:
                c.argument('include_pending', arg_type=get_three_state_flag())
    # 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)

    for scope in ['list', 'list-deleted', 'list-versions']:
        with self.argument_context('keyvault key {}'.format(scope)) as c:
            c.argument('maxresults', options_list=['--maxresults'], type=int)
    # 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 secret. By default, will look for the 'file-encoding' tag on the secret. Otherwise will assume 'utf-8'.", default=None)

    for scope in ['backup', 'restore']:
        with self.argument_context('keyvault secret {}'.format(scope)) as c:
            c.argument('file_path', options_list=['--file', '-f'], type=file_type, completer=FilesCompleter(), help='File to receive the secret contents.')

    for scope in ['list', 'list-deleted', 'list-versions']:
        with self.argument_context('keyvault secret {}'.format(scope)) as c:
            c.argument('maxresults', options_list=['--maxresults'], type=int)

    # 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 storage restore') 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(e.g. @my_policy.json).', 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', help='Admin e-mail address. Must be unique within the vault.')
        c.argument('name', help='Full admin name.')
        c.argument('phone', help='Admin phone number.')
        c.argument('first_name', help='Admin first name.')
        c.argument('last_name', help='Admin last name.')

    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')

    for scope in ['list', 'list-deleted', 'list-versions']:
        with self.argument_context('keyvault certificate {}'.format(scope)) as c:
            c.argument('maxresults', options_list=['--maxresults'], type=int)
Exemplo n.º 19
0
def load_arguments(self, _):  # pylint: disable=too-many-locals, too-many-statements
    name_arg_type = CLIArgumentType(options_list=['--name', '-n'], id_part='name', help='The name of the Azure Media Services account.', metavar='NAME')
    account_name_arg_type = CLIArgumentType(options_list=['--account-name', '-a'], id_part='name', help='The name of the Azure Media Services account.', metavar='ACCOUNT_NAME')
    storage_account_arg_type = CLIArgumentType(options_list=['--storage-account'], validator=validate_storage_account_id, metavar='STORAGE_NAME')
    password_arg_type = CLIArgumentType(options_list=['--password', '-p'], metavar='PASSWORD_NAME')
    transform_name_arg_type = CLIArgumentType(options_list=['--transform-name', '-t'], metavar='TRANSFORM_NAME')
    expiry_arg_type = CLIArgumentType(options_list=['--expiry'], type=datetime_format, metavar='EXPIRY_TIME')
    default_policy_name_arg_type = CLIArgumentType(options_list=['--content-key-policy-name'], help='The default content key policy name used by the streaming locator.', metavar='DEFAULT_CONTENT_KEY_POLICY_NAME')
    archive_window_length_arg_type = CLIArgumentType(options_list=['--archive-window-length'], validator=validate_archive_window_length, metavar='ARCHIVE_WINDOW_LENGTH')
    key_frame_interval_duration_arg_type = CLIArgumentType(options_list=['--key-frame-interval-duration'], validator=validate_archive_window_length, metavar='ARCHIVE_WINDOW_LENGTH')
    correlation_data_type = CLIArgumentType(validator=validate_correlation_data, help="Space-separated correlation data in 'key[=value]' format. This customer provided data will be returned in Job and JobOutput state events.", nargs='*', metavar='CORRELATION_DATA')
    token_claim_type = CLIArgumentType(validator=validate_token_claim, help="Space-separated required token claims in '[key=value]' format.", nargs='*', metavar='ASYMMETRIC TOKEN CLAIMS')
    output_assets_type = CLIArgumentType(validator=validate_output_assets, nargs='*', help="Space-separated assets in 'assetName=label' format. An asset without label can be sent like this: 'assetName='", metavar='OUTPUT_ASSETS')

    with self.argument_context('ams') as c:
        c.argument('account_name', name_arg_type)

    with self.argument_context('ams account') as c:
        c.argument('location', arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('ams account create') as c:
        c.argument('storage_account', storage_account_arg_type,
                   help='The name or resource ID of the primary storage account to attach to the Azure Media Services account. The storage account MUST be in the same Azure subscription as the Media Services account. It is strongly recommended that the storage account be in the same resource group as the Media Services account. Blob only accounts are not allowed as primary.')

    with self.argument_context('ams account check-name') as c:
        c.argument('account_name', options_list=['--name', '-n'], id_part=None,
                   help='The name of the Azure Media Services account.')
        c.argument('location', arg_type=get_location_type(self.cli_ctx))

    with self.argument_context('ams account mru') as c:
        c.argument('type', help='Speed of reserved processing units. The cost of media encoding depends on the pricing tier you choose. See https://azure.microsoft.com/pricing/details/media-services/ for further details. Allowed values: {}.'.format(", ".join(get_mru_type_completion_list())))
        c.argument('count', type=int, help='The number of the encoding reserved units that you want to be provisioned for this account for concurrent tasks (one unit equals one task).')

    with self.argument_context('ams account storage') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('storage_account', name_arg_type,
                   help='The name or resource ID of the secondary storage account to detach from the Azure Media Services account.',
                   validator=validate_storage_account_id)

    with self.argument_context('ams account storage sync-storage-keys') as c:
        c.argument('id', required=True)

    with self.argument_context('ams account sp') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('sp_name', name_arg_type,
                   help="The app name or app URI to associate the RBAC with. If not present, a default name like '{amsaccountname}-access-sp' will be generated.")
        c.argument('sp_password', password_arg_type,
                   help="The password used to log in. Also known as 'Client Secret'. If not present, a random secret will be generated.")
        c.argument('role', help='The role of the service principal.', completer=get_role_definition_name_completion_list)
        c.argument('xml', action='store_true', help='Enables xml output format.')
        c.argument('years', help='Number of years for which the secret will be valid. Default: 1 year.', type=int, default=None)

    with self.argument_context('ams transform') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('transform_name', name_arg_type, id_part='child_name_1',
                   help='The name of the transform.')
        c.argument('preset', help='Preset that describes the operations that will be used to modify, transcode, or extract insights from the source file to generate the transform output. Allowed values: {}. In addition to the allowed values, you can also pass a path to a custom Standard Encoder preset JSON file. See https://docs.microsoft.com/rest/api/media/transforms/createorupdate#standardencoderpreset for further details on the settings to use to build a custom preset.'
                   .format(", ".join(get_presets_definition_name_completion_list())))
        c.argument('insights_to_extract', arg_group='Video Analyzer', arg_type=get_enum_type(InsightsType), help='The type of insights to be extracted. If not set then the type will be selected based on the content type. If the content is audio only then only audio insights will be extracted and if it is video only video insights will be extracted.')
        c.argument('audio_language', arg_group='Audio/Video Analyzer', help='The language for the audio payload in the input using the BCP-47 format of \"language tag-region\" (e.g: en-US). If not specified, automatic language detection would be employed. This feature currently supports English, Chinese, French, German, Italian, Japanese, Spanish, Russian, and Portuguese. The automatic detection works best with audio recordings with clearly discernable speech. If automatic detection fails to find the language, transcription would fallback to English. Allowed values: {}.'
                   .format(", ".join(get_allowed_languages_for_preset_completion_list())))
        c.argument('relative_priority', arg_type=get_enum_type(Priority), help='Sets the relative priority of the transform outputs within a transform. This sets the priority that the service uses for processing TransformOutputs. The default priority is Normal.')
        c.argument('on_error', arg_type=get_enum_type(OnErrorType), help="A Transform can define more than one output. This property defines what the service should do when one output fails - either continue to produce other outputs, or, stop the other outputs. The overall Job state will not reflect failures of outputs that are specified with 'ContinueJob'. The default is 'StopProcessingJob'.")
        c.argument('description', help='The description of the transform.')

    with self.argument_context('ams transform output remove') as c:
        c.argument('output_index', help='The element index of the output to remove.',
                   type=int, default=None)

    with self.argument_context('ams transform list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams asset') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('asset_name', name_arg_type, id_part='child_name_1',
                   help='The name of the asset.')

    with self.argument_context('ams asset list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams asset create') as c:
        c.argument('alternate_id', help='The alternate id of the asset.')
        c.argument('description', help='The asset description.')
        c.argument('asset_name', name_arg_type, help='The name of the asset.')
        c.argument('storage_account', help='The name of the storage account.')
        c.argument('container', help='The name of the asset blob container.')

    with self.argument_context('ams asset update') as c:
        c.argument('alternate_id', help='The alternate id of the asset.')
        c.argument('description', help='The asset description.')

    with self.argument_context('ams asset get-sas-urls') as c:
        c.argument('permissions', arg_type=get_enum_type(AssetContainerPermission),
                   help='The permissions to set on the SAS URL.')
        c.argument('expiry_time', expiry_arg_type, help="Specifies the UTC datetime (Y-m-d'T'H:M:S'Z') at which the SAS becomes invalid.")

    with self.argument_context('ams asset-filter') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('asset_name', help='The name of the asset.', id_part='child_name_1')
        c.argument('filter_name', name_arg_type, id_part='child_name_2', help='The name of the asset filter.')
        c.argument('start_timestamp', arg_group='Presentation Time Range',
                   help='Applies to Video on Demand (VoD) or Live Streaming. This is a long value that represents an absolute start point of the stream. The value gets rounded to the closest next GOP start. The unit is the timescale, so a startTimestamp of 150000000 would be for 15 seconds. Use startTimestamp and endTimestampp to trim the fragments that will be in the playlist (manifest). For example, startTimestamp=40000000 and endTimestamp=100000000 using the default timescale will generate a playlist that contains fragments from between 4 seconds and 10 seconds of the VoD presentation. If a fragment straddles the boundary, the entire fragment will be included in the manifest.')
        c.argument('end_timestamp', arg_group='Presentation Time Range',
                   help='Applies to Video on Demand (VoD).For the Live Streaming presentation, it is silently ignored and applied when the presentation ends and the stream becomes VoD.This is a long value that represents an absolute end point of the presentation, rounded to the closest next GOP start. The unit is the timescale, so an endTimestamp of 1800000000 would be for 3 minutes.Use startTimestamp and endTimestamp to trim the fragments that will be in the playlist (manifest).For example, startTimestamp=40000000 and endTimestamp=100000000 using the default timescale will generate a playlist that contains fragments from between 4 seconds and 10 seconds of the VoD presentation. If a fragment straddles the boundary, the entire fragment will be included in the manifest.')
        c.argument('presentation_window_duration', arg_group='Presentation Time Range',
                   help='Applies to Live Streaming only.Use presentationWindowDuration to apply a sliding window of fragments to include in a playlist.The unit for this property is timescale (see below).For example, set presentationWindowDuration=1200000000 to apply a two-minute sliding window. Media within 2 minutes of the live edge will be included in the playlist. If a fragment straddles the boundary, the entire fragment will be included in the playlist. The minimum presentation window duration is 60 seconds.')
        c.argument('live_backoff_duration', arg_group='Presentation Time Range',
                   help='Applies to Live Streaming only. This value defines the latest live position that a client can seek to. Using this property, you can delay live playback position and create a server-side buffer for players. The unit for this property is timescale (see below). The maximum live back off duration is 300 seconds (3000000000). For example, a value of 2000000000 means that the latest available content is 20 seconds delayed from the real live edge.')
        c.argument('timescale', arg_group='Presentation Time Range',
                   help='Applies to all timestamps and durations in a Presentation Time Range, specified as the number of increments in one second.Default is 10000000 - ten million increments in one second, where each increment would be 100 nanoseconds long. For example, if you want to set a startTimestamp at 30 seconds, you would use a value of 300000000 when using the default timescale.')
        c.argument('force_end_timestamp', arg_group='Presentation Time Range', arg_type=get_three_state_flag(),
                   help='Applies to Live Streaming only. Indicates whether the endTimestamp property must be present. If true, endTimestamp must be specified or a bad request code is returned. Allowed values: false, true.')
        c.argument('bitrate', help='The first quality bitrate.', deprecate_info=c.deprecate(target='--bitrate', redirect='--first-quality', hide=True))
        c.argument('first_quality', help='The first quality (lowest) bitrate to include in the manifest.')
        c.argument('tracks', help='The JSON representing the track selections. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/en-us/rest/api/media/assetfilters/assetfilters_createorupdate#filtertrackselection')

    with self.argument_context('ams asset-filter list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams job') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('transform_name', transform_name_arg_type, id_part='child_name_1',
                   help='The name of the transform.')
        c.argument('job_name', name_arg_type, id_part='child_name_2',
                   help='The name of the job.')
        c.argument('description', help='The job description.')
        c.argument('priority', arg_type=get_enum_type(Priority),
                   help='The priority with which the job should be processed.')

    with self.argument_context('ams job list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams job start') as c:
        c.argument('correlation_data', arg_type=correlation_data_type)
        c.argument('input_asset_name',
                   arg_group='Asset Job Input',
                   help='The name of the input asset.')
        c.argument('output_assets', arg_type=output_assets_type)
        c.argument('base_uri',
                   arg_group='Http Job Input',
                   help='Base uri for http job input. It will be concatenated with provided file names. If no base uri is given, then the provided file list is assumed to be fully qualified uris.')
        c.argument('files',
                   nargs='+',
                   help='Space-separated list of files. It can be used to tell the service to only use the files specified from the input asset.')
        c.argument('label', help="A label that is assigned to a Job Input that is used to satisfy a reference used in the Transform. For example, a Transform can be authored to take an image file with the label 'xyz' and apply it as an overlay onto the input video before it is encoded. When submitting a Job, exactly one of the JobInputs should be the image file, and it should have the label 'xyz'.")
        c.argument('correlation_data', arg_type=correlation_data_type)

    with self.argument_context('ams job cancel') as c:
        c.argument('delete', action='store_true', help='Delete the job being cancelled.')

    with self.argument_context('ams content-key-policy') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('content_key_policy_name', name_arg_type, id_part='child_name_1',
                   help='The content key policy name.')
        c.argument('description', help='The content key policy description.')
        c.argument('clear_key_configuration',
                   action='store_true',
                   arg_group='Clear Key Configuration (AES Encryption)',
                   help='Use Clear Key configuration, a.k.a AES encryption. It\'s intended for non-DRM keys.')
        c.argument('open_restriction',
                   action='store_true',
                   arg_group='Open Restriction',
                   help='Use open restriction. License or key will be delivered on every request. Not recommended for production environments.')
        c.argument('policy_option_name', help='The content key policy option name.')
        c.argument('policy_option_id', help='The content key policy option identifier. This value can be obtained from "policyOptionId" property by running a show operation on a content key policy resource.')
        c.argument('issuer', arg_group='Token Restriction', help='The token issuer.')
        c.argument('audience', arg_group='Token Restriction', help='The audience for the token.')
        c.argument('token_key', arg_group='Token Restriction', help='Either a string (for symmetric key) or a filepath to a certificate (x509) or public key (rsa). Must be used in conjunction with --token-key-type.')
        c.argument('token_key_type', arg_group='Token Restriction', help='The type of the token key to be used for the primary verification key. Allowed values: {}'.format(", ".join(get_token_completion_list())))
        c.argument('add_alt_token_key', arg_group='Token Restriction', help='Creates an alternate token key with either a string (for symmetric key) or a filepath to a certificate (x509) or public key (rsa). Must be used in conjunction with --add-alt-token-key-type.')
        c.argument('add_alt_token_key_type', arg_group='Token Restriction', help='The type of the token key to be used for the alternate verification key. Allowed values: {}'.format(", ".join(get_token_completion_list())))
        c.argument('alt_symmetric_token_keys', nargs='+', arg_group='Token Restriction', help='Space-separated list of alternate symmetric token keys.')
        c.argument('alt_rsa_token_keys', nargs='+', arg_group='Token Restriction', help='Space-separated list of alternate rsa token keys.')
        c.argument('alt_x509_token_keys', nargs='+', arg_group='Token Restriction', help='Space-separated list of alternate x509 certificate token keys.')
        c.argument('token_claims', arg_group='Token Restriction', arg_type=token_claim_type)
        c.argument('token_type', arg_group='Token Restriction',
                   help='The type of token. Allowed values: {}.'.format(", ".join(get_token_type_completion_list())))
        c.argument('open_id_connect_discovery_document', arg_group='Token Restriction', help='The OpenID connect discovery document.')
        c.argument('widevine_template', arg_group='Widevine Configuration', help='JSON Widevine license template. Use @{file} to load from a file.')
        c.argument('ask', arg_group='FairPlay Configuration', help='The key that must be used as FairPlay Application Secret Key.')
        c.argument('fair_play_pfx_password', arg_group='FairPlay Configuration', help='The password encrypting FairPlay certificate in PKCS 12 (pfx) format.')
        c.argument('fair_play_pfx', arg_group='FairPlay Configuration', help='The filepath to a FairPlay certificate file in PKCS 12 (pfx) format (including private key).')
        c.argument('rental_and_lease_key_type', arg_group='FairPlay Configuration', help='The rental and lease key type. Available values: {}.'.format(", ".join(get_fairplay_rentalandlease_completion_list())))
        c.argument('rental_duration', arg_group='FairPlay Configuration', help='The rental duration. Must be greater than or equal to 0.')
        c.argument('play_ready_template', arg_group='PlayReady Configuration', help='JSON PlayReady license template. Use @{file} to load from a file.')

    with self.argument_context('ams content-key-policy list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams content-key-policy show') as c:
        c.argument('with_secrets',
                   action='store_true',
                   help='Include secret values of the content key policy.')

    with self.argument_context('ams streaming-locator') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('default_content_key_policy_name', default_policy_name_arg_type)
        c.argument('streaming_locator_name', name_arg_type, id_part='child_name_1',
                   help='The name of the streaming locator.')
        c.argument('asset_name',
                   help='The name of the asset used by the streaming locator.')
        c.argument('streaming_policy_name',
                   help='The name of the streaming policy used by the streaming locator. You can either create one with `az ams streaming policy create` or use any of the predefined policies: {}'.format(", ".join(get_default_streaming_policies_completion_list())))
        c.argument('start_time', type=datetime_format,
                   help="The ISO 8601 DateTime start time (Y-m-d'T'H:M:S'Z') of the streaming locator.")
        c.argument('end_time', type=datetime_format,
                   help="The ISO 8601 DateTime end time (Y-m-d'T'H:M:S'Z') of the streaming locator.")
        c.argument('streaming_locator_id', help='The identifier of the streaming locator.')
        c.argument('alternative_media_id', help='An alternative media identifier associated with the streaming locator.')
        c.argument('content_keys', help='JSON string with the content keys to be used by the streaming locator. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/en-us/rest/api/media/streaminglocators/streaminglocators_create#streaminglocatorcontentkey')
        c.argument('filters', nargs='+', help='A space-separated list of asset filter names and/or account filter names.')

    with self.argument_context('ams streaming-locator list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams streaming-policy') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('streaming_policy_name', name_arg_type, id_part='child_name_1', help='The name of the streaming policy.')
        c.argument('default_content_key_policy_name', help='Default Content Key used by current streaming policy.')
        c.argument('no_encryption_protocols', nargs='+', help='Space-separated list of enabled protocols for NoEncryption. Allowed values: {}.'.format(", ".join(get_protocols_completion_list())))
        c.argument('envelope_protocols', nargs='+', arg_group='Envelope Encryption', help='Space-separated list of enabled protocols for Envelope Encryption. Allowed values: {}.'.format(", ".join(get_protocols_completion_list())))
        c.argument('envelope_clear_tracks', arg_group='Envelope Encryption', help='The JSON representing which tracks should not be encrypted. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/en-us/rest/api/media/streamingpolicies/create#trackselection')
        c.argument('envelope_key_to_track_mappings', arg_group='Envelope Encryption', help='The JSON representing a list of StreamingPolicyContentKey. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/en-us/rest/api/media/streamingpolicies/create#streamingpolicycontentkey')
        c.argument('envelope_default_key_label', arg_group='Envelope Encryption', help='Label used to specify Content Key when creating a streaming locator.')
        c.argument('envelope_default_key_policy_name', arg_group='Envelope Encryption', help='Policy used by Default Key.')
        c.argument('envelope_template', arg_group='Envelope Encryption', help='The KeyAcquistionUrlTemplate is used to point to user specified service to delivery content keys.')
        c.argument('cenc_protocols', nargs='+', arg_group='Common Encryption CENC', help='Space-separated list of enabled protocols for Common Encryption CENC. Allowed values: {}.'.format(", ".join(get_protocols_completion_list())))
        c.argument('cenc_default_key_label', arg_group='Common Encryption CENC', help='Label to specify Default Content Key for an encryption scheme.')
        c.argument('cenc_default_key_policy_name', arg_group='Common Encryption CENC', help='Policy used by Default Content Key.')
        c.argument('cenc_clear_tracks', arg_group='Common Encryption CENC', help='The JSON representing which tracks should not be encrypted. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/en-us/rest/api/media/streamingpolicies/create#trackselection')
        c.argument('cenc_key_to_track_mappings', arg_group='Common Encryption CENC', help='The JSON representing a list of StreamingPolicyContentKey. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/en-us/rest/api/media/streamingpolicies/create#streamingpolicycontentkey')
        c.argument('cenc_play_ready_attributes', arg_group='Common Encryption CENC', help='Custom attributes for PlayReady.')
        c.argument('cenc_widevine_template', arg_group='Common Encryption CENC', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.')
        c.argument('cenc_play_ready_template', arg_group='Common Encryption CENC', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.')
        c.argument('cenc_disable_widevine', arg_group='Common Encryption CENC', arg_type=get_three_state_flag(), help='If specified, no Widevine cenc DRM will be configured. If --cenc-disable-widevine is set, --cenc-disable-play-ready cannot also be set.')
        c.argument('cenc_disable_play_ready', arg_group='Common Encryption CENC', arg_type=get_three_state_flag(), help='If specified, no PlayReady cenc DRM will be configured. If --cenc-disable-play-ready is set, --cenc-disable-widevine cannot also be set.')
        c.argument('cbcs_protocols', nargs='+', arg_group='Common Encryption CBCS', help='Space-separated list of enabled protocols for Common Encryption CBCS. Allowed values: {}.'.format(", ".join(get_protocols_completion_list())))
        c.argument('cbcs_default_key_label', arg_group='Common Encryption CBCS', help='Label to specify Default Content Key for an encryption scheme.')
        c.argument('cbcs_default_key_policy_name', arg_group='Common Encryption CBCS', help='Policy used by Default Content Key.')
        c.argument('cbcs_clear_tracks', arg_group='Common Encryption CBCS', help='The JSON representing which tracks should not be encrypted. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/en-us/rest/api/media/streamingpolicies/create#trackselection')
        c.argument('cbcs_key_to_track_mappings', arg_group='Common Encryption CBCS', help='The JSON representing a list of StreamingPolicyContentKey. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/en-us/rest/api/media/streamingpolicies/create#streamingpolicycontentkey')
        c.argument('cbcs_play_ready_attributes', arg_group='Common Encryption CBCS', help='Custom attributes for PlayReady.', deprecate_info=c.deprecate(hide=True))
        c.argument('cbcs_play_ready_template', arg_group='Common Encryption CBCS', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.', deprecate_info=c.deprecate(hide=True))
        c.argument('cbcs_widevine_template', arg_group='Common Encryption CBCS', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.', deprecate_info=c.deprecate(hide=True))
        c.argument('cbcs_fair_play_template', arg_group='Common Encryption CBCS', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.')
        c.argument('cbcs_fair_play_allow_persistent_license', arg_group='Common Encryption CBCS', arg_type=get_three_state_flag(), help='Allows the license to be persistent or not.')

    with self.argument_context('ams streaming-policy list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams streaming-endpoint') as c:
        c.argument('streaming_endpoint_name', name_arg_type, id_part='child_name_1',
                   help='The name of the streaming endpoint.')
        c.argument('account_name', account_name_arg_type)
        c.argument('tags', arg_type=tags_type)
        c.argument('description', help='The streaming endpoint description.')
        c.argument('scale_units', help='The number of scale units for Premium StreamingEndpoints. For Standard StreamingEndpoints, set this value to 0. Use the Scale operation to adjust this value for Premium StreamingEndpoints.')
        c.argument('availability_set_name', help='The name of the AvailabilitySet used with this StreamingEndpoint for high availability streaming. This value can only be set at creation time.')
        c.argument('max_cache_age', help='Max cache age.')
        c.argument('custom_host_names', nargs='+', help='Space-separated list of custom host names for the streaming endpoint. Use "" to clear existing list.')
        c.argument('cdn_provider', arg_group='CDN Support', help='The CDN provider name. Allowed values: {}.'.format(", ".join(get_cdn_provider_completion_list())))
        c.argument('cdn_profile', arg_group='CDN Support', help='The CDN profile name.')
        c.argument('client_access_policy', arg_group='Cross Site Access Policies',
                   help='The XML representing the clientaccesspolicy data used by Microsoft Silverlight and Adobe Flash. Use @{file} to load from a file. For further information about the XML structure please refer to documentation on https://docs.microsoft.com/en-us/rest/api/media/operations/crosssiteaccesspolicies')
        c.argument('cross_domain_policy', arg_group='Cross Site Access Policies',
                   help='The XML representing the crossdomain data used by Silverlight. Use @{file} to load from a file. For further information about the XML structure please refer to documentation on https://docs.microsoft.com/en-us/rest/api/media/operations/crosssiteaccesspolicies')
        c.argument('auto_start', action='store_true', help='The flag indicates if the resource should be automatically started on creation.')
        c.argument('ips', nargs='+', arg_group='Access Control Support', help='Space-separated IP addresses for access control. Allowed IP addresses can be specified as either a single IP address (e.g. "10.0.0.1") or as an IP range using an IP address and a CIDR subnet mask (e.g. "10.0.0.1/22"). Use "" to clear existing list. If no IP addresses are specified any IP address will be allowed.')
        c.argument('disable_cdn', arg_group='CDN Support', action='store_true', help='Use this flag to disable CDN for the streaming endpoint.')

    with self.argument_context('ams streaming-endpoint list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams streaming-endpoint scale') as c:
        c.argument('scale_unit', options_list=['--scale-units'], help='The number of scale units for Premium StreamingEndpoints.')

    with self.argument_context('ams streaming-endpoint akamai') as c:
        c.argument('identifier', help='The identifier for the authentication key. This is the nonce provided by Akamai.')
        c.argument('base64_key', help='Base64-encoded authentication key that will be used by the CDN. The authentication key provided by Akamai is an ASCII encoded string, and must be converted to bytes and then base64 encoded.')
        c.argument('expiration', type=datetime_format,
                   help='The ISO 8601 DateTime value that specifies when the Akamai authentication expires.')

    with self.argument_context('ams streaming-endpoint list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams live-event') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('live_event_name', name_arg_type, id_part='child_name_1',
                   help='The name of the live event.')
        c.argument('streaming_protocol', arg_type=get_enum_type(LiveEventInputProtocol),
                   arg_group='Input', help='The streaming protocol for the live event. This value is specified at creation time and cannot be updated.')
        c.argument('auto_start', action='store_true', help='The flag indicates if the resource should be automatically started on creation.')
        c.argument('encoding_type', arg_group='Encoding', help='The encoding type for live event. This value is specified at creation time and cannot be updated. Allowed values: {}.'.format(", ".join(get_encoding_types_list())))
        c.argument('preset_name', arg_group='Encoding', help='The encoding preset name. This value is specified at creation time and cannot be updated.')
        c.argument('tags', arg_type=tags_type)
        c.argument('key_frame_interval_duration', key_frame_interval_duration_arg_type, arg_group='Input', validator=validate_key_frame_interval_duration,
                   help='ISO 8601 timespan duration of the key frame interval duration in seconds. The value should be an interger in the range of 1 (PT1S or 00:00:01) to 30 (PT30S or 00:00:30) seconds.')
        c.argument('access_token', arg_group='Input', help='A unique identifier for a stream. This can be specified at creation time but cannot be updated. If omitted, the service will generate a unique value.')
        c.argument('description', help='The live event description.')
        c.argument('ips', nargs='+', arg_group='Input', help='Space-separated IP addresses for access control. Allowed IP addresses can be specified as either a single IP address (e.g. "10.0.0.1") or as an IP range using an IP address and a CIDR subnet mask (e.g. "10.0.0.1/22"). Use "" to clear existing list. Use "AllowAll" to allow all IP addresses. Allowing all IPs is not recommended for production environments.')
        c.argument('preview_ips', nargs='+', arg_group='Preview', help='Space-separated IP addresses for access control. Allowed IP addresses can be specified as either a single IP address (e.g. "10.0.0.1") or as an IP range using an IP address and a CIDR subnet mask (e.g. "10.0.0.1/22"). Use "" to clear existing list. Use "AllowAll" to allow all IP addresses. Allowing all IPs is not recommended for production environments.')
        c.argument('preview_locator', arg_group='Preview', help='The identifier of the preview locator in Guid format. Specifying this at creation time allows the caller to know the preview locator url before the event is created. If omitted, the service will generate a random identifier. This value cannot be updated once the live event is created.')
        c.argument('streaming_policy_name', arg_group='Preview', help='The name of streaming policy used for the live event preview. This can be specified at creation time but cannot be updated.')
        c.argument('alternative_media_id', arg_group='Preview', help='An Alternative Media Identifier associated with the StreamingLocator created for the preview. This value is specified at creation time and cannot be updated. The identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the StreamingPolicyName field.')
        c.argument('vanity_url', arg_type=get_three_state_flag(), help='Specifies whether to use a vanity url with the Live Event. This value is specified at creation time and cannot be updated.')
        c.argument('client_access_policy', arg_group='Cross Site Access Policies', help='Filepath to the clientaccesspolicy.xml used by Microsoft Silverlight and Adobe Flash. Use @{file} to load from a file.')
        c.argument('cross_domain_policy', arg_group='Cross Site Access Policies', help='Filepath to the crossdomain.xml used by Microsoft Silverlight and Adobe Flash. Use @{file} to load from a file.')
        c.argument('stream_options', nargs='+', arg_type=get_enum_type(StreamOptionsFlag), help='The options to use for the LiveEvent. This value is specified at creation time and cannot be updated.')
        c.argument('remove_outputs_on_stop', action='store_true', help='Remove live outputs on stop.')

    with self.argument_context('ams live-event list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams live-output') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('live_event_name', id_part='child_name_1',
                   help='The name of the live event.')
        c.argument('live_output_name', name_arg_type, id_part='child_name_2',
                   help='The name of the live output.')

    with self.argument_context('ams live-output list') as c:
        c.argument('account_name', id_part=None)

    with self.argument_context('ams live-output create') as c:
        c.argument('asset_name', help='The name of the asset.')
        c.argument('archive_window_length', archive_window_length_arg_type, validator=validate_archive_window_length,
                   help="ISO 8601 timespan duration of the archive window length. This is the duration that customer want to retain the recorded content. Minimum window is 5 minutes (PT5M or 00:05:00). Maximum window is 25 hours (PT25H or 25:00:00). For example, to retain the output for 10 minutes, use PT10M or 00:10:00")
        c.argument('manifest_name', help='The manifest file name. If not provided, the service will generate one automatically.')
        c.argument('description', help='The live output description.')
        c.argument('fragments_per_ts_segment', help='The number of fragments per HLS segment.')
        c.argument('output_snap_time', help='The output snapshot time.')

    with self.argument_context('ams account-filter') as c:
        c.argument('account_name', account_name_arg_type)
        c.argument('filter_name', name_arg_type, id_part='child_name_1', help='The name of the account filter.')
        c.argument('start_timestamp', arg_group='Presentation Time Range',
                   help='Applies to Video on Demand (VoD) or Live Streaming. This is a long value that represents an absolute start point of the stream. The value gets rounded to the closest next GOP start. The unit is the timescale, so a startTimestamp of 150000000 would be for 15 seconds. Use startTimestamp and endTimestampp to trim the fragments that will be in the playlist (manifest). For example, startTimestamp=40000000 and endTimestamp=100000000 using the default timescale will generate a playlist that contains fragments from between 4 seconds and 10 seconds of the VoD presentation. If a fragment straddles the boundary, the entire fragment will be included in the manifest.')
        c.argument('end_timestamp', arg_group='Presentation Time Range',
                   help='Applies to Video on Demand (VoD). For the Live Streaming presentation, it is silently ignored and applied when the presentation ends and the stream becomes VoD. This is a long value that represents an absolute end point of the presentation, rounded to the closest next GOP start. The unit is the timescale, so an endTimestamp of 1800000000 would be for 3 minutes. Use startTimestamp and endTimestamp to trim the fragments that will be in the playlist (manifest). For example, startTimestamp=40000000 and endTimestamp=100000000 using the default timescale will generate a playlist that contains fragments from between 4 seconds and 10 seconds of the VoD presentation. If a fragment straddles the boundary, the entire fragment will be included in the manifest.')
        c.argument('presentation_window_duration', arg_group='Presentation Time Range',
                   help='Applies to Live Streaming only. Use presentationWindowDuration to apply a sliding window of fragments to include in a playlist. The unit for this property is timescale (see below). For example, set presentationWindowDuration=1200000000 to apply a two-minute sliding window. Media within 2 minutes of the live edge will be included in the playlist. If a fragment straddles the boundary, the entire fragment will be included in the playlist. The minimum presentation window duration is 60 seconds.')
        c.argument('live_backoff_duration', arg_group='Presentation Time Range',
                   help='Applies to Live Streaming only. This value defines the latest live position that a client can seek to. Using this property, you can delay live playback position and create a server-side buffer for players. The unit for this property is timescale (see below). The maximum live back off duration is 300 seconds (3000000000). For example, a value of 2000000000 means that the latest available content is 20 seconds delayed from the real live edge.')
        c.argument('timescale', arg_group='Presentation Time Range',
                   help='Applies to all timestamps and durations in a Presentation Time Range, specified as the number of increments in one second. Default is 10000000 - ten million increments in one second, where each increment would be 100 nanoseconds long. For example, if you want to set a startTimestamp at 30 seconds, you would use a value of 300000000 when using the default timescale.')
        c.argument('force_end_timestamp', arg_group='Presentation Time Range', arg_type=get_three_state_flag(),
                   help='Applies to Live Streaming only. Indicates whether the endTimestamp property must be present. If true, endTimestamp must be specified or a bad request code is returned. Allowed values: false, true.')
        c.argument('bitrate', help='The first quality bitrate.', deprecate_info=c.deprecate(target='--bitrate', redirect='--first-quality', hide=True))
        c.argument('first_quality', help='The first quality (lowest) bitrate to include in the manifest.')
        c.argument('tracks', help='The JSON representing the track selections. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/en-us/rest/api/media/accountfilters/createorupdate#filtertrackselection')

    with self.argument_context('ams account-filter list') as c:
        c.argument('account_name', id_part=None)
Exemplo n.º 20
0
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

from knack.arguments import CLIArgumentType

from azure.cli.core.commands.parameters import (resource_group_name_type,
                                                get_enum_type,
                                                get_three_state_flag,
                                                tags_type)

name_arg_type = CLIArgumentType(metavar='NAME',
                                configured_default='botname',
                                id_part='Name')

# supported_languages will be use with get_enum_type after the 'Node' value is completely removed from `az bot`
# In custom.py we're still supporting 'Node' in __language_validator()
SUPPORTED_LANGUAGES = ['Csharp', 'Javascript']
UPCOMING_LANGUAGES = ['Csharp', 'Javascript', 'Typescript']
SUPPORTED_APP_INSIGHTS_REGIONS = [
    'Australia East', 'Canada Central', 'Central India', 'East Asia',
    'East US', 'East US 2', 'France Central', 'Japan East', 'Korea Central',
    'North Europe', 'South Central US', 'Southeast Asia', 'UK South',
    'West Europe', 'West US 2'
]
SUPPORTED_SKUS = ['F0', 'S1']


# pylint: disable=line-too-long,too-many-statements
def load_arguments(self, _):
Exemplo n.º 21
0
def load_arguments(self, _):

    AzureFirewallNetworkRuleProtocol, AzureFirewallRCActionType, \
        AzureFirewallNatRCActionType, FirewallPolicySkuTier = \
        self.get_models('AzureFirewallNetworkRuleProtocol', 'AzureFirewallRCActionType',
                        'AzureFirewallNatRCActionType', 'FirewallPolicySkuTier')

    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('destination_fqdns', nargs='+', help="Space-separated list of destination FQDNs.")
        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('source_ip_groups', nargs='+', help='Space-separated list of name or resource id of source IpGroups.')
        c.argument('destination_ip_groups', nargs='+', help='Space-separated list of name or resource id of destination IpGroups')
        c.argument('translated_address', help='Translated address for this NAT rule.')
        c.argument('translated_port', help='Translated port for this NAT rule.')
        c.argument('translated_fqdn', help='Translated FQDN for this NAT rule.')
        c.argument('tags', tags_type)
        c.argument('zones', zones_type)
        c.argument('firewall_policy', options_list=['--firewall-policy', '--policy'],
                   help='Name or ID of the firewallPolicy associated with this azure firewall.',
                   validator=validate_firewall_policy)
        c.argument('virtual_hub', options_list=['--virtual-hub', '--vhub'],
                   help='Name or ID of the virtualHub to which the firewall belongs.',
                   validator=validate_virtual_hub)
        c.argument('sku', arg_type=get_enum_type(['AZFW_VNet', 'AZFW_Hub']), help='SKU of Azure firewall. This field cannot be updated after the creation. '
                                                                                  'The default sku in server end is AZFW_VNet. '
                                                                                  'If you want to attach azure firewall to vhub, you should set sku to AZFW_Hub.')
        c.argument('private_ranges', nargs='+', validator=process_private_ranges, help='Space-separated list of SNAT private range. Validate values are single Ip, Ip prefixes or a single special value "IANAPrivateRanges"')
        c.argument('threat_intel_mode', arg_type=get_enum_type(['Alert', 'Deny', 'Off']), help='The operation mode for Threat Intelligence.')
        c.argument('allow_active_ftp', arg_type=get_three_state_flag(),
                   help="Allow Active FTP. By default it is false. It's only allowed for azure firewall on virtual network.")

    with self.argument_context('network firewall', arg_group='Virtual Hub Public Ip') as c:
        c.argument('hub_public_ip_count', options_list=['--public-ip-count', '--count'], type=int,
                   help="Number of Public IP Address associated with azure firewall. "
                        "It's used to add public ip addresses into this firewall.")
        c.argument('hub_public_ip_addresses', nargs='+', options_list=['--public-ips'],
                   help="Space-separated list of Public IP addresses associated with azure firewall. "
                        "It's used to delete public ip addresses from this firewall. ")

    with self.argument_context('network firewall', arg_group='DNS') as c:
        c.argument('dns_servers', nargs='+', help='Space-separated list of DNS server IP addresses')
        c.argument('enable_dns_proxy', arg_type=get_three_state_flag(), help='Enable DNS Proxy')

    with self.argument_context('network firewall threat-intel-allowlist') as c:
        c.argument('ip_addresses', nargs='+', validator=process_threat_intel_allowlist_ip_addresses, help='Space-separated list of IPv4 addresses.')
        c.argument('fqdns', nargs='+', validator=process_threat_intel_allowlist_fqdns, help='Space-separated list of FQDNs.')

    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). Supply only if you want to create the collection.', 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. Supply only if you want to create the 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. Supply only if you want to create the 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, help='The virtual network (VNet) name. It should contain one subnet called "AzureFirewallSubnet".')
        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', deprecate_info=c.deprecate(expiration='2.3.0'), help='IP address used by the Firewall ILB as the next hop in User Defined Routes.')

    with self.argument_context('network firewall ip-config', arg_group="Management Ip Config") as c:
        c.argument('management_item_name', options_list=['--m-name'],
                   help='Name of the management IP configuration.', is_preview=True)
        c.argument('management_subnet', validator=get_management_subnet_validator(), help=argparse.SUPPRESS, is_preview=True)
        c.argument('management_virtual_network_name', virtual_network_name_type, options_list=['--m-vnet-name'],
                   help='The virtual network (VNet) name for management ip configuation. '
                        'It should contain one subnet called "AzureFirewallManagementSubnet".', is_preview=True)
        c.argument('management_public_ip_address', help='Name or ID of the public IP to use for management ip configuation.',
                   options_list=['--m-public-ip-address'], validator=get_management_public_ip_validator(), is_preview=True)

    with self.argument_context('network firewall management-ip-config') as c:
        c.argument('item_name', options_list=['--name', '-n'], help='Name of the management 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,
                   help='The virtual network (VNet) name. It should contain one subnet called "AzureFirewallManagementSubnet".')
        c.argument('public_ip_address', help='Name or ID of the public IP to use.', validator=get_public_ip_validator())

    with self.argument_context('network firewall ip-config list') as c:
        c.argument('resource_name', firewall_name_type, id_part=None)

    with self.argument_context('network firewall policy') as c:
        c.argument('firewall_policy_name', options_list=['--name', '-n'], help='The name of the Firewall Policy.')
        c.argument('base_policy', validator=validate_firewall_policy, help='The name or ID of parent firewall policy from which rules are inherited.')
        c.argument('threat_intel_mode', arg_type=get_enum_type(['Alert', 'Deny', 'Off']), help='The operation mode for Threat Intelligence.')
        c.argument('sku', arg_type=get_enum_type(FirewallPolicySkuTier), help='SKU of Firewall policy', is_preview=True)

    with self.argument_context('network firewall policy', arg_group='Threat Intel Allowlist') as c:
        c.argument('ip_addresses', nargs='+', help='Space-separated list of IPv4 addresses.')
        c.argument('fqdns', nargs='+', help='Space-separated list of FQDNs.')

    with self.argument_context('network firewall policy rule-collection-group') as c:
        c.argument('firewall_policy_name', options_list=['--policy-name'], help='The name of the Firewall Policy.')
        c.argument('rule_collection_group_name', options_list=['--name', '-n'], help='The name of the Firewall Policy Rule Collection Group.')
        c.argument('priority', type=int, help='Priority of the Firewall Policy Rule Collection Group')

    with self.argument_context('network firewall policy rule-collection-group collection') as c:
        c.argument('rule_collection_group_name', options_list=['--rule-collection-group-name'], help='The name of the Firewall Policy Rule Collection Group.')
        c.argument('rule_collection_name', options_list=['--name', '-n'], help='The name of the collection in Firewall Policy Rule Collection Group.')
        c.argument('rule_priority', options_list=['--collection-priority'], type=int, help='The priority of the rule in Firewall Policy Rule Collection Group')

    with self.argument_context('network firewall policy rule-collection-group collection', arg_group='Common Rule') as c:
        c.argument('description', help='The description of rule.')
        c.argument('destination_addresses', nargs='+', help="Space-separated list of destination IP addresses.")
        c.argument('source_addresses', nargs='+', help="Space-separated list of source IP addresses.")
        c.argument('rule_name', options_list=['--rule-name'], help='The name of rule')
        c.argument('rule_type', options_list=['--rule-type'], arg_type=get_enum_type(["ApplicationRule", "NetworkRule", "NatRule"]), help='The type of rule')
        c.argument('destination_ports', nargs='+', help="Space-separated list of destination ports. This argument is supported for Nat and Network Rule.")
        c.argument('ip_protocols', nargs='+', arg_type=get_enum_type(["TCP", "UDP", "Any", "ICMP"]),
                   help="Space-separated list of IP protocols. This argument is supported for Nat and Network Rule.")
        c.argument('source_ip_groups', nargs='+', validator=validate_ip_groups,
                   help='Space-separated list of name or resource id of source IpGroups.')

    with self.argument_context('network firewall policy rule-collection-group collection', arg_group='Nat Rule') as c:
        c.argument('translated_address', help='Translated address for this NAT rule collection.')
        c.argument('translated_port', help='Translated port for this NAT rule collection.')
        c.argument('translated_fqdn', help='Translated FQDN for this NAT rule collection.')

    with self.argument_context('network firewall policy rule-collection-group collection', arg_group='Application Rule') as c:
        c.argument('target_fqdns', nargs='+', help='Space-separated list of FQDNs for this rule.', validator=validate_rule_group_collection)
        c.argument('target_urls', nargs='+', help='Space-separated list of target urls for this rule')
        c.argument('enable_terminate_tls', arg_type=get_three_state_flag(), help='Enable flag to terminate TLS connection for this rule')
        c.argument('fqdn_tags', nargs='+', help='Space-separated list of FQDN tags for this rule.', validator=validate_rule_group_collection)
        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.')

    with self.argument_context('network firewall policy rule-collection-group collection', arg_group='Network Rule') as c:
        c.argument('destination_ip_groups', nargs='+', validator=validate_ip_groups,
                   help='Space-separated list of name or resource id of destination IpGroups')

    with self.argument_context('network firewall policy rule-collection-group collection add-filter-collection') as c:
        c.argument('filter_action', options_list=['--action'], arg_type=get_enum_type(['Allow', 'Deny']), help='The action type of a rule collection.')

    with self.argument_context('network firewall policy rule-collection-group collection add-nat-collection') as c:
        c.argument('nat_action', options_list=['--action'], arg_type=get_enum_type(['DNAT', 'SNAT']), help='The action type of a rule collection.')

    with self.argument_context('network firewall policy rule-collection-group collection rule') as c:
        c.argument('rule_collection_name', options_list=['--collection-name'], help='The name of the rule collection in Firewall Policy Rule Collection Group.')
        c.argument('rule_name', options_list=['--name', '-n'], arg_group='Common Rule', help='The name of rule')
Exemplo n.º 22
0
        raise CLIError(message)


def _secure_environment_variables_type(value):
    """Space-separated values in 'key=value' format."""
    try:
        env_name, env_secure_value = value.split('=', 1)
        return {'name': env_name, 'secureValue': env_secure_value}
    except ValueError:
        message = ("Incorrectly formatted secure environment settings. "
                   "Argument values should be in the format a=b c=d")
        raise CLIError(message)


secrets_type = CLIArgumentType(
    validator=validate_secrets,
    help="space-separated secrets in 'key=value' format.",
    nargs='+')


# pylint: disable=too-many-statements
def load_arguments(self, _):
    with self.argument_context('container') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('name',
                   options_list=['--name', '-n'],
                   help="The name of the container group",
                   id_part='name')
        c.argument('location', arg_type=get_location_type(self.cli_ctx))

    with self.argument_context('container create') as c:
        c.argument('location',
Exemplo n.º 23
0
def load_arguments(self, _):
    from argcomplete.completers import FilesCompleter

    from azure.mgmt.resource.locks.models import LockLevel
    from azure.mgmt.resource.managedapplications.models import ApplicationLockLevel

    from azure.cli.core.api import get_subscription_id_list
    from azure.cli.core.commands.parameters import (
        resource_group_name_type, get_location_type, tag_type, tags_type,
        get_resource_group_completion_list, no_wait_type, file_type,
        get_enum_type, get_three_state_flag)
    from azure.cli.core.profiles import ResourceType
    from azure.cli.core.local_context import LocalContextAttribute, LocalContextAction, ALL

    from knack.arguments import ignore_type, CLIArgumentType

    from azure.cli.command_modules.resource._completers import (
        get_policy_completion_list, get_policy_set_completion_list,
        get_policy_assignment_completion_list,
        get_resource_types_completion_list, get_providers_completion_list)
    from azure.cli.command_modules.resource._validators import (
        validate_lock_parameters, validate_resource_lock, validate_group_lock,
        validate_subscription_lock, validate_metadata, RollbackAction,
        validate_msi)

    DeploymentMode, WhatIfResultFormat = self.get_models(
        'DeploymentMode',
        'WhatIfResultFormat',
        resource_type=ResourceType.MGMT_RESOURCE_RESOURCES)

    # BASIC PARAMETER CONFIGURATION

    resource_name_type = CLIArgumentType(options_list=['--name', '-n'],
                                         help='The resource name. (Ex: myC)')
    resource_type_type = CLIArgumentType(
        help=
        "The resource type (Ex: 'resC'). Can also accept namespace/type format (Ex: 'Microsoft.Provider/resC')"
    )
    resource_namespace_type = CLIArgumentType(
        options_list='--namespace',
        completer=get_providers_completion_list,
        help="Provider namespace (Ex: 'Microsoft.Provider')")
    resource_parent_type = CLIArgumentType(
        required=False,
        options_list=['--parent'],
        help="The parent path (Ex: 'resA/myA/resB/myB')")
    existing_policy_definition_name_type = CLIArgumentType(
        options_list=['--name', '-n'],
        completer=get_policy_completion_list,
        help='The policy definition name.')
    existing_policy_set_definition_name_type = CLIArgumentType(
        options_list=['--name', '-n'],
        completer=get_policy_set_completion_list,
        help='The policy set definition name.')
    subscription_type = CLIArgumentType(
        options_list='--subscription',
        FilesCompleter=get_subscription_id_list,
        help='The subscription id of the policy [set] definition.')
    management_group_name_type = CLIArgumentType(
        options_list='--management-group',
        help='The name of the management group of the policy [set] definition.'
    )
    identity_scope_type = CLIArgumentType(
        help="Scope that the system assigned identity can access")
    identity_role_type = CLIArgumentType(
        options_list=['--role'],
        help="Role name or id that will be assigned to the managed identity")
    extended_json_format_type = CLIArgumentType(
        options_list=['--handle-extended-json-format', '-j'],
        action='store_true',
        help=
        'Support to handle extended template content including multiline and comments in deployment'
    )
    deployment_name_type = CLIArgumentType(options_list=['--name', '-n'],
                                           required=True,
                                           help='The deployment name.')
    deployment_create_name_type = CLIArgumentType(
        options_list=['--name', '-n'],
        required=False,
        help='The deployment name. Default to template file base name')
    management_group_id_type = CLIArgumentType(
        options_list=['--management-group-id', '-m'],
        required=True,
        help='The management group id.')
    deployment_template_file_type = CLIArgumentType(
        options_list=['--template-file', '-f'],
        completer=FilesCompleter(),
        type=file_type,
        help="a template file path in the file system")
    deployment_template_uri_type = CLIArgumentType(
        options_list=['--template-uri', '-u'],
        help='a uri to a remote template file')
    deployment_parameters_type = CLIArgumentType(
        options_list=['--parameters', '-p'],
        action='append',
        nargs='+',
        completer=FilesCompleter(),
        help='the deployment parameters')
    filter_type = CLIArgumentType(
        options_list=['--filter'],
        is_preview=True,
        help=
        'Filter expression using OData notation. You can use --filter "provisioningState eq \'{state}\'" to filter provisioningState. '
        'To get more information, please visit https://docs.microsoft.com/en-us/rest/api/resources/deployments/listatsubscriptionscope#uri-parameters'
    )
    no_prompt = CLIArgumentType(
        arg_type=get_three_state_flag(),
        help=
        'The option to disable the prompt of missing parameters for ARM template. '
        'When the value is true, the prompt requiring users to provide missing parameter will be ignored. The default value is false.'
    )

    deployment_what_if_result_format_type = CLIArgumentType(
        options_list=['--result-format', '-r'],
        arg_type=get_enum_type(WhatIfResultFormat, "FullResourcePayloads"),
        is_preview=True,
        min_api='2019-07-01')
    deployment_what_if_no_pretty_print_type = CLIArgumentType(
        options_list=['--no-pretty-print'],
        action='store_true',
        help=
        'Disable pretty-print for What-If results. When set, the output format type will be used.'
    )
    deployment_what_if_confirmation_type = CLIArgumentType(
        options_list=['--confirm-with-what-if', '-c'],
        action='store_true',
        help=
        'Instruct the command to run deployment What-If before executing the deployment. It then prompts you to acknowledge resource changes before it continues.',
        is_preview=True,
        min_api='2019-07-01')

    _PROVIDER_HELP_TEXT = 'the resource namespace, aka \'provider\''

    with self.argument_context('resource') as c:
        c.argument('no_wait', no_wait_type)
        c.argument('resource_group_name',
                   resource_group_name_type,
                   arg_group='Resource Id')
        c.ignore('resource_id')
        c.argument('resource_name',
                   resource_name_type,
                   arg_group='Resource Id')
        c.argument('api_version',
                   help='The api version of the resource (omit for latest)',
                   required=False,
                   arg_group='Resource Id')
        c.argument('resource_provider_namespace',
                   resource_namespace_type,
                   arg_group='Resource Id')
        c.argument('resource_type',
                   arg_type=resource_type_type,
                   completer=get_resource_types_completion_list,
                   arg_group='Resource Id')
        c.argument('parent_resource_path',
                   resource_parent_type,
                   arg_group='Resource Id')
        c.argument('tag', tag_type)
        c.argument('tags', tags_type)
        c.argument(
            'resource_ids',
            nargs='+',
            options_list=['--ids'],
            help=
            'One or more resource IDs (space-delimited). If provided, no other "Resource Id" arguments should be specified.',
            arg_group='Resource Id')
        c.argument(
            'include_response_body',
            arg_type=get_three_state_flag(),
            help=
            'Use if the default command output doesn\'t capture all of the property data.'
        )

    with self.argument_context('resource list') as c:
        c.argument('name', resource_name_type)

    with self.argument_context('resource move') as c:
        c.argument('ids', nargs='+')

    with self.argument_context('resource invoke-action') as c:
        c.argument(
            'action',
            help='The action that will be invoked on the specified resource')
        c.argument(
            'request_body',
            help=
            'JSON encoded parameter arguments for the action that will be passed along in the post request body. Use @{file} to load from a file.'
        )

    with self.argument_context('resource create') as c:
        c.argument('resource_id',
                   options_list=['--id'],
                   help='Resource ID.',
                   action=None)
        c.argument(
            'properties',
            options_list=['--properties', '-p'],
            help='a JSON-formatted string containing resource properties')
        c.argument(
            'is_full_object',
            action='store_true',
            help=
            'Indicates that the properties object includes other options such as location, tags, sku, and/or plan.'
        )

    with self.argument_context('resource link') as c:
        c.argument(
            'target_id',
            options_list=[
                '--target',
                c.deprecate(target='--target-id',
                            redirect='--target',
                            hide=True)
            ],
            help='Fully-qualified resource ID of the resource link target.')
        c.argument('link_id',
                   options_list=[
                       '--link',
                       c.deprecate(target='--link-id',
                                   redirect='--link',
                                   hide=True)
                   ],
                   help='Fully-qualified resource ID of the resource link.')
        c.argument('notes', help='Notes for the link.')
        c.argument('scope', help='Fully-qualified scope for retrieving links.')
        c.argument('filter_string',
                   options_list=[
                       '--filter',
                       c.deprecate(target='--filter-string',
                                   redirect='--filter',
                                   hide=True)
                   ],
                   help='Filter string for limiting results.')

    with self.argument_context('resource tag') as c:
        c.argument(
            'is_incremental',
            action='store_true',
            options_list=['--is-incremental', '-i'],
            help=
            'The option to add tags incrementally without deleting the original tags. If the key of new tag and original tag are duplicated, the original value will be overwritten.'
        )

    with self.argument_context('provider') as c:
        c.ignore('top')
        c.argument('resource_provider_namespace',
                   options_list=['--namespace', '-n'],
                   completer=get_providers_completion_list,
                   help=_PROVIDER_HELP_TEXT)

    with self.argument_context('provider register') as c:
        c.argument('wait',
                   action='store_true',
                   help='wait for the registration to finish')

    with self.argument_context('provider unregister') as c:
        c.argument('wait',
                   action='store_true',
                   help='wait for unregistration to finish')

    with self.argument_context('provider operation') as c:
        c.argument(
            'api_version',
            help=
            "The api version of the 'Microsoft.Authorization/providerOperations' resource (omit for latest)"
        )

    with self.argument_context('feature') as c:
        c.argument('resource_provider_namespace',
                   options_list='--namespace',
                   required=True,
                   help=_PROVIDER_HELP_TEXT)
        c.argument('feature_name',
                   options_list=['--name', '-n'],
                   help='the feature name')

    with self.argument_context('feature list') as c:
        c.argument('resource_provider_namespace',
                   options_list='--namespace',
                   required=False,
                   help=_PROVIDER_HELP_TEXT)

    with self.argument_context('policy') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   help='the resource group where the policy will be applied')

    with self.argument_context(
            'policy definition',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('policy_definition_name',
                   arg_type=existing_policy_definition_name_type)
        c.argument(
            'rules',
            help='JSON formatted string or a path to a file with such content',
            type=file_type,
            completer=FilesCompleter())
        c.argument('display_name', help='Display name of policy definition.')
        c.argument('description', help='Description of policy definition.')
        c.argument(
            'params',
            help=
            'JSON formatted string or a path to a file or uri with parameter definitions.',
            type=file_type,
            completer=FilesCompleter(),
            min_api='2016-12-01')
        c.argument('metadata',
                   min_api='2017-06-01-preview',
                   nargs='+',
                   validator=validate_metadata,
                   help='Metadata in space-separated key=value pairs.')
        c.argument('management_group', arg_type=management_group_name_type)
        c.argument(
            'mode',
            options_list=['--mode', '-m'],
            help=
            'Mode of the policy definition, e.g. All, Indexed. Please visit https://aka.ms/azure-policy-mode for more information.',
            min_api='2016-12-01')
        c.argument('subscription', arg_type=subscription_type)
        c.ignore('_subscription')  # disable global subscription

    with self.argument_context(
            'policy definition create',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='Name of the new policy definition.')

    with self.argument_context(
            'policy assignment',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.ignore('_subscription')
        c.argument('name',
                   options_list=['--name', '-n'],
                   completer=get_policy_assignment_completion_list,
                   help='Name of the policy assignment.')
        c.argument('scope',
                   help='Scope to which this policy assignment applies.')
        c.argument(
            'disable_scope_strict_match',
            action='store_true',
            help=
            'Include policy assignments either inherited from parent scope or at child scope.'
        )
        c.argument('display_name',
                   help='Display name of the policy assignment.')
        c.argument('policy',
                   help='Name or id of the policy definition.',
                   completer=get_policy_completion_list)

    with self.argument_context(
            'policy assignment create',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='Name of the new policy assignment.')
        c.argument(
            'params',
            options_list=['--params', '-p'],
            help=
            'JSON formatted string or a path to a file or uri with parameter values of the policy rule.',
            type=file_type,
            completer=FilesCompleter(),
            min_api='2016-12-01')

    with self.argument_context('policy assignment create',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               min_api='2017-06-01-preview') as c:
        c.argument('policy_set_definition',
                   options_list=['--policy-set-definition', '-d'],
                   help='Name or id of the policy set definition.')
        c.argument('sku',
                   options_list=['--sku', '-s'],
                   help='policy sku.',
                   arg_type=get_enum_type(['free', 'standard']))
        c.argument('notscopes', options_list='--not-scopes', nargs='+')

    with self.argument_context('policy assignment create',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               min_api='2018-05-01') as c:
        c.argument(
            'location',
            arg_type=get_location_type(self.cli_ctx),
            help=
            'The location of the policy assignment. Only required when utilizing managed identity.'
        )

    with self.argument_context('policy assignment create',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               arg_group='Managed Identity',
                               min_api='2018-05-01') as c:
        c.argument(
            'assign_identity',
            nargs='*',
            validator=validate_msi,
            help="Assigns a system assigned identity to the policy assignment."
        )
        c.argument('identity_scope', arg_type=identity_scope_type)
        c.argument('identity_role', arg_type=identity_role_type)

    with self.argument_context('policy assignment create',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               min_api='2019-06-01') as c:
        c.argument(
            'enforcement_mode',
            options_list=['--enforcement-mode', '-e'],
            help=
            'Enforcement mode of the policy assignment, e.g. Default, DoNotEnforce. Please visit https://aka.ms/azure-policyAssignment-enforcement-mode for more information.',
            arg_type=get_enum_type(['Default', 'DoNotEnforce']))

    with self.argument_context('policy assignment identity',
                               resource_type=ResourceType.MGMT_RESOURCE_POLICY,
                               min_api='2018-05-01') as c:
        c.argument('identity_scope', arg_type=identity_scope_type)
        c.argument('identity_role', arg_type=identity_role_type)

    with self.argument_context(
            'policy set-definition',
            min_api='2017-06-01-preview',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('policy_set_definition_name',
                   arg_type=existing_policy_set_definition_name_type)
        c.argument('display_name',
                   help='Display name of policy set definition.')
        c.argument('description', help='Description of policy set definition.')
        c.argument(
            'params',
            help=
            'JSON formatted string or a path to a file or uri with parameter definitions.',
            type=file_type,
            completer=FilesCompleter())
        c.argument(
            'definitions',
            help=
            'JSON formatted string or a path to a file or uri containing definitions.',
            type=file_type,
            completer=FilesCompleter())
        c.argument(
            'definition_groups',
            min_api='2019-09-01',
            help=
            'JSON formatted string or a path to a file or uri containing policy definition groups. Groups are used to organize policy definitions within a policy set.',
            type=file_type,
            completer=FilesCompleter())
        c.argument('metadata',
                   nargs='+',
                   validator=validate_metadata,
                   help='Metadata in space-separated key=value pairs.')
        c.argument('management_group', arg_type=management_group_name_type)
        c.argument('subscription', arg_type=subscription_type)
        c.ignore('_subscription')  # disable global subscription

    with self.argument_context(
            'policy set-definition create',
            min_api='2017-06-01-preview',
            resource_type=ResourceType.MGMT_RESOURCE_POLICY) as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='Name of the new policy set definition.')

    with self.argument_context('group') as c:
        c.argument('tag', tag_type)
        c.argument('tags', tags_type)
        c.argument('resource_group_name',
                   resource_group_name_type,
                   options_list=['--name', '-n', '--resource-group', '-g'])

    with self.argument_context('group deployment') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   completer=get_resource_group_completion_list)
        c.argument('deployment_name', arg_type=deployment_name_type)
        c.argument('template_file', arg_type=deployment_template_file_type)
        c.argument('template_uri', arg_type=deployment_template_uri_type)
        c.argument(
            'mode',
            arg_type=get_enum_type(DeploymentMode, default='incremental'),
            help=
            'Incremental (only add resources to resource group) or Complete (remove extra resources from resource group)'
        )
        c.argument('parameters', arg_type=deployment_parameters_type)
        c.argument(
            'rollback_on_error',
            nargs='?',
            action=RollbackAction,
            help=
            'The name of a deployment to roll back to on error, or use as a flag to roll back to the last successful deployment.'
        )

    with self.argument_context('group deployment create') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument(
            'aux_subscriptions',
            nargs='+',
            options_list=['--aux-subs'],
            help=
            'Auxiliary subscriptions which will be used during deployment across tenants.',
            deprecate_info=c.deprecate(target='--aux-subs',
                                       redirect='--aux-tenants'))
        c.argument(
            'aux_tenants',
            nargs='+',
            options_list=['--aux-tenants'],
            help=
            'Auxiliary tenants which will be used during deployment across tenants.'
        )
        c.argument('no_prompt', arg_type=no_prompt)

    with self.argument_context('group deployment validate') as c:
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)

    with self.argument_context('group deployment list') as c:
        c.argument('filter_string', arg_type=filter_type)

    with self.argument_context('group deployment operation show') as c:
        c.argument('operation_ids',
                   nargs='+',
                   help='A list of operation ids to show')

    with self.argument_context('deployment') as c:
        c.argument('deployment_name', arg_type=deployment_name_type)
        c.argument('deployment_location',
                   arg_type=get_location_type(self.cli_ctx),
                   required=True)
        c.argument('template_file', arg_type=deployment_template_file_type)
        c.argument('template_uri', arg_type=deployment_template_uri_type)
        c.argument('parameters', arg_type=deployment_parameters_type)

    with self.argument_context('deployment create') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)
        c.argument('confirm_with_what_if',
                   arg_type=deployment_what_if_confirmation_type)
        c.argument('what_if_result_format',
                   options_list=['--what-if-result-format', '-r'],
                   arg_type=deployment_what_if_result_format_type)

    with self.argument_context('deployment validate') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)

    with self.argument_context('deployment operation') as c:
        c.argument('operation_ids',
                   nargs='+',
                   help='A list of operation ids to show')

    with self.argument_context('deployment list') as c:
        c.argument('filter_string', arg_type=filter_type)

    with self.argument_context('deployment sub') as c:
        c.argument('deployment_location',
                   arg_type=get_location_type(self.cli_ctx),
                   required=True)

    with self.argument_context('deployment sub create') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)
        c.argument('confirm_with_what_if',
                   arg_type=deployment_what_if_confirmation_type)
        c.argument('what_if_result_format',
                   options_list=['--what-if-result-format', '-r'],
                   arg_type=deployment_what_if_result_format_type)

    with self.argument_context('deployment sub what-if') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('no_prompt', arg_type=no_prompt)
        c.argument('result_format',
                   arg_type=deployment_what_if_result_format_type)
        c.argument('no_pretty_print',
                   arg_type=deployment_what_if_no_pretty_print_type)

    with self.argument_context('deployment sub validate') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)

    with self.argument_context('deployment sub list') as c:
        c.argument('filter_string', arg_type=filter_type)

    with self.argument_context('deployment group') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   completer=get_resource_group_completion_list,
                   required=True)
        c.argument(
            'mode',
            arg_type=get_enum_type(DeploymentMode, default='incremental'),
            help=
            'Incremental (only add resources to resource group) or Complete (remove extra resources from resource group)'
        )
        c.argument(
            'rollback_on_error',
            nargs='?',
            action=RollbackAction,
            help=
            'The name of a deployment to roll back to on error, or use as a flag to roll back to the last successful deployment.'
        )

    with self.argument_context('deployment group create') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument(
            'aux_subscriptions',
            nargs='+',
            options_list=['--aux-subs'],
            help=
            'Auxiliary subscriptions which will be used during deployment across tenants.',
            deprecate_info=c.deprecate(target='--aux-subs',
                                       redirect='--aux-tenants'))
        c.argument(
            'aux_tenants',
            nargs='+',
            options_list=['--aux-tenants'],
            help=
            'Auxiliary tenants which will be used during deployment across tenants.'
        )
        c.argument('no_prompt', arg_type=no_prompt)
        c.argument('confirm_with_what_if',
                   arg_type=deployment_what_if_confirmation_type)
        c.argument('what_if_result_format',
                   options_list=['--what-if-result-format', '-r'],
                   arg_type=deployment_what_if_result_format_type)

    with self.argument_context('deployment group what-if') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument(
            'aux_tenants',
            nargs='+',
            options_list=['--aux-tenants'],
            help=
            'Auxiliary tenants which will be used during deployment across tenants.'
        )
        c.argument('no_prompt', arg_type=no_prompt)
        c.argument('result_format',
                   arg_type=deployment_what_if_result_format_type)
        c.argument('no_pretty_print',
                   arg_type=deployment_what_if_no_pretty_print_type)
        c.ignore("rollback_on_error")

    with self.argument_context('deployment group validate') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)

    with self.argument_context('deployment group list') as c:
        c.argument('filter_string', arg_type=filter_type)

    with self.argument_context('deployment mg') as c:
        c.argument('management_group_id', arg_type=management_group_id_type)
        c.argument('deployment_location',
                   arg_type=get_location_type(self.cli_ctx),
                   required=True)

    with self.argument_context('deployment mg create') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)

    with self.argument_context('deployment mg validate') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)

    with self.argument_context('deployment mg list') as c:
        c.argument('filter_string', arg_type=filter_type)

    with self.argument_context('deployment operation mg') as c:
        c.argument('management_group_id', arg_type=management_group_id_type)

    with self.argument_context('deployment tenant') as c:
        c.argument('deployment_location',
                   arg_type=get_location_type(self.cli_ctx),
                   required=True)

    with self.argument_context('deployment tenant create') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)

    with self.argument_context('deployment tenant validate') as c:
        c.argument('deployment_name', arg_type=deployment_create_name_type)
        c.argument('handle_extended_json_format',
                   arg_type=extended_json_format_type,
                   deprecate_info=c.deprecate(
                       target='--handle-extended-json-format/-j'))
        c.argument('no_prompt', arg_type=no_prompt)

    with self.argument_context('deployment tenant list') as c:
        c.argument('filter_string', arg_type=filter_type)

    with self.argument_context('group export') as c:
        c.argument('include_comments', action='store_true')
        c.argument('include_parameter_default_value', action='store_true')

    with self.argument_context('group create') as c:
        c.argument('rg_name',
                   options_list=['--name', '--resource-group', '-n', '-g'],
                   help='name of the new resource group',
                   completer=None,
                   local_context_attribute=LocalContextAttribute(
                       name='resource_group_name',
                       actions=[LocalContextAction.SET],
                       scopes=[ALL]))
        c.argument(
            'managed_by',
            min_api='2016-09-01',
            help='The ID of the resource that manages this resource group.')

    with self.argument_context('group delete') as c:
        c.argument('resource_group_name',
                   resource_group_name_type,
                   options_list=['--name', '-n', '--resource-group', '-g'],
                   local_context_attribute=None)

    with self.argument_context('tag') as c:
        c.argument('tag_name', options_list=['--name', '-n'])
        c.argument('tag_value', options_list='--value')

    with self.argument_context('lock') as c:
        c.argument('lock_name',
                   options_list=['--name', '-n'],
                   validator=validate_lock_parameters)
        c.argument('level',
                   arg_type=get_enum_type(LockLevel),
                   options_list=['--lock-type', '-t'],
                   help='The type of lock restriction.')
        c.argument('parent_resource_path', resource_parent_type)
        c.argument('resource_provider_namespace', resource_namespace_type)
        c.argument('resource_type',
                   arg_type=resource_type_type,
                   completer=get_resource_types_completion_list)
        c.argument(
            'resource_name',
            options_list=['--resource', '--resource-name'],
            help=
            'Name or ID of the resource being locked. If an ID is given, other resource arguments should not be given.'
        )
        c.argument(
            'ids',
            nargs='+',
            options_list='--ids',
            help=
            'One or more resource IDs (space-delimited). If provided, no other "Resource Id" arguments should be specified.'
        )
        c.argument('resource_group',
                   resource_group_name_type,
                   validator=validate_lock_parameters)

    with self.argument_context('resource lock') as c:
        c.argument('resource_group', resource_group_name_type)
        c.argument(
            'resource_name',
            options_list=['--resource', '--resource-name'],
            help=
            'If an ID is given, other resource arguments should not be given.',
            validator=validate_resource_lock)

    with self.argument_context('group lock') as c:
        c.argument('resource_group',
                   resource_group_name_type,
                   validator=validate_group_lock,
                   id_part=None)

    with self.argument_context('group lock create') as c:
        c.argument('resource_group', required=True)

    with self.argument_context('account lock') as c:
        c.argument('resource_group',
                   ignore_type,
                   validator=validate_subscription_lock)

    for scope in ['account', 'group']:
        with self.argument_context('{} lock'.format(scope)) as c:
            c.ignore('resource_provider_namespace', 'parent_resource_path',
                     'resource_type', 'resource_name')

    for scope in ['lock', 'account lock', 'group lock', 'resource lock']:
        with self.argument_context(scope) as c:
            c.argument('lock_name',
                       options_list=['--name', '-n'],
                       help='Name of the lock')
            c.argument('level',
                       options_list=['--lock-type', '-t'],
                       arg_type=get_enum_type(
                           [LockLevel.can_not_delete, LockLevel.read_only]),
                       help='The type of lock restriction.')
            c.argument(
                'ids',
                nargs='+',
                options_list='--ids',
                help=
                'One or more resource IDs (space-delimited). If provided, no other "Resource Id" arguments should be specified.'
            )
            c.argument('notes', help='Notes about this lock.')

    with self.argument_context('managedapp') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   help='the resource group of the managed application',
                   id_part='resource_group')
        c.argument('application_name',
                   options_list=['--name', '-n'],
                   id_part='name')

    with self.argument_context('managedapp definition') as c:
        c.argument(
            'resource_group_name',
            arg_type=resource_group_name_type,
            help='the resource group of the managed application definition',
            id_part='resource_group')
        c.argument('application_definition_name',
                   options_list=['--name', '-n'],
                   id_part='name')

    with self.argument_context('managedapp create') as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='name of the new managed application',
                   completer=None)
        c.argument('location', help='the managed application location')
        c.argument('managedapp_definition_id',
                   options_list=['--managedapp-definition-id', '-d'],
                   help='the full qualified managed application definition id')
        c.argument(
            'managedby_resource_group_id',
            options_list=['--managed-rg-id', '-m'],
            help='the resource group managed by the managed application')
        c.argument(
            'parameters',
            help='JSON formatted string or a path to a file with such content',
            type=file_type)

    with self.argument_context('managedapp definition create') as c:
        c.argument('lock_level',
                   arg_type=get_enum_type(ApplicationLockLevel),
                   help='The type of lock restriction.')
        c.argument(
            'authorizations',
            options_list=['--authorizations', '-a'],
            nargs='+',
            help=
            "space-separated authorization pairs in a format of `<principalId>:<roleDefinitionId>`"
        )
        c.argument(
            'createUiDefinition',
            options_list=['--create-ui-definition', '-c'],
            help='JSON formatted string or a path to a file with such content',
            type=file_type)
        c.argument(
            'mainTemplate',
            options_list=['--main-template', '-t'],
            help='JSON formatted string or a path to a file with such content',
            type=file_type)

    with self.argument_context('account') as c:
        c.argument('subscription',
                   options_list=['--subscription', '-s'],
                   help='Name or ID of subscription.',
                   completer=get_subscription_id_list)
        c.ignore('_subscription')  # hide global subscription parameter

    with self.argument_context('account management-group') as c:
        c.argument('group_name', options_list=['--name', '-n'])

    with self.argument_context('account management-group show') as c:
        c.argument('expand',
                   options_list=['--expand', '-e'],
                   action='store_true')
        c.argument('recurse',
                   options_list=['--recurse', '-r'],
                   action='store_true')

    with self.argument_context('account management-group create') as c:
        c.argument('display_name', options_list=['--display-name', '-d'])
        c.argument('parent', options_list=['--parent', '-p'])

    with self.argument_context('account management-group update') as c:
        c.argument('display_name', options_list=['--display-name', '-d'])
        c.argument('parent_id', options_list=['--parent', '-p'])

    with self.argument_context('rest') as c:
        c.argument(
            'method',
            options_list=['--method', '-m'],
            arg_type=get_enum_type(
                ['head', 'get', 'put', 'post', 'delete', 'options', 'patch'],
                default='get'),
            help='HTTP request method')
        c.argument(
            'uri',
            options_list=['--url', '--uri', '-u'],
            help='Request URL. If it doesn\'t start with a host, '
            'CLI assumes it as an Azure resource ID and prefixes it with the ARM endpoint of the current '
            'cloud shown by `az cloud show --query endpoints.resourceManager`. Common token {subscriptionId} '
            'will be replaced with the current subscription ID specified by `az account set`'
        )
        c.argument(
            'headers',
            nargs='+',
            help=
            "Space-separated headers in KEY=VALUE format or JSON string. Use @{file} to load from a file"
        )
        c.argument(
            'uri_parameters',
            nargs='+',
            help=
            'Space-separated queries in KEY=VALUE format or JSON string. Use @{file} to load from a file'
        )
        c.argument('skip_authorization_header',
                   action='store_true',
                   help='Do not auto-append Authorization header')
        c.argument(
            'body',
            options_list=['--body', '-b'],
            help=
            'Request body. Use @{file} to load from a file. For quoting issues in different terminals, see https://github.com/Azure/azure-cli/blob/dev/doc/use_cli_effectively.md#quoting-issues'
        )
        c.argument('output_file', help='save response payload to a file')
        c.argument(
            'resource',
            help=
            'Resource url for which CLI should acquire a token from AAD in order to access '
            'the service. The token will be placed in the Authorization header. By default, '
            'CLI can figure this out based on --url argument, unless you use ones not in the list '
            'of "az cloud show --query endpoints"')
Exemplo n.º 24
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],
            help=
            'Number of message units. This property is only applicable to namespaces of Premium SKU',
            validator=validate_premiumsku_capacity)

    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('rights', arg_type=rights_arg_type)

    with self.argument_context(
            'servicebus namespace 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(
            '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', 'ReceiveDisabled']),
                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('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', 'ReceiveDisabled']),
                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('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
    # 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(
            'name',
            options_list=['--alias', '-a'],
            arg_type=name_type,
            help=
            'Name of Geo-Disaster Recovery Configuration Alias to check availability'
        )
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')

    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(
            '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.argument(
            'namespace_name',
            arg_type=name_type,
            help='Name of Standard Namespace used as source of the migration')
        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.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')
Exemplo n.º 25
0
    def load_arguments(self, _):
        # pylint: disable=line-too-long
        # PARAMETER REGISTRATION
        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 webapp. You can configure the default using 'az configure --defaults web=<name>'"
        )

        with self.argument_context('webapp container up') as c:
            c.argument('name', arg_type=webapp_name_arg_type)
            c.argument('source_location',
                       options_list=['--source-location', '-s'],
                       help='the path to the web app source directory')
            c.argument(
                'docker_custom_image_name',
                options_list=['--docker-custom-image-name', '-i'],
                help=
                'the container image name and optionally the tag name (currently public DockerHub images only)'
            )
            c.argument(
                'dryrun',
                help=
                "show summary of the create and deploy operation instead of executing it",
                default=False,
                action='store_true')
            c.argument(
                'registry_rg',
                help="the resource group of the Azure Container Registry")
            c.argument('registry_name',
                       help="the name of the Azure Container Registry")
            c.argument('slot', help="Name of the deployment slot to use")
        with self.argument_context('webapp remote-connection create') as c:
            c.argument(
                'port',
                options_list=['--port', '-p'],
                help=
                'Port for the remote connection. Default: Random available port',
                type=int)
            c.argument('name',
                       options_list=['--name', '-n'],
                       help='Name of the webapp to connect to')
            c.argument('slot', help="Name of the deployment slot to use")
        with self.argument_context('webapp scan') as c:
            c.argument('name',
                       options_list=['--name', '-n'],
                       help='Name of the webapp to connect to')
            c.argument('scan_id',
                       options_list=['--scan-id'],
                       help='Unique scan id')
            c.argument('timeout',
                       options_list=['--timeout'],
                       help='Timeout for operation in milliseconds')
            c.argument('slot', help="Name of the deployment slot to use")

        with self.argument_context('webapp deploy') as c:
            c.argument('name',
                       options_list=['--name'],
                       help='Name of the webapp to connect to')
            c.argument(
                'src_path',
                options_list=['--src-path'],
                help=
                'Path of the file to be deployed. Example: /mnt/apps/myapp.war'
            )
            c.argument(
                'src_url',
                options_list=['--src-url'],
                help=
                'url to download the package from. Example: http://mysite.com/files/myapp.war?key=123'
            )
            c.argument('type',
                       options_list=['--type'],
                       help='Type of deployment requested')
            c.argument('async',
                       options_list=['--async'],
                       help='Asynchronous deployment',
                       type=bool)
            c.argument(
                'target_path',
                options_list=['--target-path'],
                help=
                'Target path relative to wwwroot to which the file will be deployed to.'
            )
            c.argument('restart',
                       options_list=['--restart'],
                       help='restart or not. default behavior is to restart.',
                       type=bool)
            c.argument('clean',
                       options_list=['--clean'],
                       help='clean or not. default is target-type specific.',
                       type=bool)
            c.argument('ignore_stack',
                       options_list=['--ignore-stack'],
                       help='should override the default stack check',
                       type=bool)
            c.argument('timeout',
                       options_list=['--timeout'],
                       help='Timeout for operation in milliseconds')
            c.argument('slot', help="Name of the deployment slot to use")
Exemplo n.º 26
0
    get_enum_type)
from azure.cli.core.commands.validators import get_default_location_from_resource_group
from .policy import RetentionType

from ._constants import (REGISTRY_RESOURCE_TYPE, WEBHOOK_RESOURCE_TYPE,
                         REPLICATION_RESOURCE_TYPE, TASK_RESOURCE_TYPE,
                         TASKRUN_RESOURCE_TYPE)
from ._validators import (validate_headers, validate_arg, validate_secret_arg,
                          validate_set, validate_set_secret,
                          validate_retention_days, validate_registry_name,
                          validate_expiration_time)
from .scope_map import ScopeMapActions

image_by_tag_or_digest_type = CLIArgumentType(
    options_list=['--image', '-t'],
    help=
    "The name of the image. May include a tag in the format 'name:tag' or digest in the format 'name@digest'."
)


def load_arguments(self, _):  # pylint: disable=too-many-statements
    SkuName, PasswordName, DefaultAction, PolicyStatus, WebhookAction, WebhookStatus, TaskStatus, \
        BaseImageTriggerType, RunStatus, SourceRegistryLoginMode, UpdateTriggerPayloadType, TokenStatus = self.get_models(
            'SkuName', 'PasswordName', 'DefaultAction', 'PolicyStatus', 'WebhookAction', 'WebhookStatus',
            'TaskStatus', 'BaseImageTriggerType', 'RunStatus', 'SourceRegistryLoginMode', 'UpdateTriggerPayloadType',
            'TokenStatus')

    with self.argument_context('acr') as c:
        c.argument('tags', arg_type=tags_type)
        c.argument(
            'registry_name',
Exemplo n.º 27
0
def load_arguments(self, _):

    (IpsecEncryption, IpsecIntegrity, IkeEncryption, IkeIntegrity, DhGroup,
     PfsGroup, VirtualNetworkGatewayConnectionProtocol) = self.get_models(
         'IpsecEncryption', 'IpsecIntegrity', 'IkeEncryption', 'IkeIntegrity',
         'DhGroup', 'PfsGroup', 'VirtualNetworkGatewayConnectionProtocol')

    (VpnGatewayTunnelingProtocol,
     VpnAuthenticationType) = self.get_models('VpnGatewayTunnelingProtocol',
                                              'VpnAuthenticationType')

    # region VirtualWAN
    vwan_name_type = CLIArgumentType(
        options_list='--vwan-name',
        metavar='NAME',
        help='Name of the virtual WAN.',
        id_part='name',
        completer=get_resource_name_completion_list(
            'Microsoft.Network/virtualWANs'))
    vhub_name_type = CLIArgumentType(
        options_list='--vhub-name',
        metavar='NAME',
        help='Name of the virtual hub.',
        id_part='name',
        completer=get_resource_name_completion_list(
            'Microsoft.Network/networkHubs'))
    vpn_gateway_name_type = CLIArgumentType(
        options_list='--gateway-name',
        metavar='NAME',
        help='Name of the VPN gateway.',
        id_part='name',
        completer=get_resource_name_completion_list(
            'Microsoft.Network/vpnGateways'))
    vpn_site_name_type = CLIArgumentType(
        options_list='--site-name',
        metavar='NAME',
        help='Name of the VPN site config.',
        id_part='name',
        completer=get_resource_name_completion_list(
            'Microsoft.Network/vpnSites'))
    p2s_vpn_gateway_name_type = CLIArgumentType(
        options_list='--gateway-name',
        metavar='NAME',
        help='Name of the P2S VPN gateway.',
        id_part='name',
        completer=get_resource_name_completion_list(
            'Microsoft.Network/p2svpnGateways'))
    associated_route_table_type = CLIArgumentType(
        options_list=['--associated', '--associated-route-table'],
        help=
        'The resource id of route table associated with this routing configuration.'
    )
    propagated_route_tables_type = CLIArgumentType(
        options_list=['--propagated', '--propagated-route-tables'],
        nargs='+',
        help='Space-separated list of resource id of propagated route tables.')
    propagated_route_tables_label_type = CLIArgumentType(
        nargs='+',
        help='Space-separated list of labels for propagated route tables.')

    with self.argument_context('network') as c:
        c.argument('tags', tags_type)

    with self.argument_context('network vwan') as c:
        c.argument('virtual_wan_name',
                   vwan_name_type,
                   options_list=['--name', '-n'])
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('branch_to_branch_traffic',
                   arg_type=get_three_state_flag(),
                   help='Allow branch-to-branch traffic flow.')
        c.argument('vnet_to_vnet_traffic',
                   arg_type=get_three_state_flag(),
                   help='Allow VNet-to-VNet traffic flow.')
        c.argument('security_provider_name',
                   help='The security provider name.')
        c.argument('office365_category',
                   help='The office local breakout category.')
        c.argument('disable_vpn_encryption',
                   arg_type=get_three_state_flag(),
                   help='State of VPN encryption.')
        c.argument('vwan_type',
                   options_list='--type',
                   arg_type=get_enum_type(['Basic', 'Standard']),
                   help='The type of the VirtualWAN.')
    # endregion

    # region VirtualHub
    with self.argument_context('network vhub') as c:
        c.argument('virtual_hub_name',
                   vhub_name_type,
                   options_list=['--name', '-n'])
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('virtual_wan',
                   options_list='--vwan',
                   help='Name or ID of the virtual WAN.',
                   validator=get_network_resource_name_or_id(
                       'virtual_wan', 'virtualWans'))
        c.argument('address_prefix',
                   help='CIDR address prefix for the virtual hub.')
        c.argument('sku',
                   arg_type=get_enum_type(['Basic', 'Standard']),
                   help='The sku of the VirtualHub.')

    with self.argument_context('network vhub', arg_group='Gateway') as c:
        c.argument('express_route_gateway',
                   help='Name or ID of an ExpressRoute gateway.',
                   validator=get_network_resource_name_or_id(
                       'express_route_gateway', 'expressRouteGateways'))
        c.argument('p2s_vpn_gateway',
                   help='Name or ID of a P2S VPN gateway.',
                   validator=get_network_resource_name_or_id(
                       'p2s_vpn_gateway', 'P2sVpnGateways'))
        c.argument('vpn_gateway',
                   help='Name or ID of a VPN gateway.',
                   validator=get_network_resource_name_or_id(
                       'vpn_gateway', 'vpnGateways'))

    with self.argument_context('network vhub get-effective-routes') as c:
        c.argument('virtual_wan_resource_type', options_list='--resource-type')

    with self.argument_context('network vhub connection') as c:
        c.argument('virtual_hub_name', vhub_name_type)
        c.argument('connection_name',
                   help='Name of the connection.',
                   options_list=['--name', '-n'],
                   id_part='child_name_1')
        c.argument('remote_virtual_network',
                   options_list='--remote-vnet',
                   help='Name of ID of the remote VNet to connect to.',
                   validator=get_network_resource_name_or_id(
                       'remote_virtual_network', 'virtualNetworks'))
        c.argument('allow_hub_to_remote_vnet_transit',
                   arg_type=get_three_state_flag(),
                   options_list='--remote-vnet-transit',
                   deprecate_info=c.deprecate(target='--remote-vnet-transit'),
                   help='Enable hub to remote VNet transit.')
        c.argument(
            'allow_remote_vnet_to_use_hub_vnet_gateways',
            arg_type=get_three_state_flag(),
            options_list='--use-hub-vnet-gateways',
            deprecate_info=c.deprecate(target='--use-hub-vnet-gateways'),
            help='Allow remote VNet to use hub\'s VNet gateways.')
        c.argument('enable_internet_security',
                   arg_type=get_three_state_flag(),
                   options_list='--internet-security',
                   help='Enable internet security and default is enabled.',
                   default=True)

    with self.argument_context('network vhub connection list') as c:
        c.argument('virtual_hub_name', vhub_name_type, id_part=None)

    with self.argument_context('network vhub connection',
                               arg_group='RoutingConfiguration',
                               min_api='2020-04-01',
                               is_preview=True) as c:
        c.argument('address_prefixes',
                   nargs='+',
                   help='Space-separated list of all address prefixes.')
        c.argument('next_hop_ip_address',
                   options_list='--next-hop',
                   help='The ip address of the next hop.')
        c.argument(
            'route_name',
            help=
            'The name of the Static Route that is unique within a Vnet Route.')

    with self.argument_context('network vhub route') as c:
        c.argument('virtual_hub_name', vhub_name_type, id_part=None)
        c.argument('address_prefixes',
                   nargs='+',
                   help='Space-separated list of CIDR prefixes.')
        c.argument('next_hop_ip_address',
                   options_list='--next-hop',
                   help='IP address of the next hop.')
        c.argument('index',
                   type=int,
                   help='List index of the item (starting with 1).')

    with self.argument_context('network vhub route-table') as c:
        c.argument('virtual_hub_name', vhub_name_type, id_part=None)
        c.argument('route_table_name',
                   options_list=['--name', '-n'],
                   help='Name of the virtual hub route table.')
        c.argument('attached_connections',
                   options_list='--connections',
                   nargs='+',
                   arg_type=get_enum_type(['All_Vnets', 'All_Branches']),
                   help='List of all connections attached to this route table',
                   arg_group="route table v2")
        c.argument('destination_type',
                   arg_type=get_enum_type(['Service', 'CIDR', 'ResourceId']),
                   help='The type of destinations')
        c.argument('destinations',
                   nargs='+',
                   help='Space-separated list of all destinations.')
        c.argument(
            'next_hop_type',
            arg_type=get_enum_type(['IPAddress', 'ResourceId']),
            help=
            'The type of next hop. If --next-hops (v2) is provided, it should be IPAddress; if --next-hop (v3) is provided, it should be ResourceId.'
        )
        c.argument(
            'next_hops',
            nargs='+',
            help=
            'Space-separated list of IP address of the next hop. Currently only one next hop is allowed for every route.',
            arg_group="route table v2")
        c.argument('index',
                   type=int,
                   help='List index of the item (starting with 1).')
        c.argument('next_hop',
                   help='The resource ID of the next hop.',
                   arg_group="route table v3",
                   min_api='2020-04-01')
        c.argument('route_name',
                   help='The name of the route.',
                   arg_group="route table v3",
                   min_api='2020-04-01')
        c.argument(
            'labels',
            nargs='+',
            help=
            'Space-separated list of all labels associated with this route table.',
            arg_group="route table v3",
            min_api='2020-04-01')
    # endregion

    # region VpnGateways
    with self.argument_context('network vpn-gateway') as c:
        c.argument('virtual_hub',
                   options_list='--vhub',
                   help='Name or ID of a virtual hub.',
                   validator=get_network_resource_name_or_id(
                       'virtual_hub', 'virtualHubs'))
        c.argument('scale_unit',
                   type=int,
                   help='The scale unit for this VPN gateway.')
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('gateway_name',
                   vpn_gateway_name_type,
                   options_list=['--name', '-n'])

    with self.argument_context('network vpn-gateway connection') as c:
        for dest in ['gateway_name', 'resource_name']:
            c.argument(dest, vpn_gateway_name_type)
        for dest in ['item_name', 'connection_name']:
            c.argument(dest,
                       help='Name of the VPN gateway connection.',
                       options_list=['--name', '-n'],
                       id_part='child_name_1')
        c.argument('remote_vpn_site',
                   help='Name of ID of the remote VPN site.',
                   validator=get_network_resource_name_or_id(
                       'remote_vpn_site', 'vpnSites'))
        c.argument('connection_bandwidth',
                   help='Expected bandwidth in Mbps.',
                   type=int)
        c.argument('enable_bgp',
                   arg_type=get_three_state_flag(),
                   help='Enable BGP.')
        c.argument('enable_internet_security',
                   options_list='--internet-security',
                   arg_type=get_three_state_flag(),
                   help='Enable internet security.')
        c.argument('enable_rate_limiting',
                   options_list='--rate-limiting',
                   arg_type=get_three_state_flag(),
                   help='Enable rate limiting.')
        c.argument(
            'protocol_type',
            arg_type=get_enum_type(VirtualNetworkGatewayConnectionProtocol),
            help='Connection protocol.')
        c.argument('routing_weight', type=int, help='Routing weight.')
        c.argument('shared_key', help='Shared key.')

    with self.argument_context('network vpn-gateway connection list') as c:
        c.argument('resource_name', vpn_gateway_name_type, id_part=None)

    with self.argument_context('network vpn-gateway connection',
                               arg_group='IP Security') as c:
        c.argument(
            'sa_life_time_seconds',
            options_list='--sa-lifetime',
            help=
            'IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for a site-to-site VPN tunnel.',
            type=int)
        c.argument(
            'sa_data_size_kilobytes',
            options_list='--sa-data-size',
            help=
            'IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for a site-to-site VPN tunnel.',
            type=int)
        c.argument('ipsec_encryption',
                   arg_type=get_enum_type(IpsecEncryption),
                   help='IPSec encryption algorithm (IKE phase 1).')
        c.argument('ipsec_integrity',
                   arg_type=get_enum_type(IpsecIntegrity),
                   help='IPSec integrity algorithm (IKE phase 1).')
        c.argument('ike_encryption',
                   arg_type=get_enum_type(IkeEncryption),
                   help='IKE encryption algorithm (IKE phase 2).')
        c.argument('ike_integrity',
                   arg_type=get_enum_type(IkeIntegrity),
                   help='IKE integrity algorithm (IKE phase 2).')
        c.argument('dh_group',
                   arg_type=get_enum_type(DhGroup),
                   help='DH Groups used in IKE Phase 1 for initial SA.')
        c.argument('pfs_group',
                   arg_type=get_enum_type(PfsGroup),
                   help='The Pfs Groups used in IKE Phase 2 for new child SA.')

    with self.argument_context(
            'network vpn-gateway connection ipsec-policy') as c:
        c.argument('gateway_name', vpn_gateway_name_type, id_part=None)
        c.argument('connection_name',
                   options_list='--connection-name',
                   help='Name of the VPN gateway connection.')
        c.argument('index',
                   type=int,
                   help='List index of the item (starting with 1).')
    # endregion

    # region VpnSites
    with self.argument_context('network vpn-site') as c:
        c.argument('vpn_site_name',
                   vpn_site_name_type,
                   options_list=['--name', '-n'])
        c.argument('virtual_wan',
                   help='Name or ID of the virtual WAN.',
                   validator=get_network_resource_name_or_id(
                       'virtual_wan', 'virtualWans'))
        c.argument('is_security_site',
                   arg_type=get_three_state_flag(),
                   options_list='--security-site',
                   help='Whether the VPN site is security-related.')
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('ip_address', help='IP address of the VPN site.')
        c.argument(
            'site_key',
            help='Key for the VPN site that can be used for connections.')
        c.argument('address_prefixes',
                   nargs='+',
                   help='Space-separated list of CIDR address prefixes.')

    with self.argument_context('network vpn-site',
                               arg_group='Device Property') as c:
        c.argument('device_model', help='Model of the device.')
        c.argument('device_vendor', help='Name of the device vendor.')
        c.argument('link_speed', help='Link speed in Mbps.', type=int)

    for scope in ['vpn-site', 'vpn-gateway']:
        with self.argument_context('network {}'.format(scope),
                                   arg_group='BGP Peering') as c:
            c.argument('asn', help='BGP speaker\'s ASN.', type=int)
            c.argument(
                'peer_weight',
                help='Weight added to routes learned from this BGP speaker.',
                type=int)
            c.argument(
                'bgp_peering_address',
                help='Peering address and BGP identifier of this BGP speaker.')

    with self.argument_context('network vpn-site download') as c:
        c.argument('virtual_wan_name', vwan_name_type, id_part=None)
        c.argument('vpn_sites',
                   help='Space-separated list of VPN site names or IDs.',
                   nargs='+',
                   validator=get_network_resource_name_or_id(
                       'vpn_sites', 'vpnSites'))
    # endregion

    # region VpnServerConfigurations
    with self.argument_context('network vpn-server-config') as c:
        c.argument('vpn_protocols',
                   nargs='+',
                   options_list=['--protocols'],
                   arg_type=get_enum_type(VpnGatewayTunnelingProtocol),
                   help='VPN protocols for the VpnServerConfiguration.')
        c.argument(
            'vpn_auth_types',
            nargs='+',
            options_list=['--auth-types'],
            arg_type=get_enum_type(VpnAuthenticationType),
            help='VPN authentication types for the VpnServerConfiguration.')
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('vpn_server_configuration_name',
                   options_list=['--name', '-n'],
                   help='Name of the Vpn server configuration.')
    with self.argument_context('network vpn-server-config',
                               arg_group='AAD Auth') as c:
        c.argument('aad_tenant',
                   help='AAD Vpn authentication parameter AAD tenant.')
        c.argument('aad_audience',
                   help='AAD Vpn authentication parameter AAD audience.')
        c.argument('aad_issuer',
                   help='AAD Vpn authentication parameter AAD issuer.')
    with self.argument_context('network vpn-server-config',
                               arg_group='Certificate Auth') as c:
        c.argument('vpn_client_root_certs',
                   help='List of VPN client root certificate file paths.',
                   nargs='+')
        c.argument('vpn_client_revoked_certs',
                   help='List of VPN client revoked certificate file paths.',
                   nargs='+')
    with self.argument_context('network vpn-server-config',
                               arg_group='Radius Auth') as c:
        c.argument('radius_client_root_certs',
                   help='List of Radius client root certificate file paths.',
                   nargs='+')
        c.argument('radius_server_root_certs',
                   help='List of Radius server root certificate file paths.',
                   nargs='+')
        c.argument('radius_servers',
                   nargs='+',
                   action=RadiusServerAddAction,
                   help='Radius Server configuration.')

    with self.argument_context('network vpn-server-config',
                               arg_group='IP Security') as c:
        c.argument(
            'sa_life_time_seconds',
            options_list='--sa-lifetime',
            help=
            'IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for a site-to-site VPN tunnel.',
            type=int)
        c.argument(
            'sa_data_size_kilobytes',
            options_list='--sa-data-size',
            help=
            'IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for a site-to-site VPN tunnel.',
            type=int)
        c.argument('ipsec_encryption',
                   arg_type=get_enum_type(IpsecEncryption),
                   help='IPSec encryption algorithm (IKE phase 1).')
        c.argument('ipsec_integrity',
                   arg_type=get_enum_type(IpsecIntegrity),
                   help='IPSec integrity algorithm (IKE phase 1).')
        c.argument('ike_encryption',
                   arg_type=get_enum_type(IkeEncryption),
                   help='IKE encryption algorithm (IKE phase 2).')
        c.argument('ike_integrity',
                   arg_type=get_enum_type(IkeIntegrity),
                   help='IKE integrity algorithm (IKE phase 2).')
        c.argument('dh_group',
                   arg_type=get_enum_type(DhGroup),
                   help='DH Groups used in IKE Phase 1 for initial SA.')
        c.argument('pfs_group',
                   arg_type=get_enum_type(PfsGroup),
                   help='The Pfs Groups used in IKE Phase 2 for new child SA.')
        c.argument('index',
                   type=int,
                   help='List index of the ipsec policy(starting with 0).')
    # endregion

    # region P2SVpnGateways
    with self.argument_context('network p2s-vpn-gateway') as c:
        c.argument(
            'address_space',
            nargs='+',
            help=
            'Address space for P2S VpnClient. Space-separated list of IP address ranges.'
        )
        c.argument('p2s_conn_config_name',
                   options_list=['--config-name'],
                   help='Name or p2s connection configuration.')
        c.argument('scale_unit',
                   type=int,
                   help='The scale unit for this VPN gateway.')
        c.argument('gateway_name',
                   options_list=['--name', '-n'],
                   help='Name of the P2S Vpn Gateway.')
        c.argument('virtual_hub',
                   options_list='--vhub',
                   help='Name or ID of a virtual hub.',
                   validator=get_network_resource_name_or_id(
                       'virtual_hub', 'virtualHubs'))
        c.argument('vpn_server_config',
                   help='Name or ID of a vpn server configuration.',
                   validator=get_network_resource_name_or_id(
                       'vpn_server_config', 'vpnServerConfigurations'))
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)

    with self.argument_context('network p2s-vpn-gateway connection') as c:
        for dest in ['gateway_name', 'resource_name']:
            c.argument(dest, p2s_vpn_gateway_name_type)
        c.argument('item_name',
                   help='Name of the P2S VPN gateway connection.',
                   options_list=['--name', '-n'],
                   id_part='child_name_1')

    with self.argument_context('network p2s-vpn-gateway connection list') as c:
        c.argument('resource_name', p2s_vpn_gateway_name_type, id_part=None)
    # endregion

    # region Routing Configuration
    for item in [
            'vpn-gateway connection', 'p2s-vpn-gateway', 'vhub connection'
    ]:
        with self.argument_context('network {}'.format(item),
                                   arg_group='Routing Configuration',
                                   min_api='2020-04-01',
                                   is_preview=True) as c:
            c.argument('associated_route_table', associated_route_table_type)
            c.argument('propagated_route_tables', propagated_route_tables_type)
            c.argument('labels', propagated_route_tables_label_type)
Exemplo n.º 28
0
from knack.arguments import CLIArgumentType

from azure.cli.core.commands.parameters import (
    resource_group_name_type, get_resource_name_completion_list,
    get_three_state_flag, get_location_type, get_enum_type, tags_type,
    name_type)

from .advanced_filter import EventSubscriptionAddFilter
from .event_channel_filter import EventChannelAddFilter
from .inbound_ip_rules import AddInboundIpRule
from .delivery_attribute_mapping import AddDeliveryAttributeMapping
from .user_assigned import AddUserAssignedIdentities

included_event_types_type = CLIArgumentType(
    help=
    "A space-separated list of event types (e.g., Microsoft.Storage.BlobCreated and Microsoft.Storage.BlobDeleted). In order to subscribe to all default event types, do not specify any value for this argument. For event grid topics, event types are customer defined. For Azure events, e.g., Storage Accounts, IoT Hub, etc., you can query their event types using this CLI command 'az eventgrid topic-type list-event-types'.",
    nargs='+')

labels_type = CLIArgumentType(
    help=
    "A space-separated list of labels to associate with this event subscription.",
    nargs='+')

authorized_subscription_ids_type = CLIArgumentType(
    help=
    "A space-separated list of Azure subscription Ids that are authorized to create a partner namespace associated with this partner registration. This is an optional property. Creating partner namespaces is always permitted under the same Azure subscription as the one used for creating the partner registration.",
    nargs='+')

input_schema_type = CLIArgumentType(
    help=
    "Schema in which incoming events will be published to this topic/domain. If you specify customeventschema as the value for this parameter, you must also provide values for at least one of --input_mapping_default_values / --input_mapping_fields.",
Exemplo n.º 29
0
def load_arguments(self, _):

    name_arg_type = CLIArgumentType(options_list=('--name', '-n'), metavar='NAME')
    profile_name_help = 'Name of the CDN profile which is unique within the resource group.'

    with self.argument_context('cdn') as c:
        c.argument('name', name_arg_type, id_part='name')
        c.argument('tags', tags_type)

    # Profile #
    with self.argument_context('cdn profile') as c:
        c.argument('profile_name', name_arg_type, id_part='name', help=profile_name_help)

    with self.argument_context('cdn profile create') as c:
        c.argument('sku', arg_type=get_enum_type([item.value for item in list(SkuName)]))
        c.argument('location', validator=get_default_location_from_resource_group)
        c.argument('name', name_arg_type, id_part='name', help=profile_name_help)

    # Endpoint #

    with self.argument_context('cdn endpoint') as c:
        c.argument('endpoint_name', name_arg_type, id_part='name', help='Name of the CDN endpoint.')
        c.argument('location', validator=get_default_location_from_resource_group)
        c.argument('origins', options_list='--origin', nargs='+', action=OriginType, validator=validate_origin,
                   help='Endpoint origin specified by the following space-delimited 3 '
                        'tuple: `www.example.com http_port https_port`. The HTTP and HTTPs'
                        'ports are optional and will default to 80 and 443 respectively.')
        c.argument('is_http_allowed', arg_type=get_three_state_flag(invert=True), options_list='--no-http',
                   help='Indicates whether HTTP traffic is not allowed on the endpoint. '
                   'Default is to allow HTTP traffic.')
        c.argument('is_https_allowed', arg_type=get_three_state_flag(invert=True), options_list='--no-https',
                   help='Indicates whether HTTPS traffic is not allowed on the endpoint. '
                   'Default is to allow HTTPS traffic.')
        c.argument('is_compression_enabled', arg_type=get_three_state_flag(), options_list='--enable-compression',
                   help='If compression is enabled, content will be served as compressed if '
                        'user requests for a compressed version. Content won\'t be compressed '
                        'on CDN when requested content is smaller than 1 byte or larger than 1 '
                        'MB.')

        caching_behavior = [item.value for item in list(QueryStringCachingBehavior)]
        c.argument('query_string_caching_behavior', options_list='--query-string-caching',
                   arg_type=get_enum_type(caching_behavior))
        c.argument('content_types_to_compress', nargs='+')
        c.argument('profile_name', help=profile_name_help)

    with self.argument_context('cdn endpoint create') as c:
        c.argument('name', name_arg_type, id_part='name', help='Name of the CDN endpoint.')

    with self.argument_context('cdn endpoint load') as c:
        c.argument('content_paths', nargs='+')

    with self.argument_context('cdn endpoint purge') as c:
        c.argument('content_paths', nargs='+')

    # Custom Domain #

    with self.argument_context('cdn custom-domain') as c:
        c.argument('custom_domain_name', name_arg_type, id_part=None, help='Name of the custom domain.')

    with self.argument_context('cdn custom-domain create') as c:
        c.argument('location', validator=get_default_location_from_resource_group)

    # Origin #
    with self.argument_context('cdn origin') as c:
        c.argument('origin_name', name_arg_type, id_part='name')
Exemplo n.º 30
0
def load_arguments(self, _):
    resource_name = CLIArgumentType(options_list='--resource-name',
                                    help='Name of the resource.',
                                    id_part='name')

    custom_location = CLIArgumentType(
        options_list=['--custom-location', '-c'],
        help=
        'Name or ID of the custom location that will manage this resource.',
    )

    vcenter = CLIArgumentType(
        options_list=['--vcenter', '-v'],
        help='Name or ID of the vCenter that is managing this resource.',
    )

    mo_ref_id = CLIArgumentType(
        options_list=['--mo-ref-id', '-m'],
        help=
        'VCenter MoRef (Managed Object Reference) ID for the existing resource.',
    )

    inventory_item = CLIArgumentType(
        options_list=['--inventory-item', '-i'],
        help='Name or ID of the inventory item.',
    )

    with self.argument_context('connectedvmware') as c:
        c.argument('tags', tags_type)
        c.argument('location',
                   validator=get_default_location_from_resource_group)
        c.argument('resource_name',
                   resource_name,
                   options_list=['--name', '-n'])
        c.argument('custom_location',
                   custom_location,
                   options_list=['--custom-location', '-c'])
        c.argument('vcenter', vcenter, options_list=['--vcenter', '-v'])
        c.argument('mo_ref_id', mo_ref_id, options_list=['--mo-ref-id', '-m'])
        c.argument('inventory_item',
                   inventory_item,
                   options_list=['--inventory-item', '-i'])

    with self.argument_context('connectedvmware vcenter connect') as c:
        c.argument('fqdn',
                   options_list=['--fqdn'],
                   help="FQDN/IP address of the vCenter.")
        c.argument('port',
                   type=int,
                   options_list=['--port'],
                   help="The port of the vCenter.")
        c.argument(
            'username',
            options_list=['--username'],
            help="Username to use for connecting to the vCenter.",
        )
        c.argument(
            'password',
            options_list=['--password'],
            help=
            "Username password credentials to use for connecting to the vCenter.",
        )

    with self.argument_context('connectedvmware vcenter delete') as c:
        c.argument('force',
                   action='store_true',
                   help="Whether force delete or not.")

    self.argument_context('connectedvmware vcenter inventory-item list')

    self.argument_context('connectedvmware vcenter inventory-item show')

    self.argument_context('connectedvmware resource-pool create')

    with self.argument_context('connectedvmware resource-pool delete') as c:
        c.argument('force',
                   action='store_true',
                   help="Whether force delete or not.")

    self.argument_context('connectedvmware cluster create')

    with self.argument_context('connectedvmware cluster delete') as c:
        c.argument('force',
                   action='store_true',
                   help="Whether force delete or not.")

    self.argument_context('connectedvmware datastore create')

    with self.argument_context('connectedvmware datastore delete') as c:
        c.argument('force',
                   action='store_true',
                   help="Whether force delete or not.")

    self.argument_context('connectedvmware host create')

    with self.argument_context('connectedvmware host delete') as c:
        c.argument('force',
                   action='store_true',
                   help="Whether force delete or not.")

    self.argument_context('connectedvmware virtual-network create')

    with self.argument_context('connectedvmware virtual-network delete') as c:
        c.argument('force',
                   action='store_true',
                   help="Whether force delete or not.")

    self.argument_context('connectedvmware vm-template create')

    with self.argument_context('connectedvmware vm-template delete') as c:
        c.argument('force',
                   action='store_true',
                   help="Whether force delete or not.")

    with self.argument_context('connectedvmware vm create') as c:
        c.argument(
            'vm_template',
            help="Name or ID of the vm template for deploying the vm.",
        )
        c.argument(
            'resource_pool',
            help="Name or ID of the resource pool for deploying the vm.",
        )
        c.argument(
            'cluster',
            options_list=['--cluster'],
            help="Name or ID of the cluster for deploying the VM.",
        )
        c.argument(
            'host',
            options_list=['--host'],
            help="Name or ID of the host for deploying the VM.",
        )
        c.argument(
            'datastore',
            options_list=['--datastore'],
            help="Name or ID of the datastore for deploying the VM.",
        )
        c.argument(
            'admin_username',
            options_list=['--admin-username'],
            help="Admin username for the vm.",
        )
        c.argument(
            'admin_password',
            options_list=['--admin-password'],
            help="Admin password for the vm.",
        )
        c.argument(
            'num_CPUs',
            type=int,
            options_list=['--num-CPUs'],
            help="Number of desired vCPUs for the vm.",
        )
        c.argument(
            'num_cores_per_socket',
            type=int,
            options_list=['--num-cores-per-socket'],
            help="Number of desired cores per socket for the vm.",
        )
        c.argument(
            'memory_size',
            type=int,
            options_list=['--memory-size'],
            help="Desired memory size in MBs for the vm.",
        )
        c.argument(
            'nics',
            options_list=['--nic'],
            action=VmNicAddAction,
            nargs='+',
            help="Network overrides for the vm. "
            "Usage: --nic name=<> network=<> nic-type=<> power-on-boot=<> "
            "allocation-method=<> ip-address=<> subnet-mask=<> device-key=<> "
            "gateway=<command separated list of gateways>.",
        )
        c.argument(
            'disks',
            options_list=['--disk'],
            action=VmDiskAddAction,
            nargs='+',
            help="Disk overrides for the vm. "
            "Usage: --disk name=<> disk_size=<> disk_mode=<> controller_key=<> "
            "device-key=<> unit_number=<>.",
        )

    with self.argument_context('connectedvmware vm update') as c:
        c.argument(
            'num_CPUs',
            type=int,
            options_list=['--num-CPUs'],
            help="Number of desired vCPUs for the vm.",
        )
        c.argument(
            'num_cores_per_socket',
            type=int,
            options_list=['--num-cores-per-socket'],
            help="Number of desired cores per socket for the vm.",
        )
        c.argument(
            'memory_size',
            type=int,
            options_list=['--memory-size'],
            help="Desired memory size in MBs for the vm.",
        )
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('connectedvmware vm delete') as c:
        c.argument('force',
                   action='store_true',
                   help="Whether force delete or not.")

    with self.argument_context('connectedvmware vm stop') as c:
        c.argument(
            'skip_shutdown',
            action='store_true',
            help="Skips shutdown and power-off immediately.",
        )

    with self.argument_context('connectedvmware vm nic') as c:
        c.argument('nic_name',
                   options_list=['--name', '-n'],
                   help="Name of the NIC.")
        c.argument('vm_name',
                   options_list=['--vm-name'],
                   help="Name of the virtual machine.")
        c.argument(
            'network',
            options_list=['--network'],
            help="Name or Id of the virtual network.",
        )
        c.argument('nic_type',
                   options_list=['--nic-type'],
                   help="The nic type for the NIC.")
        c.argument(
            'power_on_boot',
            options_list=['--power-on-boot'],
            help="The power on boot option for the nic.",
        )
        c.argument(
            'device_key',
            type=int,
            options_list=['--device-key'],
            help="The device key for the nic.",
        )
        c.argument('nic_names',
                   options_list=['--nics'],
                   nargs='+',
                   help="Names of the NICs.")

    with self.argument_context('connectedvmware vm disk add') as c:
        c.argument('disk_name',
                   options_list=['--name', '-n'],
                   help="Name of the Disk.")
        c.argument('vm_name',
                   options_list=['--vm-name'],
                   help="Name of the virtual machine.")
        c.argument(
            'disk_size',
            type=int,
            options_list=['--disk-size'],
            help="The disk size in GBs.",
        )
        c.argument('disk_mode',
                   options_list=['--disk-mode'],
                   help="The mode of the disk.")
        c.argument(
            'controller_key',
            type=int,
            options_list=['--controller-key'],
            help="The controller key of the disk.",
        )
        c.argument(
            'unit_number',
            type=int,
            options_list=['--unit-number'],
            help="The unit number of the disk.",
        )
        c.argument(
            'device_key',
            type=int,
            options_list=['--device-key'],
            help="The device key for the disk.",
        )
        c.argument(
            'disk_names',
            options_list=['--disks'],
            nargs='+',
            help="Names of the Disks.",
        )

    with self.argument_context('connectedvmware vm disk delete') as c:
        c.argument('vm_name', help="Name of the virtual machine.")
        c.argument(
            'disk_names',
            options_list=['--disks'],
            nargs='+',
            help="Names of the Disks.",
        )

    with self.argument_context('connectedvmware vm disk list') as c:
        c.argument('vm_name', help="Name of the virtual machine.")

    with self.argument_context('connectedvmware vm disk show') as c:
        c.argument('disk_name',
                   options_list=['--name', '-n'],
                   help="Name of the Disk.")
        c.argument('vm_name',
                   options_list=['--vm-name'],
                   help="Name of the virtual machine.")

    with self.argument_context('connectedvmware vm disk update') as c:
        c.argument('disk_name',
                   options_list=['--name', '-n'],
                   help="Name of the Disk.")
        c.argument('vm_name', help="Name of the virtual machine.")
        c.argument(
            'disk_size',
            type=int,
            options_list=['--disk-size'],
            help="The disk size in GBs.",
        )
        c.argument('disk_mode',
                   options_list=['--disk-mode'],
                   help="The mode of the disk.")
        c.argument(
            'controller_key',
            type=int,
            options_list=['--controller-key'],
            help="The controller key of the disk.",
        )
        c.argument(
            'unit_number',
            type=int,
            options_list=['--unit-number'],
            help="The unit number of the disk.",
        )
        c.argument(
            'device_key',
            type=int,
            options_list=['--device-key'],
            help="The device key for the disk.",
        )

    with self.argument_context('connectedvmware vm guest-agent enable') as c:
        c.argument('vm_name', help="Name of the VM.")
        c.argument(
            'username',
            options_list=['--username'],
            help="Username to use for connecting to the vm.",
        )
        c.argument(
            'password',
            options_list=['--password'],
            help=
            "Username password credentials to use for connecting to the VM.",
        )

    with self.argument_context('connectedvmware vm guest-agent show') as c:
        c.argument(
            'password',
            options_list=['--password'],
            help=
            "Username password credentials to use for connecting to the VM.",
        )

    with self.argument_context('connectedvmware vm guest-agent show') as c:
        c.argument(
            'vm_name',
            help="Name of the VM.",
        )

    with self.argument_context('connectedvmware vm extension list') as c:
        c.argument('vm_name',
                   type=str,
                   help='The name of the vm containing the extension.')
        c.argument('expand',
                   help='The expand expression to apply on the operation.')

    with self.argument_context('connectedvmware vm extension show') as c:
        c.argument('vm_name',
                   type=str,
                   help='The name of the vm containing the extension.',
                   id_part='name')
        c.argument('name',
                   type=str,
                   help='The name of the vm extension.',
                   id_part='child_name_1')

    for scope in [
            'connectedvmware vm extension update',
            'connectedvmware vm extension create'
    ]:
        with self.argument_context(scope) as c:
            c.argument('vm_name',
                       type=str,
                       help='The name of the vm where the extension '
                       'should be created or updated.')
            c.argument('name', type=str, help='The name of the vm extension.')
            c.argument('tags', tags_type)
            c.argument(
                'force_update_tag',
                type=str,
                help=
                'How the extension handler should be forced to update even if '
                'the extension configuration has not changed.')
            c.argument('publisher',
                       type=str,
                       help='The name of the extension handler publisher.')
            c.argument('type_',
                       options_list=['--type'],
                       type=str,
                       help='Specify the type of the extension; an example '
                       'is "CustomScriptExtension".')
            c.argument('type_handler_version',
                       type=str,
                       help='Specifies the version of the script handler.')
            c.argument(
                'auto_upgrade_minor',
                arg_type=get_three_state_flag(),
                help='Indicate whether the extension should '
                'use a newer minor version if one is available at deployment time. Once deployed, however, the '
                'extension will not upgrade minor versions unless redeployed, even with this property set to true.'
            )
            c.argument(
                'settings',
                type=validate_file_or_dict,
                help='Json formatted public settings for the extension. '
                'Expected value: json-string/json-file/@json-file.')
            c.argument(
                'protected_settings',
                type=validate_file_or_dict,
                help='The extension can contain either '
                'protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. Expected '
                'value: json-string/json-file/@json-file.')

    with self.argument_context('connectedvmware vm extension create') as c:
        c.argument('instance_view_type',
                   type=str,
                   help='Specify the type of the extension; an example is '
                   '"CustomScriptExtension".',
                   arg_group='Instance View')
        c.argument('inst_handler_version',
                   type=str,
                   help='Specify the version of the script handler.',
                   arg_group='Instance View')

    with self.argument_context('connectedvmware vm extension delete') as c:
        c.argument('vm_name',
                   type=str,
                   help='The name of the vm where the extension '
                   'should be deleted.',
                   id_part='name')
        c.argument('name',
                   type=str,
                   help='The name of the vm extension.',
                   id_part='child_name_1')
Exemplo n.º 31
0
def load_arguments(self, _):

    modules_type = CLIArgumentType(
        nargs='*',
        help=
        "Space-separated list of modules or extensions (dev mode) to check. "
        "Use 'CLI' to check built-in modules or 'EXT' to check extensions. "
        "Omit to check all. ")

    with ArgumentsContext(self, '') as c:
        c.argument('private',
                   action='store_true',
                   help='Target the private repo.')
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   action='store_true',
                   help='Answer "yes" to all prompts.')
        c.argument(
            'use_ext_index',
            action='store_true',
            help=
            'Run command on extensions registered in the azure-cli-extensions index.json.'
        )
        c.argument(
            'git_source',
            options_list='--src',
            arg_group='Git',
            help=
            'Name of the Git source branch to check (i.e. master or upstream/master).'
        )
        c.argument(
            'git_target',
            options_list='--tgt',
            arg_group='Git',
            help=
            'Name of the Git target branch to check (i.e. dev or upstream/dev)'
        )
        c.argument('git_repo',
                   options_list='--repo',
                   arg_group='Git',
                   help='Path to the Git repo to check.')

    with ArgumentsContext(self, 'setup') as c:
        c.argument(
            'cli_path',
            options_list=['--cli', '-c'],
            nargs='?',
            const=Flag,
            help=
            "Path to an existing Azure CLI repo. Omit value to search for the repo or use special value 'EDGE' to install the latest developer edge build."
        )
        c.argument(
            'ext_repo_path',
            options_list=['--repo', '-r'],
            nargs='+',
            help=
            'Space-separated list of paths to existing Azure CLI extensions repos.'
        )
        c.argument(
            'ext',
            options_list=['--ext', '-e'],
            nargs='+',
            help=
            "Space-separated list of extensions to install initially. Use '*' to install all extensions."
        )
        c.argument('deps',
                   options_list=['--deps-from', '-d'],
                   choices=['requirements.txt', 'setup.py'],
                   default='requirements.txt',
                   help="Choose the file to resolve dependencies.")

    with ArgumentsContext(self, 'test') as c:
        c.argument(
            'discover',
            options_list='--discover',
            action='store_true',
            help=
            'Build an index of test names so that you don\'t need to specify fully qualified test paths.'
        )
        c.argument(
            'xml_path',
            options_list='--xml-path',
            help=
            'Path and filename at which to store the results in XML format. If omitted, the file will be saved as `test_results.xml` in your `.azdev` directory.'
        )
        c.argument('in_series',
                   options_list='--series',
                   action='store_true',
                   help='Disable test parallelization.')
        c.argument('run_live',
                   options_list='--live',
                   action='store_true',
                   help='Run all tests live.')

        c.positional(
            'tests',
            nargs='*',
            help=
            "Space-separated list of tests to run. Can specify module or extension names, test filenames, class name or individual method names. "
            "Omit to check all or use 'CLI' or 'EXT' to check only CLI modules or extensions respectively.",
            completer=get_test_completion)
        c.argument(
            'profile',
            options_list='--profile',
            help=
            'Run automation against a specific profile. If omit, the tests will run against current profile.'
        )
        c.argument('pytest_args',
                   nargs=argparse.REMAINDER,
                   options_list=['--pytest-args', '-a'],
                   help='Denotes the remaining args will be passed to pytest.')
        c.argument('last_failed',
                   options_list='--lf',
                   action='store_true',
                   help='Re-run the last tests that failed.')
        c.argument('no_exit_first',
                   options_list='--no-exitfirst',
                   action='store_true',
                   help='Do not exit on first error or failed test')

        # CI parameters
        c.argument(
            'cli_ci',
            action='store_true',
            arg_group='Continuous Integration',
            help='Apply incremental test strategy to Azure CLI on Azure DevOps'
        )

    with ArgumentsContext(self, 'coverage') as c:
        c.argument('prefix',
                   type=str,
                   help='Filter analysis by command prefix.')
        c.argument('report',
                   action='store_true',
                   help='Display results as a report.')
        c.argument(
            'untested_params',
            nargs='+',
            help=
            'Space-separated list of param dest values to search for (OR logic)'
        )

    with ArgumentsContext(self, 'style') as c:
        c.positional('modules', modules_type)
        c.argument('pylint', action='store_true', help='Run pylint.')
        c.argument('pep8',
                   action='store_true',
                   help='Run flake8 to check PEP8.')

    with ArgumentsContext(self, 'cli check-versions') as c:
        c.argument(
            'update',
            action='store_true',
            help=
            'If provided, the command will update the versions in azure-cli\'s setup.py file.'
        )
        c.argument(
            'pin',
            action='store_true',
            help=
            'If provided and used with --update, will pin the module versions in azure-cli\'s setup.py file.'
        )

    with ArgumentsContext(self, 'cli update-setup') as c:
        c.argument(
            'pin',
            action='store_true',
            help='Pin the module versions in azure-cli\'s setup.py file.')

    # region linter
    with ArgumentsContext(self, 'linter') as c:
        c.positional('modules', modules_type)
        c.argument(
            'rules',
            options_list=['--rules', '-r'],
            nargs='+',
            help='Space-separated list of rules to run. Omit to run all rules.'
        )
        c.argument(
            'rule_types',
            options_list=['--rule-types', '-t'],
            nargs='+',
            choices=['params', 'commands', 'command_groups', 'help_entries'],
            help='Space-separated list of rule types to run. Omit to run all.')
        c.argument(
            'ci_exclusions',
            action='store_true',
            help='Force application of CI exclusions list when run locally.')
        c.argument(
            'include_whl_extensions',
            action='store_true',
            help=
            "Allow running linter on extensions installed by `az extension add`."
        )
        c.argument(
            'save_global_exclusion',
            action='store_true',
            options_list=['--save', '-s'],
            help=
            "Allow saving global exclusion. It would take effect when modules is CLI or EXT.",
            deprecate_info=c.deprecate(hide=True))
        c.argument(
            'min_severity',
            choices=linter_severity_choices(),
            help='The minimum severity level to run the linter on. '
            'For example, specifying "medium" runs linter rules that have "high" or "medium" severity. '
            'However, specifying "low" runs the linter on every rule, regardless of severity. '
            'Defaults to "high".')
    # endregion

    with ArgumentsContext(self, 'perf') as c:
        c.argument('runs',
                   type=int,
                   help='Number of runs to average performance over.')

    with ArgumentsContext(self, 'extension') as c:
        c.argument(
            'dist_dir',
            help='Name of a directory in which to save the resulting WHL files.'
        )

    with ArgumentsContext(self, 'extension publish') as c:
        c.argument(
            'update_index',
            action='store_true',
            help='Update the index.json file after publishing is complete.')

    with ArgumentsContext(self, 'extension publish') as c:
        c.argument(
            'storage_account',
            help=
            'Name of the storage account to publish to. Environment variable: AZDEV_DEFAULTS_STORAGE_ACCOUNT.',
            arg_group='Storage',
            configured_default='storage_account')
        c.argument(
            'storage_container',
            help=
            'Name of the storage container to publish to. Environment variable: AZDEV_DEFAULTS_STORAGE_CONTAINER.',
            arg_group='Storage',
            configured_default='storage_container')
        c.argument('storage_account_key',
                   help='Key of the storage account to publish to. ',
                   arg_group='Storage',
                   configured_default='storage_account')

    for scope in [
            'extension add', 'extension remove', 'extension build',
            'extension publish'
    ]:
        with ArgumentsContext(self, scope) as c:
            c.positional('extensions',
                         metavar='NAME',
                         nargs='+',
                         help='Space-separated list of extension names.')

    for scope in ['extension repo add', 'extension repo remove']:
        with ArgumentsContext(self, scope) as c:
            c.positional(
                'repos',
                metavar='PATH',
                nargs='+',
                help='Space-separated list of paths to Git repositories.')

    with ArgumentsContext(self, 'extension update-index') as c:
        c.positional(
            'extensions',
            nargs='+',
            metavar='URL',
            help='Space-separated list of URLs to extension WHL files.')

    with ArgumentsContext(self, 'cli create') as c:
        c.positional('mod_name', help='Name of the module to create.')

    with ArgumentsContext(self, 'cli create') as c:
        c.ignore('local_sdk')

    with ArgumentsContext(self, 'extension create') as c:
        c.positional('ext_name', help='Name of the extension to create.')

    for scope in ['extension create', 'cli create']:
        with ArgumentsContext(self, scope) as c:
            c.argument(
                'github_alias',
                help=
                'Github alias for the individual who will be the code owner for this package.'
            )
            c.argument(
                'not_preview',
                action='store_true',
                help='Do not create template commands under a "Preview" status.'
            )
            c.argument(
                'required_sdk',
                help=
                'Name and version of the underlying Azure SDK that is published on PyPI. (ex: azure-mgmt-contoso==0.1.0).',
                arg_group='SDK')
            c.argument(
                'local_sdk',
                help=
                'Path to a locally saved SDK. Use if your SDK is not available on PyPI.',
                arg_group='SDK')
            c.argument(
                'client_name',
                help=
                'Name of the Python SDK client object (ex: ContosoManagementClient).',
                arg_group='SDK')
            c.argument(
                'operation_name',
                help=
                'Name of the principal Python SDK operation class (ex: ContosoOperations).',
                arg_group='SDK')
            c.argument(
                'sdk_property',
                help=
                'The name of the Python variable that describes the main object name in the SDK calls (i.e.: account_name)',
                arg_group='SDK')
            c.argument('repo_name',
                       help='Name of the repo the extension will exist in.')
            c.argument('display_name',
                       arg_group='Help',
                       help='Description to display in help text.')
            c.argument('display_name_plural',
                       arg_group='Help',
                       help='Description to display in help text when plural.')

    with ArgumentsContext(self, 'cli generate-docs') as c:
        c.argument(
            'all_profiles',
            action='store_true',
            help=
            "If specified, generate docs for all CLI profiles. NOTE: this command updates the current CLI profile and will attempt to reset it to its original value. "
            "Please check the CLI's profile after running this command.")

    for scope in ['cli', 'extension']:
        with ArgumentsContext(self, '{} generate-docs'.format(scope)) as c:

            c.argument(
                'output_dir',
                help=
                'Directory to place the generated docs in. Defaults to a temporary directory. '
                'If the base directory does not exist, it will be created')
            c.argument('output_type',
                       choices=['xml', 'html', 'text', 'man', 'latex'],
                       default="xml",
                       help='Output type of the generated docs.')
Exemplo n.º 32
0
 def test_override_remove_validator(self):
     existing_options_list = ('--something-else', '-s')
     arg = CLIArgumentType(options_list=existing_options_list,
                           validator=lambda *args, **kwargs: ())
     arg.update(validator=None)
     self.assertIsNone(arg.settings['validator'])
Exemplo n.º 33
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_name',
                   options_list=('--application-name', ),
                   help="The name 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_name',
                   options_list=('--application-name', ),
                   help="The name of the application.")
        c.argument('version_name',
                   options_list=('--version-name', ),
                   help="The version name 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_supported_images,
            arg_group="Pool: Virtual Machine Configuration",
            help=
            "OS image reference. This can be either 'publisher:offer:sku[:version]' format, or a fully qualified ARM image id of the form '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName}'. If 'publisher:offer:sku[:version]' format, version is optional and if omitted latest will be used. Valid values can be retrieved via 'az batch pool supported-images list'. For example: 'MicrosoftWindowsServer:WindowsServer:2012-R2-Datacenter:latest'"
        )

    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'
            )