コード例 #1
0
    def register_common_storage_account_options(self):
        from azure.cli.core.commands.parameters import get_three_state_flag, get_enum_type
        from ._validators import validate_encryption_services

        t_access_tier, t_sku_name, t_encryption_services = self.command_loader.get_models(
            'AccessTier', 'SkuName', 'EncryptionServices', resource_type=CUSTOM_MGMT_STORAGE)

        self.argument('https_only', help='Allows https traffic only to storage service.',
                      arg_type=get_three_state_flag())
        self.argument('file_aad', arg_type=get_three_state_flag(),
                      help='Allows Azure File Active Directory integration, which will support SMB access to '
                           'azure files using AAD. Requires AAD domain service setup: "https://'
                           'docs.microsoft.com/en-us/azure/storage/files/storage-files-active-directory-enable"')
        self.argument('sku', help='The storage account SKU.', arg_type=get_enum_type(t_sku_name))
        self.argument('assign_identity', action='store_true', resource_type=CUSTOM_MGMT_STORAGE,
                      min_api='2017-06-01',
                      help='Generate and assign a new Storage Account Identity for this storage account for use '
                           'with key management services like Azure KeyVault.')
        self.argument('access_tier', arg_type=get_enum_type(t_access_tier),
                      help='The access tier used for billing StandardBlob accounts. Cannot be set for StandardLRS, '
                           'StandardGRS, StandardRAGRS, or PremiumLRS account types. It is required for '
                           'StandardBlob accounts during creation')

        if t_encryption_services:
            encryption_choices = list(
                t_encryption_services._attribute_map.keys())  # pylint: disable=protected-access
            self.argument('encryption_services', arg_type=get_enum_type(encryption_choices),
                          resource_type=CUSTOM_MGMT_STORAGE, min_api='2016-12-01', nargs='+',
                          validator=validate_encryption_services, help='Specifies which service(s) to encrypt.')
コード例 #2
0
def load_arguments(self, _):
    with self.argument_context('account management-group') as c:
        c.argument('group_name', options_list=['--group-name', '--name', '-n'])

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

    with self.argument_context('account management-group create') as c:
        c.argument('display_name', options_list=['--display-name', '-d'])
        c.argument('parent_id', options_list=['--parent-id', '-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-id', '-p'])
コード例 #3
0
ファイル: _params.py プロジェクト: derekbekoe/azure-cli
def load_arguments(self, _):
    with self.argument_context('eventgrid') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location', arg_type=get_location_type(self.cli_ctx))
        c.argument('tags', arg_type=tags_type)
        c.argument('included_event_types', arg_type=included_event_types_type)
        c.argument('labels', arg_type=labels_type)
        c.argument('endpoint_type', arg_type=get_enum_type(['webhook', 'eventhub'], default='webhook'))
        c.argument('resource_id', help="Fully qualified identifier of the Azure resource.")
        c.argument('endpoint', help="Endpoint where EventGrid should deliver events matching this event subscription. For webhook endpoint type, this should be the corresponding webhook URL. For eventhub endpoint type, this should be the Azure ResourceID of the event hub.")
        c.argument('event_subscription_name', help="Name of the event subscription.")
        c.argument('subject_begins_with', help="An optional string to filter events for an event subscription based on a prefix. Wildcard characters are not supported.")
        c.argument('subject_ends_with', help="An optional string to filter events for an event subscription based on a suffix. Wildcard characters are not supported.")
        c.argument('topic_type_name', help="Name of the topic type.")
        c.argument('is_subject_case_sensitive', arg_type=get_three_state_flag(), options_list=['--subject-case-sensitive'], help="Specify to indicate whether the subject fields should be compared in a case sensitive manner. True if flag present.", )

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

    with self.argument_context('eventgrid event-subscription') as c:
        c.argument('topic_name', help='Name of the Event Grid topic', options_list=['--topic-name'], completer=get_resource_name_completion_list('Microsoft.EventGrid/topics'))
        c.argument('event_subscription_name', arg_type=name_type, help='Name of the event subscription')

    with self.argument_context('eventgrid event-subscription create') as c:
        c.argument('topic_name', help='Name of the Event Grid topic to which the event subscription needs to be created.', options_list=['--topic-name'], completer=get_resource_name_completion_list('Microsoft.EventGrid/topics'))
        c.argument('event_subscription_name', arg_type=name_type, help='Name of the new event subscription')
        c.argument('resource_id', help="Fully qualified identifier of the Azure resource to which the event subscription needs to be created.")

    with self.argument_context('eventgrid event-subscription delete') as c:
        c.argument('topic_name', help='Name of the Event Grid topic whose event subscription needs to be deleted.', options_list=['--topic-name'], completer=get_resource_name_completion_list('Microsoft.EventGrid/topics'))
        c.argument('event_subscription_name', arg_type=name_type, help='Name of the event subscription')
        c.argument('resource_id', help="Fully qualified identifier of the Azure resource whose event subscription needs to be deleted.")

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

    with self.argument_context('eventgrid topic-type') as c:
        c.argument('topic_type_name', arg_type=name_type, help="Name of the topic type.", completer=get_resource_name_completion_list('Microsoft.EventGrid/topictypes'))
コード例 #4
0
ファイル: _params.py プロジェクト: sptramer/azure-cli
def load_arguments(self, _):

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

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

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

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

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

    with self.argument_context('cosmosdb collection') as c:
        c.argument('collection_id', options_list=['--collection-name', '-c'], help='Collection Name')
        c.argument('throughput', type=int, help='Offer Throughput')
        c.argument('partition_key_path', help='Partition Key Path, e.g., \'/properties/name\'')
        c.argument('indexing_policy', type=shell_safe_json_parse, completer=FilesCompleter(), help='Indexing Policy, you can enter it as a string or as a file, e.g., --indexing-policy @policy-file.json)')
        c.argument('default_ttl', type=int, help='Default TTL')
コード例 #5
0
ファイル: _command_type.py プロジェクト: derekbekoe/azure-cli
    def attributes_argument(self, name, attr_class, create=False, ignore=None):
        from azure.cli.command_modules.keyvault._validators import get_attribute_validator, datetime_type
        from azure.cli.core.commands.parameters import get_three_state_flag

        from knack.arguments import ignore_type

        ignore = ignore or []
        self.argument('{}_attributes'.format(name), ignore_type,
                      validator=get_attribute_validator(name, attr_class, create))
        if create:
            self.extra('disabled', help='Create {} in disabled state.'.format(name), arg_type=get_three_state_flag())
        else:
            self.extra('enabled', help='Enable the {}.'.format(name), arg_type=get_three_state_flag())
        if 'expires' not in ignore:
            self.extra('expires', default=None, help='Expiration UTC datetime  (Y-m-d\'T\'H:M:S\'Z\').',
                       type=datetime_type)
        if 'not_before' not in ignore:
            self.extra('not_before', default=None, type=datetime_type,
                       help='Key not usable before the provided UTC datetime  (Y-m-d\'T\'H:M:S\'Z\').')
コード例 #6
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) etc',
        arg_type=get_enum_type([
            'F1', 'FREE', 'D1', 'SHARED', 'B1', 'B2', 'B3', 'S1', 'S2', 'S3',
            'P1', 'P2', 'P3', 'P1V2', 'P2V2', 'P3V2'
        ]))
    webapp_name_arg_type = CLIArgumentType(
        configured_default='web',
        options_list=['--name', '-n'],
        metavar='NAME',
        completer=get_resource_name_completion_list('Microsoft.Web/sites'),
        id_part='name',
        help=
        "name of the web. You can configure the default using 'az configure --defaults web=<name>'"
    )

    # use this hidden arg to give a command the right instance, that functionapp commands
    # work on function app and webapp ones work on web app
    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 web. 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')
    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(
            '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 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))
    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')

    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')
        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('disable_msi',
                       action='store_true',
                       help='disable the identity')
            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('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 config appsettings') as c:
        c.argument(
            'slot_settings',
            nargs='+',
            help=
            "space-separated slot app settings in a format of <name>=<value>")
    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 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))

    with self.argument_context('webapp 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(
            '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(
            'app_command_line',
            options_list=['--startup-file'],
            help=
            "The startup file for linux hosted web apps, e.g. 'process.json' for Node.js web"
        )

    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))
        c.argument('action', arg_type=get_enum_type(AUTH_TYPES))
        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')
        c.argument('client_secret',
                   options_list=['--aad-client-secret'],
                   arg_group='Azure Active Directory')
        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')
        c.argument('facebook_app_secret', arg_group='Facebook')
        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')
        c.argument('twitter_consumer_secret', arg_group='Twitter')
        c.argument('google_client_id', arg_group='Google')
        c.argument('google_client_secret', arg_group='Google')
        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')
        c.argument('microsoft_account_client_secret', arg_group='Microsoft')
        c.argument(
            'microsoft_account_oauth_scopes',
            nargs='+',
            help=
            "One or more Microsoft authentification scopes (space-delimited).",
            arg_group='Microsoft')

    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."
        )
    # 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)
コード例 #7
0
ファイル: _params.py プロジェクト: ykimura0725/azure-cli
def load_arguments(self, _):  # pylint: disable=too-many-statements
    # Arguments for IoT DPS
    with self.argument_context('iot dps') as c:
        c.argument('dps_name',
                   dps_name_type,
                   options_list=['--name', '-n'],
                   id_part='name')
        c.argument('tags', tags_type)

    with self.argument_context('iot dps create') as c:
        c.argument(
            'location',
            get_location_type(self.cli_ctx),
            help=
            'Location of your IoT Provisioning Service. Default is the location of target resource group.'
        )
        c.argument('sku',
                   arg_type=get_enum_type(IotDpsSku),
                   help='Pricing tier for the IoT provisioning service.')
        c.argument('unit',
                   help='Units in your IoT Provisioning Service.',
                   type=int)

    for subgroup in ['access-policy', 'linked-hub', 'certificate']:
        with self.argument_context('iot dps {}'.format(subgroup)) as c:
            c.argument('dps_name', options_list=['--dps-name'], id_part=None)

    with self.argument_context('iot dps access-policy') as c:
        c.argument('access_policy_name',
                   options_list=['--access-policy-name', '--name', '-n'],
                   help='A friendly name for DPS access policy.')

    with self.argument_context('iot dps access-policy create') as c:
        c.argument(
            'rights',
            options_list=['--rights', '-r'],
            nargs='+',
            arg_type=get_enum_type(AccessRightsDescription),
            help=
            'Access rights for the IoT provisioning service. Use space-separated list for multiple rights.'
        )
        c.argument('primary_key', help='Primary SAS key value.')
        c.argument('secondary_key', help='Secondary SAS key value.')

    with self.argument_context('iot dps access-policy update') as c:
        c.argument(
            'rights',
            options_list=['--rights', '-r'],
            nargs='+',
            arg_type=get_enum_type(AccessRightsDescription),
            help=
            'Access rights for the IoT provisioning service. Use space-separated list for multiple rights.'
        )
        c.argument('primary_key', help='Primary SAS key value.')
        c.argument('secondary_key', help='Secondary SAS key value.')

    with self.argument_context('iot dps linked-hub') as c:
        c.argument('linked_hub',
                   options_list=['--linked-hub'],
                   help='Host name of linked IoT Hub.')

    with self.argument_context('iot dps linked-hub create') as c:
        c.argument('connection_string',
                   help='Connection string of the IoT hub.')
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   help='Location of the IoT hub.')
        c.argument(
            'apply_allocation_policy',
            help=
            'A boolean indicating whether to apply allocation policy to the IoT hub.',
            arg_type=get_three_state_flag())
        c.argument('allocation_weight',
                   help='Allocation weight of the IoT hub.')

    with self.argument_context('iot dps linked-hub update') as c:
        c.argument(
            'apply_allocation_policy',
            help=
            'A boolean indicating whether to apply allocation policy to the Iot hub.',
            arg_type=get_three_state_flag())
        c.argument('allocation_weight',
                   help='Allocation weight of the IoT hub.')

    with self.argument_context('iot dps allocation-policy update') as c:
        c.argument('allocation_policy',
                   options_list=['--policy', '-p'],
                   arg_type=get_enum_type(AllocationPolicy),
                   help='Allocation policy for the IoT provisioning service.')

    with self.argument_context('iot dps certificate') as c:
        c.argument('certificate_path',
                   options_list=['--path', '-p'],
                   type=file_type,
                   completer=FilesCompleter([".cer", ".pem"]),
                   help='The path to the file containing the certificate.')
        c.argument('certificate_name',
                   options_list=['--certificate-name', '--name', '-n'],
                   help='A friendly name for the certificate.')
        c.argument('etag',
                   options_list=['--etag', '-e'],
                   help='Entity Tag (etag) of the object.')

    # Arguments for IoT Hub
    with self.argument_context('iot hub') as c:
        c.argument('hub_name',
                   hub_name_type,
                   options_list=['--name', '-n'],
                   id_part='name')
        c.argument('etag',
                   options_list=['--etag', '-e'],
                   help='Entity Tag (etag) of the object.')
        c.argument(
            'sku',
            arg_type=get_enum_type(IotHubSku),
            help='Pricing tier for Azure IoT Hub. '
            'Note that only one free IoT hub instance (F1) is allowed in each '
            'subscription. Exception will be thrown if free instances exceed one.'
        )
        c.argument('unit', help='Units in your IoT Hub.', type=int)
        c.argument(
            'partition_count',
            help=
            'The number of partitions of the backing Event Hub for device-to-cloud messages.',
            type=int)
        c.argument(
            'retention_day',
            options_list=['--retention-day', '--rd'],
            type=int,
            validator=validate_retention_days,
            help=
            'Specifies how long this IoT hub will maintain device-to-cloud events, between 1 and 7 days.'
        )
        c.argument(
            'c2d_ttl',
            options_list=['--c2d-ttl', '--ct'],
            type=int,
            validator=validate_c2d_ttl,
            help=
            'The amount of time a message is available for the device to consume before it is expired'
            ' by IoT Hub, between 1 and 48 hours.')
        c.argument(
            'c2d_max_delivery_count',
            options_list=['--c2d-max-delivery-count', '--cdd'],
            type=int,
            validator=validate_c2d_max_delivery_count,
            help=
            'The number of times the IoT hub will attempt to deliver a cloud-to-device'
            ' message to a device, between 1 and 100.')
        c.argument(
            'feedback_ttl',
            options_list=['--feedback-ttl', '--ft'],
            type=int,
            validator=validate_feedback_ttl,
            help=
            'The period of time for which the IoT hub will maintain the feedback for expiration'
            ' or delivery of cloud-to-device messages, between 1 and 48 hours.'
        )
        c.argument(
            'feedback_lock_duration',
            options_list=['--feedback-lock-duration', '--fld'],
            type=int,
            validator=validate_feedback_lock_duration,
            help=
            'The lock duration for the feedback queue, between 5 and 300 seconds.'
        )
        c.argument(
            'feedback_max_delivery_count',
            options_list=['--feedback-max-delivery-count', '--fd'],
            type=int,
            validator=validate_feedback_max_delivery_count,
            help='The number of times the IoT hub attempts to'
            ' deliver a message on the feedback queue, between 1 and 100.')
        c.argument(
            'enable_fileupload_notifications',
            options_list=['--fileupload-notifications', '--fn'],
            arg_type=get_three_state_flag(),
            help=
            'A boolean indicating whether to log information about uploaded files to the'
            ' messages/servicebound/filenotifications IoT Hub endpoint.')
        c.argument(
            'fileupload_notification_max_delivery_count',
            type=int,
            options_list=[
                '--fileupload-notification-max-delivery-count', '--fnd'
            ],
            validator=validate_fileupload_notification_max_delivery_count,
            help=
            'The number of times the IoT hub will attempt to deliver a file notification message,'
            ' between 1 and 100.')
        c.argument(
            'fileupload_notification_ttl',
            options_list=['--fileupload-notification-ttl', '--fnt'],
            type=int,
            validator=validate_fileupload_notification_ttl,
            help=
            'The amount of time a file upload notification is available for the service to'
            ' consume before it is expired by IoT Hub, between 1 and 48 hours.'
        )
        c.argument(
            'fileupload_storage_connectionstring',
            options_list=['--fileupload-storage-connectionstring', '--fcs'],
            help=
            'The connection string for the Azure Storage account to which files are uploaded.'
        )
        c.argument(
            'fileupload_storage_authentication_type',
            options_list=['--fileupload-storage-auth-type', '--fsa'],
            help=
            'The authentication type for the Azure Storage account to which files are uploaded.'
            'Possible values are keyBased and identityBased')
        c.argument(
            'fileupload_storage_container_uri',
            options_list=['--fileupload-storage-container-uri', '--fcu'],
            help=
            'The container URI for the Azure Storage account to which files are uploaded.'
        )
        c.argument(
            'fileupload_storage_container_name',
            options_list=['--fileupload-storage-container-name', '--fc'],
            help=
            'The name of the root container where you upload files. The container need not exist but'
            ' should be creatable using the connectionString specified.')
        c.argument(
            'fileupload_sas_ttl',
            options_list=['--fileupload-sas-ttl', '--fst'],
            type=int,
            validator=validate_fileupload_sas_ttl,
            help=
            'The amount of time a SAS URI generated by IoT Hub is valid before it expires,'
            ' between 1 and 24 hours.')
        c.argument(
            'min_tls_version',
            options_list=['--min-tls-version', '--mintls'],
            type=str,
            help=
            'Specify the minimum TLS version to support for this hub. Can be set to'
            ' "1.2" to have clients that use a TLS version below 1.2 to be rejected.'
        )

    for subgroup in [
            'consumer-group', 'policy', 'certificate', 'routing-endpoint',
            'route'
    ]:
        with self.argument_context('iot hub {}'.format(subgroup)) as c:
            c.argument('hub_name', options_list=['--hub-name'])

    with self.argument_context('iot hub route') as c:
        c.argument('route_name',
                   options_list=['--route-name', '--name', '-n'],
                   help='Name of the Route.')
        c.argument('endpoint_name',
                   options_list=['--endpoint-name', '--endpoint', '--en'],
                   help='Name of the routing endpoint.')
        c.argument(
            'condition',
            options_list=['--condition', '-c'],
            help='Condition that is evaluated to apply the routing rule.')
        c.argument(
            'enabled',
            options_list=['--enabled', '-e'],
            arg_type=get_three_state_flag(),
            help='A boolean indicating whether to enable route to the Iot hub.'
        )
        c.argument('source_type',
                   arg_type=get_enum_type(RouteSourceType),
                   options_list=['--source-type', '--type', '--source', '-s'],
                   help='Source of the route.')

    with self.argument_context('iot hub route test') as c:
        c.argument('body',
                   options_list=['--body', '-b'],
                   help='Body of the route message.')
        c.argument('app_properties',
                   options_list=['--app-properties', '--ap'],
                   help='App properties of the route message.')
        c.argument('system_properties',
                   options_list=['--system-properties', '--sp'],
                   help='System properties of the route message.')

    with self.argument_context('iot hub routing-endpoint') as c:
        c.argument('endpoint_name',
                   options_list=['--endpoint-name', '--name', '-n'],
                   help='Name of the Routing Endpoint.')
        c.argument('endpoint_resource_group',
                   options_list=['--endpoint-resource-group', '--erg', '-r'],
                   help='Resource group of the Endpoint resoure.')
        c.argument('endpoint_subscription_id',
                   options_list=['--endpoint-subscription-id', '-s'],
                   help='SubscriptionId of the Endpoint resource.')
        c.argument('connection_string',
                   options_list=['--connection-string', '-c'],
                   help='Connection string of the Routing Endpoint.')
        c.argument('container_name',
                   options_list=['--container-name', '--container'],
                   help='Name of the storage container.')
        c.argument('endpoint_type',
                   arg_type=get_enum_type(EndpointType),
                   options_list=['--endpoint-type', '--type', '-t'],
                   help='Type of the Routing Endpoint.')
        c.argument(
            'encoding',
            options_list=['--encoding'],
            arg_type=get_enum_type(EncodingFormat),
            help='Encoding format for the container. The default is AVRO. '
            'Note that this field is applicable only for blob container endpoints.'
        )
        c.argument('endpoint_uri',
                   options_list=['--endpoint-uri'],
                   help='The uri of the endpoint resource.')
        c.argument('entity_path',
                   options_list=['--entity-path'],
                   help='The entity path of the endpoint resource.')

    with self.argument_context('iot hub routing-endpoint create') as c:
        c.argument(
            'batch_frequency',
            options_list=['--batch-frequency', '-b'],
            type=int,
            help=
            'Request batch frequency in seconds. The maximum amount of time that can elapse before data is'
            ' written to a blob, between 60 and 720 seconds.')
        c.argument(
            'chunk_size_window',
            options_list=['--chunk-size', '-w'],
            type=int,
            help=
            'Request chunk size in megabytes(MB). The maximum size of blobs, between 10 and 500 MB.'
        )
        c.argument(
            'file_name_format',
            options_list=['--file-name-format', '--ff'],
            help=
            'File name format for the blob. The file name format must contain {iothub},'
            ' {partition}, {YYYY}, {MM}, {DD}, {HH} and {mm} fields. All parameters are'
            ' mandatory but can be reordered with or without delimiters.')
        c.argument(
            'authentication_type',
            options_list=['--auth-type'],
            arg_type=get_enum_type(AuthenticationType),
            help=
            'Authentication type for the endpoint. The default is keyBased.')

    with self.argument_context('iot hub certificate') as c:
        c.argument('certificate_path',
                   options_list=['--path', '-p'],
                   type=file_type,
                   completer=FilesCompleter([".cer", ".pem"]),
                   help='The path to the file containing the certificate.')
        c.argument('certificate_name',
                   options_list=['--name', '-n'],
                   help='A friendly name for the certificate.')

    with self.argument_context('iot hub consumer-group') as c:
        c.argument('consumer_group_name',
                   options_list=['--name', '-n'],
                   id_part='child_name_2',
                   help='Event hub consumer group name.')
        c.argument('event_hub_name',
                   id_part='child_name_1',
                   help='Event hub endpoint name.')

    with self.argument_context('iot hub policy') as c:
        c.argument('policy_name',
                   options_list=['--name', '-n'],
                   id_part='child_name_1',
                   help='Shared access policy name.')
        permission_values = ', '.join([x.value for x in SimpleAccessRights])
        c.argument(
            'permissions',
            nargs='*',
            validator=validate_policy_permissions,
            type=str.lower,
            help=
            'Permissions of shared access policy. Use space-separated list for multiple permissions. '
            'Possible values: {}'.format(permission_values))

    with self.argument_context('iot hub policy renew-key') as c:
        c.argument('regenerate_key',
                   options_list=['--renew-key', '--rk'],
                   arg_type=get_enum_type(RenewKeyType),
                   help='Regenerate keys')

    with self.argument_context('iot hub create') as c:
        c.argument('hub_name', completer=None)
        c.argument(
            'location',
            get_location_type(self.cli_ctx),
            help=
            'Location of your IoT Hub. Default is the location of target resource group.'
        )

    with self.argument_context('iot hub show-connection-string') as c:
        c.argument('show_all',
                   options_list=['--all'],
                   help='Allow to show all shared access policies.')
        c.argument('hub_name', options_list=['--hub-name', '--name', '-n'])
        c.argument('policy_name', help='Shared access policy to use.')
        c.argument('key_type',
                   arg_type=get_enum_type(KeyType),
                   options_list=['--key'],
                   help='The key to use.')

    # Arguments for Message Enrichments
    with self.argument_context('iot hub message-enrichment') as c:
        c.argument('key',
                   options_list=['--key', '-k'],
                   help='The enrichment\'s key.')
        c.argument('value',
                   options_list=['--value', '-v'],
                   help='The enrichment\'s value.')
        c.argument(
            'endpoints',
            options_list=['--endpoints', '-e'],
            nargs='*',
            help=
            'Endpoint(s) to apply enrichments to. Use a space-separated list for multiple endpoints.'
        )

    with self.argument_context('iot central app') as c:
        c.argument('app_name', app_name_type, options_list=['--name', '-n'])

    with self.argument_context('iot central app create') as c:
        c.argument(
            'app_name',
            completer=None,
            help=
            'Give your IoT Central app a unique name so you can find it later.'
            'This will be used as the resource name in the Azure portal and CLI.'
            'Avoid special characters `-` '
            'instead, use lower case letters (a-z), numbers (0-9), and dashes (-)'
        )
        c.argument(
            'location',
            get_location_type(self.cli_ctx),
            help=
            'Where your app\'s info and resources are stored. We will default to the location'
            ' of the target resource group. See documentation for a full list of supported locations.'
        )
        c.argument('sku',
                   arg_type=get_enum_type(AppSku),
                   options_list=['--sku', '-p'],
                   help='Pricing plan for IoT Central application.')
        c.argument(
            'subdomain',
            options_list=['--subdomain', '-s'],
            help=
            'Enter a unique URL. Your app will be accessible via https://<subdomain>.azureiotcentral.com/.'
            ' Avoid special characters `-` instead, use lower '
            'case letters (a-z), numbers (0-9), and dashes (-).')
        c.argument(
            'template',
            options_list=['--template', '-t'],
            help=
            'IoT Central application template name. Default is "Custom application". See documentation for'
            ' a list of available templates.')
        c.argument(
            'display_name',
            options_list=['--display-name', '-d'],
            help=
            'Custom display name for the IoT Central app. This will be used in the IoT Central application'
            ' manager to help you identify your app. Default value is the resource name.'
        )
コード例 #8
0
def load_arguments(self, _):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('network waf-policy custom-rule list') as c:
        c.argument('policy_name', waf_policy_name_type, id_part=None)
コード例 #9
0
def load_arguments(self, _):    # pylint: disable=too-many-statements
    with self.argument_context('eventgrid') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location', arg_type=get_location_type(self.cli_ctx))
        c.argument('tags', arg_type=tags_type)
        c.argument('included_event_types', arg_type=included_event_types_type)
        c.argument('labels', arg_type=labels_type)
        c.argument('endpoint_type', arg_type=get_enum_type(['webhook', 'eventhub', 'storagequeue', 'hybridconnection', 'servicebusqueue'], default='webhook'))
        c.argument('source_resource_id', help="Fully qualified identifier of the source Azure resource.")
        c.argument('resource_id', deprecate_info=c.deprecate(redirect="--source-resource-id", expiration='2.1.0', hide=True), help="Fully qualified identifier of the Azure resource.")
        c.argument('endpoint', help="Endpoint where EventGrid should deliver events matching this event subscription. For webhook endpoint type, this should be the corresponding webhook URL. For other endpoint types, this should be the Azure resource identifier of the endpoint.")
        c.argument('event_subscription_name', help="Name of the event subscription.")
        c.argument('subject_begins_with', help="An optional string to filter events for an event subscription based on a prefix. Wildcard characters are not supported.")
        c.argument('subject_ends_with', help="An optional string to filter events for an event subscription based on a suffix. Wildcard characters are not supported.")
        c.argument('topic_type_name', help="Name of the topic type.")
        c.argument('is_subject_case_sensitive', arg_type=get_three_state_flag(), options_list=['--subject-case-sensitive'], help="Specify to indicate whether the subject fields should be compared in a case sensitive manner. True if flag present.", )
        c.argument('input_mapping_fields', arg_type=input_mapping_fields_type)
        c.argument('input_mapping_default_values', arg_type=input_mapping_default_values_type)
        c.argument('input_schema', arg_type=input_schema_type)
        c.argument('odata_query', arg_type=odata_query_type)
        c.argument('domain_name', arg_type=domain_name_type)
        c.argument('domain_topic_name', arg_type=domain_topic_name_type)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('eventgrid topic-type') as c:
        c.argument('topic_type_name', arg_type=name_type, help="Name of the topic type.", completer=get_resource_name_completion_list('Microsoft.EventGrid/topictypes'))
コード例 #10
0
ファイル: _params.py プロジェクト: derekbekoe/azure-cli
def load_arguments(self, _):
    from azure.keyvault.models import JsonWebKeyOperation
    from azure.keyvault.models import KeyAttributes, SecretAttributes, CertificateAttributes
    from azure.mgmt.keyvault.models.key_vault_management_client_enums import (
        SkuName, KeyPermissions, SecretPermissions, CertificatePermissions)

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

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

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

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

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

    # region Shared
    for item in ['key', 'secret', 'certificate']:
        with self.argument_context('keyvault ' + item) 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)
    # 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.')
        c.argument('key_version', options_list=['--version', '-v'], help='The key version. If omitted, uses the latest version.', default='', required=False, completer=get_keyvault_version_completion_list('key'))

    for scope in ['keyvault key create', 'keyvault key import']:
        with self.argument_context(scope) as c:
            c.argument('destination', arg_type=get_enum_type(['software', 'hsm']), options_list=['--protection', '-p'], help='Specifies the type of key protection.', validator=validate_key_type)
            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 import', arg_group='Key Source') as c:
        c.argument('pem_file', type=file_type, help='PEM file containing the key to be imported.', completer=FilesCompleter(), validator=validate_key_import_source)
        c.argument('pem_password', help='Password of PEM file.')
        c.argument('byok_file', type=file_type, help='BYOK file containing the key to be imported. Must not be password protected.', completer=FilesCompleter())

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

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

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

    # region KeyVault Secret
    with self.argument_context('keyvault secret') as c:
        c.argument('secret_version', options_list=['--version', '-v'], help='The secret version. If omitted, uses the latest version.', default='', required=False, completer=get_keyvault_version_completion_list('secret'))

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

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

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

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

    # KeyVault Certificate
    with self.argument_context('keyvault certificate') as c:
        c.argument('certificate_version', options_list=['--version', '-v'], help='The certificate version. If omitted, uses the latest version.', default='', required=False, completer=get_keyvault_version_completion_list('certificate'))
        c.argument('validity', type=int, help='Number of months the certificate is valid for. Overrides the value specified with --policy/-p')

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('keyvault certificate issuer', arg_group='Organization Detail') as c:
        c.argument('organization_id')
        c.argument('admin_first_name')
        c.argument('admin_last_name')
        c.argument('admin_email')
        c.argument('admin_phone')
コード例 #11
0
ファイル: _params.py プロジェクト: derekbekoe/azure-cli
def load_arguments(self, _):
    from azure.mgmt.compute.models import CachingTypes, UpgradeMode
    from azure.mgmt.storage.models import SkuName

    # REUSABLE ARGUMENT DEFINITIONS
    name_arg_type = CLIArgumentType(options_list=['--name', '-n'], metavar='NAME')
    multi_ids_type = CLIArgumentType(nargs='+')
    existing_vm_name = CLIArgumentType(overrides=name_arg_type,
                                       configured_default='vm',
                                       help="The name of the Virtual Machine. You can configure the default using `az configure --defaults vm=<name>`",
                                       completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachines'), id_part='name')
    existing_disk_name = CLIArgumentType(overrides=name_arg_type, help='The name of the managed disk', completer=get_resource_name_completion_list('Microsoft.Compute/disks'), id_part='name')
    existing_snapshot_name = CLIArgumentType(overrides=name_arg_type, help='The name of the snapshot', completer=get_resource_name_completion_list('Microsoft.Compute/snapshots'), id_part='name')
    vmss_name_type = CLIArgumentType(name_arg_type,
                                     configured_default='vmss',
                                     completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'),
                                     help="Scale set name. You can configure the default using `az configure --defaults vmss=<name>`",
                                     id_part='name')
    disk_sku = CLIArgumentType(help='Underlying storage SKU.', arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS']))

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

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

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

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

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

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

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

    # region Snapshots
    with self.argument_context('snapshot', resource_type=ResourceType.MGMT_COMPUTE, operation_group='snapshots') as c:
        c.argument('snapshot_name', existing_snapshot_name, id_part='name', completer=get_resource_name_completion_list('Microsoft.Compute/snapshots'))
        c.argument('name', arg_type=name_arg_type)
        if self.supported_api_version(min_api='2018-04-01', operation_group='snapshots'):
            c.argument('sku', arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS', 'Standard_ZRS']))
        else:
            c.argument('sku', arg_type=disk_sku)
    # endregion

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

    with self.argument_context('image create') as c:
        # here we collpase all difference image sources to under 2 common arguments --os-disk-source --data-disk-sources
        c.argument('name', arg_type=name_arg_type, help='new image name')
        c.argument('source', help='OS disk source from the same region, including a virtual machine ID or name, OS disk blob URI, managed OS disk ID or name, or OS snapshot ID or name')
        c.argument('data_disk_sources', nargs='+', help='Space-separated list of data disk sources, including unmanaged blob URI, managed disk ID or name, or snapshot ID or name')
        c.argument('zone_resilient', min_api='2017-12-01', arg_type=get_three_state_flag(), help='Specifies whether an image is zone resilient or not. '
                   'Default is false. Zone resilient images can be created only in regions that provide Zone Redundant Storage')
        c.ignore('source_virtual_machine', 'os_blob_uri', 'os_disk', 'os_snapshot', 'data_blob_uris', 'data_disks', 'data_snapshots')
    # endregion

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

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

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

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

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

    with self.argument_context('vm update') as c:
        c.argument('os_disk', min_api='2017-12-01', help="Managed OS disk ID or name to swap to. Feature registration for 'Microsoft.Compute/AllowManagedDisksReplaceOSDisk' is needed")
        c.argument('write_accelerator', nargs='*', min_api='2017-12-01',
                   help="enable/disable disk write accelerator. Use singular value 'true/false' to apply across, or specify individual disks, e.g.'os=true 1=true 2=true' for os disk and data disks with lun of 1 & 2")
        c.argument('disk_caching', nargs='*', help="Use singular value to apply across, or specify individual disks, e.g. 'os=ReadWrite 0=None 1=ReadOnly' should enable update os disk and 2 data disks")

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

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

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

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

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

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

    with self.argument_context('vm disk attach') as c:
        c.argument('enable_write_accelerator', min_api='2017-12-01', action='store_true', help='enable write accelerator')

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

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

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

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

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

    with self.argument_context('vm secret list') as c:
        c.argument('vm_name', arg_type=existing_vm_name, id_part=None)

    with self.argument_context('vm image') as c:
        c.argument('publisher_name', options_list=['--publisher', '-p'])
        c.argument('publisher', options_list=['--publisher', '-p'], help='image publisher')
        c.argument('offer', options_list=['--offer', '-f'], help='image offer')
        c.argument('plan', help='image billing plan')
        c.argument('sku', options_list=['--sku', '-s'], help='image sku')
        c.argument('version', help="image sku's version")
        c.argument('urn', help="URN, in format of 'publisher:offer:sku:versin'. If specified, other argument values can be omitted")

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('vm unmanaged-disk list') as c:
        c.argument('vm_name', arg_type=existing_vm_name, id_part=None)

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

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

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

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

    with self.argument_context('vmss create') as c:
        VMPriorityTypes = self.get_models('VirtualMachinePriorityTypes', resource_type=ResourceType.MGMT_COMPUTE)
        VirtualMachineEvictionPolicyTypes = self.get_models('VirtualMachineEvictionPolicyTypes', resource_type=ResourceType.MGMT_COMPUTE)
        c.argument('name', name_arg_type)
        c.argument('nat_backend_port', default=None, help='Backend port to open with NAT rules.  Defaults to 22 on Linux and 3389 on Windows.')
        c.argument('single_placement_group', arg_type=get_three_state_flag(), help="Enable replicate using fault domains within the same cluster. Default to 'false' for any zonals, or with 100+ instances"
                   " See https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-placement-groups for details")
        c.argument('platform_fault_domain_count', type=int, help='Fault Domain count for each placement group in the availability zone', min_api='2017-12-01')
        c.argument('vmss_name', name_arg_type, id_part=None, help='Name of the virtual machine scale set.')
        c.argument('instance_count', help='Number of VMs in the scale set.', type=int)
        c.argument('disable_overprovision', help='Overprovision option (see https://azure.microsoft.com/en-us/documentation/articles/virtual-machine-scale-sets-overview/ for details).', action='store_true')
        c.argument('upgrade_policy_mode', help=None, arg_type=get_enum_type(UpgradeMode))
        c.argument('health_probe', help='(Preview) probe name from the existing load balancer, mainly used for rolling upgrade')
        c.argument('vm_sku', help='Size of VMs in the scale set.  See https://azure.microsoft.com/en-us/pricing/details/virtual-machines/ for size info.')
        c.argument('nsg', help='Name or ID of an existing Network Security Group.', arg_group='Network')
        c.argument('priority', resource_type=ResourceType.MGMT_COMPUTE, min_api='2017-12-01', arg_type=get_enum_type(VMPriorityTypes, default=None),
                   help="(PREVIEW)Priority. Use 'Low' to run short-lived workloads in a cost-effective way")
        c.argument('eviction_policy', resource_type=ResourceType.MGMT_COMPUTE, min_api='2017-12-01', arg_type=get_enum_type(VirtualMachineEvictionPolicyTypes, default=None),
                   help="(PREVIEW) the eviction policy for virtual machines in a low priority scale set.")

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

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

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

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

    with self.argument_context('vmss disk') as c:
        c.argument('lun', type=int, help='0-based logical unit number (LUN). Max value depends on the Virtual Machine instance size.')
        c.argument('size_gb', options_list=['--size-gb', '-z'], help='size in GB.')
        c.argument('vmss_name', vmss_name_type, completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'))
        c.argument('disk', validator=validate_vmss_disk, help='existing disk name or ID to attach or detach from VM instances',
                   min_api='2017-12-01', completer=get_resource_name_completion_list('Microsoft.Compute/disks'))
        c.argument('instance_id', help='Scale set VM instance id', min_api='2017-12-01')

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

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

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

    with self.argument_context('vmss nic list') as c:
        c.argument('virtual_machine_scale_set_name', arg_type=vmss_name_type, options_list=['--vmss-name'], id_part=None)
    # endregion

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

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

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

    for scope in ['vm identity show', 'vmss identity show']:
        with self.argument_context(scope) as c:
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

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

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

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

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

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

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

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

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

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

    for scope in ['vm extension image', 'vmss extension image']:
        with self.argument_context(scope) as c:
            c.argument('image_location', options_list=['--location', '-l'], help='Image location.')
            c.argument('name', help='Image name', id_part=None)
            c.argument('publisher_name', options_list=['--publisher', '-p'], help='Image publisher name')
            c.argument('type', options_list=['--name', '-n'], help='Name of the extension')
            c.argument('latest', action='store_true', help='Show the latest version only.')
            c.argument('version', help='Extension version')
            c.argument('orderby', help="the $orderby odata query option")
            c.argument('top', help='the $top odata query option')
コード例 #12
0
def load_arguments(self, _):
    with self.argument_context('ad app') as c:
        c.argument('app_id', help='application id')
        c.argument('application_object_id', options_list=('--object-id',))
        c.argument('display_name', help='the display name of the application')
        c.argument('homepage', help='the url where users can sign in and use your app.')
        c.argument('identifier', options_list=['--id'], help='identifier uri, application id, or object id')
        c.argument('identifier_uris', nargs='+', help='space-separated unique URIs that Azure AD can use for this app.')
        c.argument('reply_urls', nargs='+', help='space-separated URIs to which Azure AD will redirect in response to an OAuth 2.0 request. The value does not need to be a physical endpoint, but must be a valid URI.')
        c.argument('start_date', help="Date or datetime at which credentials become valid(e.g. '2017-01-01T01:00:00+00:00' or '2017-01-01'). Default value is current time")
        c.argument('end_date', help="Date or datetime after which credentials expire(e.g. '2017-12-31T11:59:59+00:00' or '2017-12-31'). Default value is one year after current time")
        c.argument('available_to_other_tenants', help='the application can be used from any Azure AD tenants', arg_type=get_three_state_flag())
        c.argument('key_value', help='the value for the key credentials associated with the application')
        # TODO: Update these with **enum_choice_list(...) when SDK supports proper enums
        c.argument('key_type', help='the type of the key credentials associated with the application', arg_type=get_enum_type(['AsymmetricX509Cert', 'Password', 'Symmetric'], default='AsymmetricX509Cert'))
        c.argument('key_usage', help='the usage of the key credentials associated with the application.', arg_type=get_enum_type(['Sign', 'Verify'], default='Verify'))
        c.argument('password', help="app password, aka 'client secret'")
        c.argument('oauth2_allow_implicit_flow', arg_type=get_three_state_flag(), help='whether to allow implicit grant flow for OAuth2')
        c.argument('required_resource_accesses', type=validate_file_or_dict,
                   help="resource scopes and roles the application requires access to. Should be in manifest json format. See examples below for details")
        c.argument('native_app', arg_type=get_three_state_flag(), help="an application which can be installed on a user's device or computer")

    with self.argument_context('ad sp') as c:
        c.argument('identifier', options_list=['--id'], help='service principal name, or object id')

    with self.argument_context('ad sp create') as c:
        c.argument('identifier', options_list=['--id'], help='identifier uri, application id, or object id of the associated application')

    with self.argument_context('ad sp create-for-rbac') as c:
        c.argument('scopes', nargs='+')
        c.argument('role', completer=get_role_definition_name_completion_list)
        c.argument('skip_assignment', arg_type=get_three_state_flag(), help='do not create default assignment')
        c.argument('show_auth_for_sdk', options_list='--sdk-auth', help='output result in compatible with Azure SDK auth file', arg_type=get_three_state_flag())

    for item in ['create-for-rbac', 'credential reset']:
        with self.argument_context('ad sp {}'.format(item)) as c:
            c.argument('name', name_arg_type)
            c.argument('cert', arg_group='Credential', validator=validate_cert)
            c.argument('password', options_list=['--password', '-p'], arg_group='Credential')
            c.argument('years', type=int, default=None, arg_group='Credential')
            c.argument('create_cert', action='store_true', arg_group='Credential')
            c.argument('keyvault', arg_group='Credential')
            c.argument('append', action='store_true', help='Append the new credential instead of overwriting.')

    for item in ['delete', 'list']:
        with self.argument_context('ad sp credential {}'.format(item)) as c:
            c.argument('key_id', help='credential key id')
            c.argument('cert', action='store_true', help='a certificate based credential')

    with self.argument_context('ad') as c:
        c.argument('display_name', help='object\'s display name or its prefix')
        c.argument('identifier_uri', help='graph application identifier, must be in uri format')
        c.argument('spn', help='service principal name')
        c.argument('upn', help='user principal name, e.g. [email protected]')
        c.argument('query_filter', options_list=['--filter'], help='OData filter')

    with self.argument_context('ad user') as c:
        c.argument('mail_nickname', help='mail alias. Defaults to user principal name')
        c.argument('force_change_password_next_login', arg_type=get_three_state_flag())

    group_help_msg = "group's object id or display name(prefix also works if there is a unique match)"
    with self.argument_context('ad group') as c:
        for arg in VARIANT_GROUP_ID_ARGS:
            c.argument(arg, options_list=['--group', '-g'], validator=validate_group, help=group_help_msg)

    with self.argument_context('ad group show') as c:
        c.extra('cmd')

    member_id_help_msg = 'The object ID of the contact, group, user, or service principal'
    with self.argument_context('ad group get-member-groups') as c:
        c.argument('security_enabled_only', arg_type=get_three_state_flag(), default=False, required=False)
        c.extra('cmd')

    with self.argument_context('ad group member add') as c:
        c.argument('url', options_list='--member-id', validator=validate_member_id, help=member_id_help_msg)

    for item in ['member add', 'member check', 'member list', 'member remove', 'delete']:
        with self.argument_context('ad group {}'.format(item)) as c:
            c.extra('cmd')

    with self.argument_context('ad group member') as c:
        c.argument('member_object_id', options_list='--member-id', help=member_id_help_msg)

    with self.argument_context('role') as c:
        c.argument('scope', help='scope at which the role assignment or definition 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('resource_group_name', options_list=['--resource-group', '-g'], help='use it only if the role or assignment was added at the level of a resource group')

    with self.argument_context('role assignment') as c:
        c.argument('role_assignment_name', options_list=['--name', '-n'])
        c.argument('role', help='role name or id', completer=get_role_definition_name_completion_list)
        c.argument('show_all', options_list=['--all'], action='store_true', help='show all assignments under the current subscription')
        c.argument('include_inherited', action='store_true', help='include assignments applied on parent scopes')
        c.argument('can_delegate', action='store_true', help='when set, the assignee will be able to create further role assignments to the same role')
        c.argument('assignee', help='represent a user, group, or service principal. supported format: object id, user sign-in name, or service principal name')
        c.argument('assignee_object_id', help="assignee's graph object id, such as the 'principal id' from a managed service identity. Use this instead of '--assignee' to bypass graph permission issues")
        c.argument('ids', nargs='+', help='space-separated role assignment ids')
        c.argument('include_classic_administrators', arg_type=get_three_state_flag(), help='list default role assignments for subscription classic administrators, aka co-admins')

    time_help = ('The {} of the query in the format of %Y-%m-%dT%H:%M:%SZ, e.g. 2000-12-31T12:59:59Z. Defaults to {}')
    with self.argument_context('role assignment list-changelogs') as c:
        c.argument('start_time', help=time_help.format('start time', '1 Hour prior to the current time'))
        c.argument('end_time', help=time_help.format('end time', 'the current time'))

    with self.argument_context('role definition') as c:
        c.argument('role_definition_id', options_list=['--name', '-n'], help='the role definition name')
        c.argument('custom_role_only', arg_type=get_three_state_flag(), help='custom roles only(vs. build-in ones)')
        c.argument('role_definition', help="json formatted content which defines the new role.")
        c.argument('name', arg_type=name_arg_type, completer=get_role_definition_name_completion_list, help="the role's name")
コード例 #13
0
ファイル: _params.py プロジェクト: mevtorres/Azure-CLI
def load_arguments_eh(self, _):
    from knack.arguments import CLIArgumentType
    from azure.mgmt.eventhub.models import KeyType, AccessRights, SkuName
    from azure.cli.command_modules.eventhubs._completers import get_consumergroup_command_completion_list, get_eventhubs_command_completion_list
    from azure.cli.command_modules.eventhubs._validator import validate_storageaccount, validate_partner_namespace

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

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

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

    with self.argument_context('eventhubs namespace') as c:
        c.argument('namespace_name',
                   arg_type=name_type,
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.ServiceBus/namespaces'),
                   help='Name of Namespace')
        c.argument(
            'is_kafka_enabled',
            options_list=['--enable-kafka'],
            arg_type=get_three_state_flag(),
            help=
            'A boolean value that indicates whether Kafka is enabled for eventhub namespace.'
        )

    with self.argument_context('eventhubs namespace create') as c:
        c.argument('tags', arg_type=tags_type)
        c.argument('sku',
                   options_list=['--sku'],
                   arg_type=get_enum_type(SkuName))
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('capacity', type=int, help='Capacity for Sku')
        c.argument(
            'is_auto_inflate_enabled',
            options_list=['--enable-auto-inflate'],
            arg_type=get_three_state_flag(),
            help=
            'A boolean value that indicates whether AutoInflate is enabled for eventhub namespace.'
        )
        c.argument(
            'maximum_throughput_units',
            type=int,
            help=
            'Upper limit of throughput units when AutoInflate is enabled, vaule should be within 0 to 20 throughput units. ( 0 if AutoInflateEnabled = true)'
        )

    with self.argument_context('eventhubs namespace update') as c:
        c.argument('tags', arg_type=tags_type)
        c.argument('sku',
                   options_list=['--sku'],
                   arg_type=get_enum_type(SkuName))
        c.argument('capacity', type=int, help='Capacity for Sku')
        c.argument(
            'is_auto_inflate_enabled',
            options_list=['--enable-auto-inflate'],
            arg_type=get_three_state_flag(),
            help=
            'A boolean value that indicates whether AutoInflate is enabled for eventhub namespace.'
        )
        c.argument(
            'maximum_throughput_units',
            type=int,
            help=
            'Upper limit of throughput units when AutoInflate is enabled, vaule should be within 0 to 20 throughput units. ( 0 if AutoInflateEnabled = true)'
        )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context(
            'eventhubs georecovery-alias authorization-rule keys list') as c:
        c.argument('alias',
                   options_list=['--alias', '-a'],
                   id_part=None,
                   help='Name of Geo-Disaster Recovery Configuration Alias')
        c.argument('namespace_name',
                   options_list=['--namespace-name'],
                   id_part=None,
                   help='Name of Namespace')
        c.argument('authorization_rule_name',
                   arg_type=name_type,
                   help='Name of Namespace AuthorizationRule')
コード例 #14
0
ファイル: _params.py プロジェクト: xinity/azure-cli
def load_arguments(self, _):

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

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

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

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

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

# SQL database
    with self.argument_context('cosmosdb sql database') as c:
        c.argument('account_name', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", id_part=None)
        c.argument('database_name', options_list=['--database-name', '-d'], help="Database name")
        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')

# MongoDB
    with self.argument_context('cosmosdb mongodb database') as c:
        c.argument('account_name', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", id_part=None)
        c.argument('database_name', options_list=['--database-name', '-d'], help="Database name")
        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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", id_part=None)
        c.argument('database_name', options_list=['--database-name', '-d'], help="Database name")
        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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", id_part=None)
        c.argument('database_name', options_list=['--database-name', '-d'], help="Database name")
        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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", id_part=None)
        c.argument('database_name', options_list=['--database-name', '-d'], help="Database name")
        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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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', options_list=['--account-name', '-a'], help="Cosmosdb account name", id_part=None)
        c.argument('database_name', options_list=['--database-name', '-d'], help="Database name")
        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', options_list=['--account-name', '-a'], help="Cosmosdb account name", 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).')
コード例 #15
0
ファイル: _params.py プロジェクト: yugangw-msft/azure-cli
def load_arguments(self, _):
    StorageAccountTypes, UpgradeMode, CachingTypes = self.get_models('StorageAccountTypes', 'UpgradeMode', 'CachingTypes')
    OperatingSystemTypes = self.get_models('OperatingSystemTypes')

    # REUSABLE ARGUMENT DEFINITIONS
    name_arg_type = CLIArgumentType(options_list=['--name', '-n'], metavar='NAME')
    multi_ids_type = CLIArgumentType(nargs='+')
    existing_vm_name = CLIArgumentType(overrides=name_arg_type,
                                       configured_default='vm',
                                       help="The name of the Virtual Machine. You can configure the default using `az configure --defaults vm=<name>`",
                                       completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachines'), id_part='name')
    existing_disk_name = CLIArgumentType(overrides=name_arg_type, help='The name of the managed disk', completer=get_resource_name_completion_list('Microsoft.Compute/disks'), id_part='name')
    existing_snapshot_name = CLIArgumentType(overrides=name_arg_type, help='The name of the snapshot', completer=get_resource_name_completion_list('Microsoft.Compute/snapshots'), id_part='name')
    vmss_name_type = CLIArgumentType(name_arg_type,
                                     configured_default='vmss',
                                     completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'),
                                     help="Scale set name. You can configure the default using `az configure --defaults vmss=<name>`",
                                     id_part='name')

    extension_instance_name_type = CLIArgumentType(help="Name of the vm's instance of the extension. Default: name of the extension.")

    if StorageAccountTypes:
        disk_sku = CLIArgumentType(arg_type=get_enum_type(StorageAccountTypes))
    else:
        # StorageAccountTypes introduced in api version 2016_04_30_preview of Resource.MGMT.Compute package..
        # However, 2017-03-09-profile targets version 2016-03-30 of compute package.
        disk_sku = CLIArgumentType(arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS']))

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

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

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

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

    # region Disks
    with self.argument_context('disk') as c:
        c.argument('zone', zone_type, min_api='2017-03-30', options_list=['--zone'])  # TODO: --size-gb currently has claimed -z. We can do a breaking change later if we want to.
        c.argument('disk_name', existing_disk_name, completer=get_resource_name_completion_list('Microsoft.Compute/disks'))
        c.argument('name', arg_type=name_arg_type)
        c.argument('sku', arg_type=disk_sku, help='Underlying storage SKU')
        c.argument('os_type', arg_type=get_enum_type(OperatingSystemTypes), help='The Operating System type of the Disk.')
        c.argument('disk_iops_read_write', type=int, min_api='2018-06-01', help='The number of IOPS allowed for this disk. Only settable for UltraSSD disks. One operation can transfer between 4k and 256k bytes')
        c.argument('disk_mbps_read_write', type=int, min_api='2018-06-01', help="The bandwidth allowed for this disk. Only settable for UltraSSD disks. MBps means millions of bytes per second with ISO notation of powers of 10")
    # endregion

    # region Snapshots
    with self.argument_context('snapshot', resource_type=ResourceType.MGMT_COMPUTE, operation_group='snapshots') as c:
        c.argument('snapshot_name', existing_snapshot_name, id_part='name', completer=get_resource_name_completion_list('Microsoft.Compute/snapshots'))
        c.argument('name', arg_type=name_arg_type)
        if self.supported_api_version(min_api='2018-04-01', operation_group='snapshots'):
            c.argument('sku', arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS', 'Standard_ZRS']))
        else:
            c.argument('sku', arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS']))
    # endregion

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

    with self.argument_context('image create') as c:
        # here we collpase all difference image sources to under 2 common arguments --os-disk-source --data-disk-sources
        c.argument('name', arg_type=name_arg_type, help='new image name')
        c.argument('source', help='OS disk source from the same region, including a virtual machine ID or name, OS disk blob URI, managed OS disk ID or name, or OS snapshot ID or name')
        c.argument('data_disk_sources', nargs='+', help='Space-separated list of data disk sources, including unmanaged blob URI, managed disk ID or name, or snapshot ID or name')
        c.argument('zone_resilient', min_api='2017-12-01', arg_type=get_three_state_flag(), help='Specifies whether an image is zone resilient or not. '
                   'Default is false. Zone resilient images can be created only in regions that provide Zone Redundant Storage')
        c.argument('storage_sku', arg_type=disk_sku, help='The SKU of the storage account with which to create the VM image. Unused if source VM is specified.')
        c.argument('os_disk_caching', arg_type=get_enum_type(CachingTypes), help="Storage caching type for the image's OS disk.")
        c.ignore('source_virtual_machine', 'os_blob_uri', 'os_disk', 'os_snapshot', 'data_blob_uris', 'data_disks', 'data_snapshots')
    # endregion

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

    with self.argument_context('vm availability-set create') as c:
        c.argument('availability_set_name', name_arg_type, validator=get_default_location_from_resource_group, help='Name of the availability set')
        c.argument('platform_update_domain_count', type=int, help='Update Domain count. If unspecified, the server will pick the most optimal number like 5.')
        c.argument('platform_fault_domain_count', type=int, help='Fault Domain count.')
        c.argument('validate', help='Generate and validate the ARM template without creating any resources.', action='store_true')
        c.argument('unmanaged', action='store_true', min_api='2016-04-30-preview', help='contained VMs should use unmanaged disks')

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

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

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

    with self.argument_context('vm update') as c:
        c.argument('os_disk', min_api='2017-12-01', help="Managed OS disk ID or name to swap to")
        c.argument('write_accelerator', nargs='*', min_api='2017-12-01',
                   help="enable/disable disk write accelerator. Use singular value 'true/false' to apply across, or specify individual disks, e.g.'os=true 1=true 2=true' for os disk and data disks with lun of 1 & 2")
        c.argument('disk_caching', nargs='*', help="Use singular value to apply across, or specify individual disks, e.g. 'os=ReadWrite 0=None 1=ReadOnly' should enable update os disk and 2 data disks")

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

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

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

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

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

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

    with self.argument_context('vm disk attach') as c:
        c.argument('enable_write_accelerator', min_api='2017-12-01', action='store_true', help='enable write accelerator')
        c.argument('disk', options_list=['--name', '-n', c.deprecate(target='--disk', redirect='--name', hide=True)],
                   help="The name or ID of the managed disk", validator=validate_vm_disk, id_part='name',
                   completer=get_resource_name_completion_list('Microsoft.Compute/disks'))

    with self.argument_context('vm disk detach') as c:
        c.argument('disk_name', arg_type=name_arg_type, help='The data disk name.')

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

    with self.argument_context('vm extension') as c:
        c.argument('vm_extension_name', name_arg_type, completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachines/extensions'), help='Name of the extension.', id_part='child_name_1')
        c.argument('vm_name', arg_type=existing_vm_name, options_list=['--vm-name'], id_part='name')
        c.argument('expand', deprecate_info=c.deprecate(expiration='2.1.0', hide=True))

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

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

    with self.argument_context('vm secret list') as c:
        c.argument('vm_name', arg_type=existing_vm_name, id_part=None)

    with self.argument_context('vm image') as c:
        c.argument('publisher_name', options_list=['--publisher', '-p'])
        c.argument('publisher', options_list=['--publisher', '-p'], help='image publisher')
        c.argument('offer', options_list=['--offer', '-f'], help='image offer')
        c.argument('plan', help='image billing plan')
        c.argument('sku', options_list=['--sku', '-s'], help='image sku')
        c.argument('version', help="image sku's version")
        c.argument('urn', help="URN, in format of 'publisher:offer:sku:version'. If specified, other argument values can be omitted")

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

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

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

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

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

    with self.argument_context('vm unmanaged-disk attach') as c:
        c.argument('disk_name', options_list=['--name', '-n'], help='The data disk name.')
        c.argument('size_gb', options_list=['--size-gb', '-z'], help='size in GB. Max size: 4095 GB (certain preview disks can be larger).', type=int)

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

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

    with self.argument_context('vm unmanaged-disk list') as c:
        c.argument('vm_name', options_list=['--vm-name', '--name', '-n'], arg_type=existing_vm_name, id_part=None)

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

    with self.argument_context('vm list-skus') as c:
        c.argument('size', options_list=['--size', '-s'], help="size name, partial name is accepted")
        c.argument('zone', options_list=['--zone', '-z'], arg_type=get_three_state_flag(), help="show all vm size supporting availability zones")
        c.argument('show_all', options_list=['--all'], arg_type=get_three_state_flag(),
                   help="show all information including vm sizes not available under the current subscription")
        c.argument('resource_type', options_list=['--resource-type', '-r'], help='resource types e.g. "availabilitySets", "snapshots", "disk", etc')

    with self.argument_context('vm restart') as c:
        c.argument('force', action='store_true', help='Force the VM to restart by redeploying it. Use if the VM is unresponsive.')
    # endregion

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

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

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

    with self.argument_context('vmss create') as c:
        VMPriorityTypes = self.get_models('VirtualMachinePriorityTypes', resource_type=ResourceType.MGMT_COMPUTE)
        VirtualMachineEvictionPolicyTypes = self.get_models('VirtualMachineEvictionPolicyTypes', resource_type=ResourceType.MGMT_COMPUTE)
        c.argument('name', name_arg_type)
        c.argument('nat_backend_port', default=None, help='Backend port to open with NAT rules.  Defaults to 22 on Linux and 3389 on Windows.')
        c.argument('single_placement_group', arg_type=get_three_state_flag(), help="Enable replicate using fault domains within the same cluster. Default to 'false' for any zonals, or with 100+ instances"
                   " See https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-placement-groups for details")
        c.argument('platform_fault_domain_count', type=int, help='Fault Domain count for each placement group in the availability zone', min_api='2017-12-01')
        c.argument('vmss_name', name_arg_type, id_part=None, help='Name of the virtual machine scale set.')
        c.argument('instance_count', help='Number of VMs in the scale set.', type=int)
        c.argument('disable_overprovision', help='Overprovision option (see https://azure.microsoft.com/en-us/documentation/articles/virtual-machine-scale-sets-overview/ for details).', action='store_true')
        c.argument('upgrade_policy_mode', help=None, arg_type=get_enum_type(UpgradeMode))
        c.argument('health_probe', help='(Preview) probe name from the existing load balancer, mainly used for rolling upgrade')
        c.argument('vm_sku', help='Size of VMs in the scale set. Default to "Standard_DS1_v2". See https://azure.microsoft.com/en-us/pricing/details/virtual-machines/ for size info.')
        c.argument('nsg', help='Name or ID of an existing Network Security Group.', arg_group='Network')
        c.argument('priority', resource_type=ResourceType.MGMT_COMPUTE, min_api='2017-12-01', arg_type=get_enum_type(VMPriorityTypes, default=None),
                   help="Priority. Use 'Low' to run short-lived workloads in a cost-effective way")
        c.argument('eviction_policy', resource_type=ResourceType.MGMT_COMPUTE, min_api='2017-12-01', arg_type=get_enum_type(VirtualMachineEvictionPolicyTypes, default=None),
                   help="(PREVIEW) The eviction policy for virtual machines in a low priority scale set.")
        c.argument('application_security_groups', resource_type=ResourceType.MGMT_COMPUTE, min_api='2018-06-01', nargs='+', options_list=['--asgs'], help='Space-separated list of existing application security groups to associate with the VM.', arg_group='Network', validator=validate_asg_names_or_ids)

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

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

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

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

    with self.argument_context('vmss disk') as c:
        options_list = ['--vmss-name'] + [c.deprecate(target=opt, redirect='--vmss-name', hide=True)for opt in name_arg_type.settings['options_list']]
        new_vmss_name_type = CLIArgumentType(overrides=vmss_name_type, options_list=options_list)

        c.argument('lun', type=int, help='0-based logical unit number (LUN). Max value depends on the Virtual Machine instance size.')
        c.argument('size_gb', options_list=['--size-gb', '-z'], help='size in GB. Max size: 4095 GB (certain preview disks can be larger).', type=int)
        c.argument('vmss_name', new_vmss_name_type, completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'))
        c.argument('disk', validator=validate_vmss_disk, help='existing disk name or ID to attach or detach from VM instances',
                   min_api='2017-12-01', completer=get_resource_name_completion_list('Microsoft.Compute/disks'))
        c.argument('instance_id', help='Scale set VM instance id', min_api='2017-12-01')
        c.argument('sku', arg_type=disk_sku, help='Underlying storage SKU')

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

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

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

    with self.argument_context('vmss nic list') as c:
        c.argument('virtual_machine_scale_set_name', arg_type=vmss_name_type, options_list=['--vmss-name'], id_part=None)
    # endregion

    # region VM & VMSS Shared
    for scope in ['vm', 'vmss']:
        with self.argument_context(scope) as c:
            c.argument('no_auto_upgrade', arg_type=get_three_state_flag(), help='If set, the extension service will not automatically pick or upgrade to the latest minor version, even if the extension is redeployed.')

        with self.argument_context('{} run-command'.format(scope)) as c:
            c.argument('command_id', completer=get_vm_run_command_completion_list, help="The command id. Use 'az {} run-command list' to get the list".format(scope))
            if scope == 'vmss':
                c.argument('vmss_name', vmss_name_type)

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

    for scope in ['vm identity assign', 'vmss identity assign']:
        with self.argument_context(scope) as c:
            c.argument('assign_identity', options_list=['--identities'], nargs='*', help="Space-separated identities to assign. Use '{0}' to refer to the system assigned identity. Default: '{0}'".format(MSI_LOCAL_ID))
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

    for scope in ['vm identity remove', 'vmss identity remove']:
        with self.argument_context(scope) as c:
            c.argument('identities', nargs='+', help="Space-separated identities to remove. Use '{0}' to refer to the system assigned identity. Default: '{0}'".format(MSI_LOCAL_ID))
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

    for scope in ['vm identity show', 'vmss identity show']:
        with self.argument_context(scope) as c:
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

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

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

        with self.argument_context(scope, arg_group='Storage') as c:
            if StorageAccountTypes:
                allowed_values = ", ".join([sku.value for sku in StorageAccountTypes])
            else:
                allowed_values = ", ".join(['Premium_LRS', 'Standard_LRS'])

            usage = 'Usage: [--storage-sku SKU | --storage-sku ID=SKU ID=SKU ID=SKU...], where each ID is "os" or a 0-indexed lun.'
            allowed_values = 'Allowed values: {}.'.format(allowed_values)
            storage_sku_help = 'The SKU of the storage account with which to persist VM. Use a singular sku that would be applied across all disks, ' \
                               'or specify individual disks. {} {}'.format(usage, allowed_values)

            c.argument('os_disk_name', help='The name of the new VM OS disk.')
            c.argument('os_type', help='Type of OS installed on a custom VHD. Do not use when specifying an URN or URN alias.', arg_type=get_enum_type(['windows', 'linux']))
            c.argument('storage_account', help="Only applicable when used with `--use-unmanaged-disk`. The name to use when creating a new storage account or referencing an existing one. If omitted, an appropriate storage account in the same resource group and location will be used, or a new one will be created.")
            c.argument('storage_sku', nargs='+', help=storage_sku_help)
            c.argument('storage_container_name', help="Only applicable when used with `--use-unmanaged-disk`. Name of the storage container for the VM OS disk. Default: vhds")
            c.ignore('os_publisher', 'os_offer', 'os_sku', 'os_version', 'storage_profile')
            c.argument('use_unmanaged_disk', action='store_true', help='Do not use managed disk to persist VM')
            c.argument('data_disk_sizes_gb', nargs='+', type=int, help='space-separated empty managed data disk sizes in GB to create')
            c.ignore('disk_info', 'storage_account_type', 'public_ip_address_type', 'nsg_type', 'nic_type', 'vnet_type', 'load_balancer_type', 'app_gateway_type')
            c.argument('os_caching', options_list=[self.deprecate(target='--storage-caching', redirect='--os-disk-caching', hide=True), '--os-disk-caching'], help='Storage caching type for the VM OS disk. Default: ReadWrite', arg_type=get_enum_type(CachingTypes))
            c.argument('data_caching', options_list=['--data-disk-caching'], nargs='+',
                       help="storage caching type for data disk(s), including 'None', 'ReadOnly', 'ReadWrite', etc. Use a singular value to apply on all disks, or use '<lun>=<vaule1> <lun>=<value2>' to configure individual disk")
            c.argument('ultra_ssd_enabled', arg_type=get_three_state_flag(), min_api='2018-06-01',
                       help='(PREVIEW) Enables or disables the capability to have 1 or more managed data disks with UltraSSD_LRS storage account')
            c.argument('ephemeral_os_disk', arg_type=get_three_state_flag(), min_api='2018-06-01',
                       help='(Preview) Allows you to create an OS disk directly on the host node, providing local disk performance and faster VM/VMSS reimage time.')

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

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

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

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

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

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

    with self.argument_context('vm extension set') as c:
        c.argument('force_update', action='store_true', help='force to update even if the extension configuration has not changed.')
        c.argument('extension_instance_name', extension_instance_name_type, arg_group='Resource Id')

    with self.argument_context('vmss extension set', min_api='2017-12-01') as c:
        c.argument('force_update', action='store_true', help='force to update even if the extension configuration has not changed.')
        c.argument('extension_instance_name', extension_instance_name_type)
        c.argument('provision_after_extensions', nargs='+', help='Space-separated list of extension names after which this extension should be provisioned. These extensions must already be set on the vm.')

    for scope in ['vm extension image', 'vmss extension image']:
        with self.argument_context(scope) as c:
            c.argument('image_location', options_list=['--location', '-l'], help='Image location.')
            c.argument('name', help='Image name', id_part=None)
            c.argument('publisher_name', options_list=['--publisher', '-p'], help='Image publisher name')
            c.argument('type', options_list=['--name', '-n'], help='Name of the extension')
            c.argument('latest', action='store_true', help='Show the latest version only.')
            c.argument('version', help='Extension version')
            c.argument('orderby', help="the $orderby odata query option")
            c.argument('top', help='the $top odata query option')

    for scope in ['vm create', 'vm update', 'vmss create', 'vmss update']:
        with self.argument_context(scope) as c:
            license_msg = "Specifies that the Windows image or disk was licensed on-premises. " \
                          "To enable Azure Hybrid Benefit for Windows Server, use 'Windows_Server'. " \
                          "To enable Multitenant Hosting Rights for Windows 10, use 'Windows_Client'. " \
                          "For more information see the Azure Windows VM online docs."
            c.argument('license_type', help=license_msg, arg_type=get_enum_type(['Windows_Server', 'Windows_Client', 'None']))

    with self.argument_context('sig') as c:
        c.argument('gallery_name', options_list=['--gallery-name', '-r'], help='gallery name')
        c.argument('gallery_image_name', options_list=['--gallery-image-definition', '-i'], help='gallery image definition')
        c.argument('gallery_image_version', options_list=['--gallery-image-version', '-e'], help='gallery image version')

    for scope in ['sig show', 'sig image-definition show', 'sig image-definition delete']:
        with self.argument_context(scope) as c:
            c.argument('gallery_name', options_list=['--gallery-name', '-r'], id_part='name', help='gallery name')
            c.argument('gallery_image_name', options_list=['--gallery-image-definition', '-i'], id_part='child_name_1', help='gallery image definition')

    with self.argument_context('sig image-definition create') as c:
        c.argument('offer', options_list=['--offer', '-f'], help='image offer')
        c.argument('sku', options_list=['--sku', '-s'], help='image sku')
        c.argument('publisher', options_list=['--publisher', '-p'], help='image publisher')
        c.argument('os_type', arg_type=get_enum_type(['Windows', 'Linux']), help='the type of the OS that is included in the disk if creating a VM from user-image or a specialized VHD')
        c.ignore('os_state')  # service is not ready
        c.argument('minimum_cpu_core', type=int, arg_group='Recommendation', help='minimum cpu cores')
        c.argument('maximum_cpu_core', type=int, arg_group='Recommendation', help='maximum cpu cores')
        c.argument('minimum_memory', type=int, arg_group='Recommendation', help='minimum memory in MB')
        c.argument('maximum_memory', type=int, arg_group='Recommendation', help='maximum memory in MB')

        c.argument('plan_publisher', help='plan publisher', arg_group='Purchase plan')
        c.argument('plan_name', help='plan name', arg_group='Purchase plan')
        c.argument('plan_product', help='plan product', arg_group='Purchase plan')

        c.argument('eula', help='The Eula agreement for the gallery image')
        c.argument('privacy_statement_uri', help='The privacy statement uri')
        c.argument('release_note_uri', help='The release note uri')
        c.argument('end_of_life_date', help="the end of life date, e.g. '2020-12-31'")
        c.argument('disallowed_disk_types', nargs='*', help='disk types which would not work with the image, e.g., Standard_LRS')

    with self.argument_context('sig create') as c:
        c.argument('description', help='the description of the gallery')
    with self.argument_context('sig update') as c:
        c.ignore('gallery')
    with self.argument_context('sig image-definition create') as c:
        c.argument('description', help='the description of the gallery image definition')
    with self.argument_context('sig image-definition update') as c:
        c.ignore('gallery_image')

    with self.argument_context('sig image-version') as c:
        deprecated_option = c.deprecate(target='--gallery-image-version-name', redirect='--gallery-image-version', hide=True, expiration="2.1.0")
        c.argument('gallery_image_version_name', options_list=['--gallery-image-version', '-e', deprecated_option], )

    with self.argument_context('sig image-version create') as c:
        c.argument('gallery_image_version', options_list=['--gallery-image-version', '-e'],
                   help='Gallery image version in semantic version pattern. The allowed characters are digit and period. Digits must be within the range of a 32-bit integer, e.g. <MajorVersion>.<MinorVersion>.<Patch>')
        c.argument('description', help='the description of the gallery image version')
        c.argument('managed_image', help='image name(if in the same resource group) or resource id')
        c.argument('exclude_from_latest', arg_type=get_three_state_flag(), help='The flag means that if it is set to true, people deploying VMs with version omitted will not use this version.')
        c.argument('version', help='image version')
        c.argument('end_of_life_date', help="the end of life date, e.g. '2020-12-31'")

    with self.argument_context('sig image-version show') as c:
        c.argument('expand', help="The expand expression to apply on the operation, e.g. 'ReplicationStatus'")
    for scope in ['sig image-version create', 'sig image-version update']:
        with self.argument_context(scope) as c:
            c.argument('target_regions', nargs='*', validator=process_gallery_image_version_namespace,
                       help='Space-separated list of regions and their replica counts. Use "<region>=<replica count>" to set the replica count for each region. If only the region is specified, the default replica count will be used.')
            c.argument('replica_count', help='The default number of replicas to be created per region. To set regional replication counts, use --target-regions', type=int)
コード例 #16
0
def load_arguments(self, _):
    with self.argument_context("k8s-configuration") as c:
        c.argument("tags", tags_type)
        c.argument("location",
                   validator=get_default_location_from_resource_group)
        c.argument(
            "cluster_name",
            options_list=["--cluster-name", "-c"],
            help="Name of the Kubernetes cluster",
        )
        c.argument(
            "cluster_type",
            options_list=["--cluster-type", "-t"],
            arg_type=get_enum_type(["connectedClusters", "managedClusters"]),
            help="Specify Arc connected clusters or AKS managed clusters.",
        )

    with self.argument_context("k8s-configuration flux") as c:
        c.argument(
            "name",
            options_list=["--name", "-n"],
            help="Name of the flux configuration",
            validator=validate_fluxconfig_name,
        )
        c.argument(
            "scope",
            options_list=["--scope", "-s"],
            arg_type=get_enum_type(["namespace", "cluster"]),
            help="Specify scope of the operator to be 'namespace' or 'cluster'",
        )
        c.argument(
            "namespace",
            help="Namespace to deploy the configuration",
            options_list=["--namespace", "--ns"],
            validator=validate_namespace,
        )
        c.argument(
            "kind",
            arg_type=get_enum_type([consts.GIT, consts.BUCKET]),
            help="Source kind to reconcile",
        )
        c.argument("url",
                   options_list=["--url", "-u"],
                   help="URL of the source to reconcile")
        c.argument(
            "timeout",
            help="Maximum time to reconcile the source before timing out")
        c.argument(
            "sync_interval",
            options_list=["--interval", "--sync-interval"],
            help="Time between reconciliations of the source on the cluster",
        )
        c.argument(
            "branch",
            arg_group="Git Repo Ref",
            help="Branch within the git source to reconcile with the cluster",
        )
        c.argument(
            "tag",
            arg_group="Git Repo Ref",
            help="Tag within the git source to reconcile with the cluster",
        )
        c.argument(
            "semver",
            arg_group="Git Repo Ref",
            help=
            "Semver range within the git source to reconcile with the cluster",
        )
        c.argument(
            "commit",
            arg_group="Git Repo Ref",
            help="Commit within the git source to reconcile with the cluster",
        )
        c.argument(
            "ssh_private_key",
            arg_group="Git Auth",
            help="Base64-encoded private ssh key for private repository sync",
        )
        c.argument(
            "ssh_private_key_file",
            arg_group="Git Auth",
            help="File path to private ssh key for private repository sync",
        )
        c.argument(
            "https_user",
            arg_group="Git Auth",
            help="HTTPS username for private repository sync",
        )
        c.argument(
            "https_key",
            arg_group="Git Auth",
            help="HTTPS token/password for private repository sync",
        )
        c.argument(
            "https_ca_cert",
            arg_group="Git Auth",
            help=
            "Base64-encoded HTTPS CA certificate for TLS communication with private repository sync",
        )
        c.argument(
            "https_ca_cert_file",
            arg_group="Git Auth",
            help=
            "File path to HTTPS CA certificate file for TLS communication with private repository sync",
        )
        c.argument(
            "known_hosts",
            arg_group="Git Auth",
            help=
            "Base64-encoded known_hosts data containing public SSH keys required to access private Git instances",
        )
        c.argument(
            "known_hosts_file",
            arg_group="Git Auth",
            help=
            "File path to known_hosts contents containing public SSH keys required to access private Git instances",
        )
        c.argument(
            "bucket_access_key",
            arg_group="Bucket Auth",
            help="Access Key ID used to authenticate with the bucket",
        )
        c.argument(
            "bucket_secret_key",
            arg_group="Bucket Auth",
            help="Secret Key used to authenticate with the bucket",
        )
        c.argument(
            "bucket_name",
            help="Name of the S3 bucket to sync",
        )
        c.argument(
            "bucket_insecure",
            arg_type=get_three_state_flag(),
            help="Communicate with a bucket without TLS",
        )
        c.argument(
            "local_auth_ref",
            arg_group="Auth",
            options_list=["--local-auth-ref", "--local-ref"],
            help=
            "Local reference to a kubernetes secret in the configuration namespace to use for communication to the source",
        )
        c.argument(
            "suspend",
            arg_type=get_three_state_flag(),
            help=
            "Suspend the reconciliation of the source and kustomizations associated with this configuration",
        )
        c.argument(
            "kustomization",
            action=KustomizationAddAction,
            options_list=["--kustomization", "-k"],
            help=
            "Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'force']",
            nargs="+",
        )

    with self.argument_context("k8s-configuration flux update") as c:
        c.argument("yes",
                   options_list=["--yes", "-y"],
                   help="Do not prompt for confirmation")

    with self.argument_context("k8s-configuration flux delete") as c:
        c.argument(
            "force",
            arg_type=get_three_state_flag(),
            help="Force delete the flux configuration from the cluster.",
        )
        c.argument("yes",
                   options_list=["--yes", "-y"],
                   help="Do not prompt for confirmation")

    with self.argument_context(
            "k8s-configuration flux deployed-object show") as c:
        c.argument(
            "object_name",
            help=
            "Name of the object deployed by the configuration on the cluster.",
        )
        c.argument(
            "object_namespace",
            help=
            "Namespace of the object deployed by the configuration on the cluster.",
        )
        c.argument(
            "object_kind",
            arg_type=get_enum_type([
                "GitRepository",
                "Bucket",
                "HelmRepository",
                "HelmChart",
                "HelmRelease",
                "Kustomization",
            ]),
            help=
            "Kind of the object deployed by the configuration on the cluster.",
        )

    with self.argument_context("k8s-configuration") as c:
        c.argument(
            "name",
            options_list=["--name", "-n"],
            help="Name of the configuration",
            validator=validate_configuration_name,
        )

    with self.argument_context("k8s-configuration create") as c:
        c.argument(
            "repository_url",
            options_list=["--repository-url", "-u"],
            help="Url of the source control repository",
        )
        c.argument(
            "scope",
            arg_type=get_enum_type(["namespace", "cluster"]),
            help=
            """Specify scope of the operator to be 'namespace' or 'cluster' """,
        )
        c.argument(
            "enable_helm_operator",
            arg_group="Helm Operator",
            arg_type=get_three_state_flag(),
            options_list=["--enable-helm-operator", "--enable-hop"],
            help="Enable support for Helm chart deployments",
        )
        c.argument(
            "helm_operator_params",
            arg_group="Helm Operator",
            options_list=["--helm-operator-params", "--hop-params"],
            help="Chart values for the Helm Operator (if enabled)",
        )
        c.argument(
            "helm_operator_chart_version",
            arg_group="Helm Operator",
            options_list=[
                "--helm-operator-chart-version", "--hop-chart-version"
            ],
            help="Chart version of the Helm Operator (if enabled)",
        )
        c.argument("operator_params",
                   arg_group="Operator",
                   help="Parameters for the Operator")
        c.argument(
            "operator_instance_name",
            arg_group="Operator",
            help="Instance name of the Operator",
            validator=validate_operator_instance_name,
        )
        c.argument(
            "operator_namespace",
            arg_group="Operator",
            help="Namespace in which to install the Operator",
            validator=validate_operator_namespace,
        )
        c.argument(
            "operator_type",
            arg_group="Operator",
            help="""Type of the operator. Valid value is 'flux' """,
        )
        c.argument(
            "ssh_private_key",
            arg_group="Auth",
            help=
            "Specify Base64-encoded private ssh key for private repository sync",
        )
        c.argument(
            "ssh_private_key_file",
            arg_group="Auth",
            help=
            "Specify file path to private ssh key for private repository sync",
        )
        c.argument(
            "https_user",
            arg_group="Auth",
            help="Specify HTTPS username for private repository sync",
        )
        c.argument(
            "https_key",
            arg_group="Auth",
            help="Specify HTTPS token/password for private repository sync",
        )
        c.argument(
            "ssh_known_hosts",
            arg_group="Auth",
            help=
            "Specify Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances",
        )
        c.argument(
            "ssh_known_hosts_file",
            arg_group="Auth",
            help=
            "Specify file path to known_hosts contents containing public SSH keys required to access private Git instances",
        )

    with self.argument_context("k8s-configuration flux kustomization") as c:
        c.argument(
            "kustomization_name",
            options_list=["--kustomization-name", "-k"],
            help="Specify the name of the kustomization to target",
        )
        c.argument(
            "path",
            help=
            "Specify the path in the source that the kustomization should apply",
        )
        c.argument(
            "dependencies",
            options_list=["--depends", "--dependencies", "--depends-on"],
            help="Comma-separated list of kustomization dependencies",
        )
        c.argument(
            "timeout",
            help=
            "Maximum time to reconcile the kustomization before timing out",
        )
        c.argument(
            "sync_interval",
            options_list=["--interval", "--sync-interval"],
            help=
            "Time between reconciliations of the kustomization on the cluster",
        )
        c.argument(
            "retry_interval",
            help=
            "Time between reconciliations of the kustomization on the cluster on failures, defaults to --sync-interval",
        )
        c.argument(
            "prune",
            arg_type=get_three_state_flag(),
            help=
            "Garbage collect resources deployed by the kustomization on the cluster",
        )
        c.argument(
            "force",
            arg_type=get_three_state_flag(),
            help=
            "Re-create resources that cannot be updated on the cluster (i.e. jobs)",
        )

    with self.argument_context(
            "k8s-configuration flux kustomization delete") as c:
        c.argument("yes",
                   options_list=["--yes", "-y"],
                   help="Do not prompt for confirmation")
コード例 #17
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.')

    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 (low) to 4 (high).')
        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='2.1.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='2.1.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)

    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')
コード例 #18
0
ファイル: _params.py プロジェクト: yorek/azure-cli
def load_arguments(self, _):  # pylint: disable=too-many-statements

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    for scope in [
            'mariadb server configuration', 'mysql server configuration',
            'postgres server configuration'
    ]:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('configuration_name',
                       id_part='child_name_1',
                       options_list=['--name', '-n'])
コード例 #19
0
ファイル: _params.py プロジェクト: derekbekoe/azure-cli
def load_arguments(self, _):
    from azure.mgmt.monitor.models.monitor_management_client_enums import ConditionOperator, TimeAggregationOperator

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

    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=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 .validators import (process_metric_timespan, process_metric_aggregation, process_metric_result_type,
                                 process_metric_dimension, validate_metric_names)
        from azure.mgmt.monitor.models.monitor_management_client_enums import AggregationType
        c.resource_parameter('resource_uri', arg_group='Target Resource')
        c.extra('start_time', options_list=['--start-time'], validator=process_metric_timespan, arg_group='Time')
        c.extra('end_time', options_list=['--end-time'], arg_group='Time')
        c.extra('metadata', options_list=['--metadata'], action='store_true', validator=process_metric_result_type)
        c.extra('dimension', options_list=['--dimension'], nargs='*', validator=process_metric_dimension)
        c.argument('interval', arg_group='Time')
        c.argument('aggregation', arg_type=get_enum_type(t for t in AggregationType if t.name != 'none'), nargs='*', validator=process_metric_aggregation)
        c.argument('metricnames', options_list=['--metrics'], nargs='+', help='Space-separated list of metric names to retrieve.', validator=validate_metric_names)
        c.ignore('timespan', 'result_type')
    # 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:
        c.argument('select', nargs='+')

    with self.argument_context('monitor activity-log list', arg_group='OData Filter') as c:
        c.argument('correlation_id')
        c.argument('resource_group')
        c.argument('resource_id')
        c.argument('resource_provider')
        c.argument('start_time')
        c.argument('end_time')
        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='+')
コード例 #20
0
def load_arguments(self, _):
    with self.argument_context('bot') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('resource_name',
                   options_list=['--name', '-n'],
                   help='The resource name of the bot.',
                   arg_type=name_arg_type)

    with self.argument_context('bot create') as c:
        c.argument('sku_name',
                   options_list=['--sku'],
                   arg_type=get_enum_type(['F0', 'S1']),
                   help='The Sku of the bot.',
                   arg_group='Registration bot Specific')
        c.argument('kind',
                   options_list=['--kind', '-k'],
                   arg_type=get_enum_type(
                       ['registration', 'function', 'webapp']),
                   help='The kind of the bot.')
        c.argument(
            'display_name',
            help=
            'The display name of the bot. If not specified, defaults to the name of the bot.',
            arg_group='Registration bot Specific')
        c.argument('description',
                   options_list=['--description', '-d'],
                   help='The description of the bot.',
                   arg_group='Registration bot Specific')
        c.argument('endpoint',
                   options_list=['-e', '--endpoint'],
                   help='The messaging endpoint of the bot.',
                   arg_group='Registration bot Specific')
        c.argument(
            'msa_app_id',
            options_list=['--appid'],
            help='The Microsoft account ID (MSA ID) to be used with the bot.')
        c.argument('password',
                   options_list=['-p', '--password'],
                   help='The Microsoft account (MSA) password for the bot.')
        c.argument(
            'storageAccountName',
            options_list=['-s', '--storage'],
            help=
            'Storage account name to be used with the bot. If not provided, a new account will be created.',
            arg_group='Web/Function bot Specific')
        c.argument('tags', arg_type=tags_type)
        c.argument('language',
                   help='The language to be used to create the bot.',
                   options_list=['--lang'],
                   arg_type=get_enum_type(supported_languages),
                   arg_group='Web/Function bot Specific')
        c.argument(
            'appInsightsLocation',
            help='The location for the app insights to be used with the bot.',
            options_list=['--insights-location'],
            arg_group='Web/Function bot Specific',
            arg_type=get_enum_type([
                'South Central US', 'East US', 'West US 2', 'North Europe',
                'West Europe', 'Southeast Asia'
            ]))
        c.argument(
            'version',
            options_list=['-v', '--version'],
            help=
            'The Microsoft Bot Builder SDK version to be used to create the bot',
            arg_type=get_enum_type(['v3', 'v4']),
            arg_group='Web/Function bot Specific')

    with self.argument_context('bot publish') as c:
        c.argument('code_dir',
                   options_list=['--code-dir'],
                   help='The directory to upload bot code from.')
        c.argument('proj_name', help='Name of the start up project file name.')
        c.argument('version',
                   options_list=['-v', '--version'],
                   help='The Microsoft Bot Builder SDK version by the bot.')

    with self.argument_context('bot download') as c:
        c.argument('file_save_path',
                   options_list=['--save-path'],
                   help='The directory to download bot code to.')

    with self.argument_context('bot show') as c:
        c.argument('bot_json',
                   options_list=['--msbot'],
                   help='Show the output as JSON compatible with a .bot file.',
                   arg_type=get_three_state_flag())

    with self.argument_context('bot prepare-publish') as c:
        c.argument(
            'proj_name',
            help='Name of the start up project file name. Required only for C#.'
        )
        c.argument(
            'sln_name',
            help=
            'Name of the start up solution file name. Required only for C#.')
        c.argument('code_dir',
                   options_list=['--code-dir'],
                   help='The directory to download deployment scripts to.')
        c.argument('version',
                   options_list=['-v', '--version'],
                   help='The Microsoft Bot Builder SDK version to be used '
                   'in the bot template that will be created.',
                   arg_type=get_enum_type(['v3', 'v4']),
                   arg_group='Web/Function bot Specific')

    with self.argument_context('bot facebook create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state')
        c.argument('page_id',
                   options_list=['--page-id'],
                   help='Page ID of the Facebook page to be used for the bot.')
        c.argument('app_id',
                   options_list=['--appid'],
                   help='The Facebook application id.')
        c.argument('app_secret',
                   options_list=['--secret'],
                   help='The Facebook application secret.')
        c.argument('access_token',
                   options_list=['--token'],
                   help='The Facebook application access token.')

    with self.argument_context('bot email create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state')
        c.argument('email_address',
                   options_list=['--email-address', '-a'],
                   help='The email address for the bot.')
        c.argument('password',
                   options_list=['--password', '-p'],
                   help='The email password for the bot.')

    with self.argument_context('bot msteams create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state.')
        c.argument('enable_calling',
                   help='Enable calling on Microsoft Teams.',
                   arg_type=get_three_state_flag())
        c.argument('calling_web_hook',
                   help='The calling web hook to use on Microsoft Teams.')

    with self.argument_context('bot skype create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state.')
        c.argument('enable_messaging',
                   help='Enable messaging on Skype.',
                   arg_type=get_three_state_flag())
        c.argument('enable_media_cards',
                   help='Enable media cards on Skype.',
                   arg_type=get_three_state_flag())
        c.argument('enable_video',
                   help='Enable video on Skype.',
                   arg_type=get_three_state_flag())
        c.argument('enable_calling',
                   help='Enable calling on Skype.',
                   arg_type=get_three_state_flag())
        c.argument('enable_screen_sharing',
                   help='Enable screen sharing on Skype.',
                   arg_type=get_three_state_flag())
        c.argument('enable_groups',
                   help='Enable groups on Skype.',
                   arg_type=get_three_state_flag())
        c.argument('groups_mode', help='select groups mode on Skype.')
        c.argument('calling_web_hook',
                   help='The calling web hook to use on Skype.')

    with self.argument_context('bot kik create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state.')
        c.argument('user_name',
                   options_list=['--user-name', '-u'],
                   help='Kik user name.')
        c.argument(
            'is_validated',
            help=
            'Whether or not the Kik account has been validated for use with the bot.',
            arg_type=get_three_state_flag())
        c.argument('api_key',
                   options_list=['--key'],
                   help='The API key for the Kik account.')

    with self.argument_context('bot webchat create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state.')
        c.argument('site_name',
                   options_list=['-s', '--site-name'],
                   help='Name of the Webchat channel site.')
        c.argument('enable_preview',
                   help='Enable preview features on the chat control.',
                   arg_type=get_three_state_flag())

    with self.argument_context('bot directline create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state.')
        c.argument('site_name',
                   options_list=['-s', '--site-name'],
                   help='Name of the Directline channel site.')
        c.argument('is_v1_disabled',
                   options_list=['--disablev1'],
                   help='If true, v1 protocol will be disabled on the channel',
                   arg_type=get_three_state_flag())
        c.argument(
            'is_v3_disabled',
            options_list=['--disablev3'],
            help='If true, v3 protocol will be disabled on the channel.',
            arg_type=get_three_state_flag())

    with self.argument_context('bot telegram create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state.')
        c.argument('access_token',
                   help='The access token for the Telegram account.')
        c.argument(
            'is_validated',
            help=
            'Whether or not the Telegram account has been validated for use with the bot.',
            arg_type=get_three_state_flag())

    with self.argument_context('bot sms create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state.')
        c.argument('account_sid',
                   help='The account SID for the Twilio account.')
        c.argument('auth_token',
                   help='The token token for the Twilio account.')
        c.argument(
            'is_validated',
            help=
            'Whether or not the Twilio account has been validated for use with the bot.',
            arg_type=get_three_state_flag())
        c.argument('phone', help='The phone number for the Twilio account.')

    with self.argument_context('bot slack create') as c:
        c.argument('is_disabled',
                   options_list=['--add-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Add the channel in a disabled state.')
        c.argument('client_secret', help='The client secret from Slack.')
        c.argument('client_id', help='The client ID from Slack.')
        c.argument('verification_token',
                   help='The verification token from Slack.')
        c.argument('landing_page_url',
                   help='The landing page url to redirect to after login.')

    with self.argument_context('bot authsetting') as c:
        c.argument('connection_name',
                   options_list=['--setting-name', '-c'],
                   help='Name of the oauth connection setting.',
                   id_part='child_name_1')

    with self.argument_context('bot authsetting create') as c:
        c.argument(
            'client_id',
            help='Client ID associated with the service provider setting.')
        c.argument(
            'client_secret',
            help='Client secret associated with the service provider setting.')
        c.argument(
            'scopes',
            options_list=['--provider-scope-string'],
            help=
            'The scope string associated with the service provider setting.The string should be delimited as needed for the service provider.'
        )
        c.argument(
            'service_provider_name',
            options_list=['--service'],
            help=
            'Name of the service provider. For a list of all service providers, use `az bot connection listserviceproviders`.'
        )
        c.argument(
            'parameters',
            help=
            'Parameter values for service provider parameters. Usage: --parameters key=value key1=value1.',
            nargs='+')

    with self.argument_context('bot authsetting list-providers') as c:
        c.argument('as_raw_settings',
                   options_list=['--as-raw'],
                   help='Output the raw json for each service provider.',
                   arg_type=get_three_state_flag())
        c.argument('name',
                   options_list=['--provider-name'],
                   help='Service provider name for which to fetch details.')

    for channel in [
            'facebook', 'email', 'msteams', 'skype', 'kik', 'webchat',
            'directline', 'telegram', 'sms', 'slack'
    ]:
        with self.argument_context('bot {0} show'.format(channel)) as c:
            c.argument('show_secrets',
                       options_list=['--with-secrets'],
                       help='Show secrets in response for the channel.',
                       arg_type=get_three_state_flag())
コード例 #21
0
ファイル: _params.py プロジェクト: superclassiceth/azure-cli
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', options_list=['--name', '-n'], help='The name of the container registry. You can configure the default registry name using `az configure --defaults acr=<registry name>`', completer=get_resource_name_completion_list(REGISTRY_RESOURCE_TYPE), configured_default='acr', validator=validate_registry_name)
        c.argument('tenant_suffix', options_list=['--suffix'], help="The tenant suffix in registry login server. You may specify '--suffix tenant' if your registry login server is in the format 'registry-tenant.azurecr.io'. Applicable if you\'re accessing the registry from a different subscription or you have permission to access images but not the permission to manage the registry resource.")
        c.argument('sku', help='The SKU of the container registry', arg_type=get_enum_type(SkuName))
        c.argument('admin_enabled', help='Indicates whether the admin user is enabled', arg_type=get_three_state_flag())
        c.argument('password_name', help='The name of password to regenerate', arg_type=get_enum_type(PasswordName))
        c.argument('username', options_list=['--username', '-u'], help='The username used to log into a container registry')
        c.argument('password', options_list=['--password', '-p'], help='The password used to log into a container registry')
        c.argument('yes', options_list=['--yes', '-y'], help='Do not prompt for confirmation.', action='store_true')
        c.argument('image_names', options_list=['--image', '-t'], help="The name and tag of the image using the format: '-t repo/image:tag'. Multiple tags are supported by passing -t multiple times.", action='append')
        c.argument('timeout', type=int, help='The timeout in seconds.')
        c.argument('docker_file_path', options_list=['--file', '-f'], help="The relative path of the the docker file to the source code root folder. Default to 'Dockerfile'.")
        c.argument('no_logs', help="Do not show logs after successfully queuing the build.", action='store_true')
        c.argument('no_wait', help="Do not wait for the run to complete and return immediately after queuing the run.", action='store_true')
        c.argument('no_format', help="Indicates whether the logs should be displayed in raw format", action='store_true')
        c.argument('platform', help="The platform where build/task is run, Eg, 'windows' and 'linux'. When it's used in build commands, it also can be specified in 'os/arch/variant' format for the resulting image. Eg, linux/arm/v7. The 'arch' and 'variant' parts are optional.")
        c.argument('target', help='The name of the target build stage.')
        c.argument('auth_mode', help='Auth mode of the source registry.', arg_type=get_enum_type(SourceRegistryLoginMode))
        # Overwrite default shorthand of cmd to make availability for acr usage
        c.argument('cmd', options_list=['--__cmd__'])
        c.argument('cmd_value', help="Commands to execute.", options_list=['--cmd'])

    for scope in ['acr create', 'acr update']:
        with self.argument_context(scope, arg_group='Network Rule') as c:
            c.argument('default_action', arg_type=get_enum_type(DefaultAction),
                       help='Default action to apply when no rule matches. Only applicable to Premium SKU.')
            c.argument('public_network_enabled', get_three_state_flag(), help="Allow public network access for the container registry. The Default is allowed")

    with self.argument_context('acr create', arg_group="Customer managed key") as c:
        c.argument('identity', help="Use assigned managed identity resource id or name if in the same resource group")
        c.argument('key_encryption_key', help="key vault key uri")

    with self.argument_context('acr update', arg_group='Network Rule') as c:
        c.argument('data_endpoint_enabled', get_three_state_flag(), help="Enable dedicated data endpoint for client firewall configuration")

    with self.argument_context('acr import') as c:
        c.argument('source_image', options_list=['--source'], help="Source image name or fully qualified source containing the registry login server. If `--registry` is used, `--source` will always be interpreted as a source image, even if it contains the login server.")
        c.argument('source_registry', options_list=['--registry', '-r'], help='The source Azure container registry. This can be name, login server or resource ID of the source registry.')
        c.argument('source_registry_username', options_list=['--username', '-u'], help='The username of source container registry')
        c.argument('source_registry_password', options_list=['--password', '-p'], help='The password of source container registry')
        c.argument('target_tags', options_list=['--image', '-t'], help="The name and tag of the image using the format: '-t repo/image:tag'. Multiple tags are supported by passing -t multiple times.", action='append')
        c.argument('repository', help='The repository name for a manifest-only copy of images. Multiple copies supported by passing --repository multiple times.', action='append')
        c.argument('force', help='Overwrite the existing tag of the image to be imported.', action='store_true')

    with self.argument_context('acr config content-trust') as c:
        c.argument('registry_name', options_list=['--registry', '-r', c.deprecate(target='-n', redirect='-r', hide=True), c.deprecate(target='--name', redirect='--registry', hide=True)])
        c.argument('status', help="Indicates whether content-trust is enabled.", arg_type=get_enum_type(PolicyStatus))

    with self.argument_context('acr config retention') as c:
        c.argument('status', help="Indicates whether retention policy is enabled.", arg_type=get_enum_type(PolicyStatus))
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('days', type=int, help='The number of days to retain an untagged manifest after which it gets purged (Range: 0 to 365). Value "0" will delete untagged manifests immediately.', validator=validate_retention_days, default=7)
        c.argument('policy_type', options_list=['--type'], help='The type of retention policy.', arg_type=get_enum_type(RetentionType))

    with self.argument_context('acr login') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(hide=True))
        c.argument('expose_token', options_list=['--expose-token', '-t'], help='Expose access token instead of automatically logging in through Docker CLI', action='store_true')

    with self.argument_context('acr repository') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(hide=True))
        c.argument('repository', help="The name of the repository.")
        c.argument('image', arg_type=image_by_tag_or_digest_type)
        c.argument('top', type=int, help='Limit the number of items in the results.')
        c.argument('orderby', help='Order the items in the results. Default to alphabetical order of names.', arg_type=get_enum_type(['time_asc', 'time_desc']))
        c.argument('detail', help='Show detailed information.', action='store_true')
        c.argument('delete_enabled', help='Indicates whether delete operation is allowed.', arg_type=get_three_state_flag())
        c.argument('list_enabled', help='Indicates whether this item shows in list operation results.', arg_type=get_three_state_flag())
        c.argument('read_enabled', help='Indicates whether read operation is allowed.', arg_type=get_three_state_flag())
        c.argument('write_enabled', help='Indicates whether write or delete operation is allowed.', arg_type=get_three_state_flag())

    with self.argument_context('acr repository untag') as c:
        c.argument('image', options_list=['--image', '-t'], help="The name of the image. May include a tag in the format 'name:tag'.")

    with self.argument_context('acr create') as c:
        c.argument('registry_name', completer=None, validator=None)
        c.argument('deployment_name', validator=None)
        c.argument('location', validator=get_default_location_from_resource_group)
        c.argument('workspace', is_preview=True,
                   help='Name or ID of the Log Analytics workspace to send registry diagnostic logs to. All events will be enabled. You can use "az monitor log-analytics workspace create" to create one. Extra billing may apply.')

    with self.argument_context('acr check-name') as c:
        c.argument('registry_name', completer=None, validator=None)

    with self.argument_context('acr webhook') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('webhook_name', options_list=['--name', '-n'], help='The name of the webhook', completer=get_resource_name_completion_list(WEBHOOK_RESOURCE_TYPE))
        c.argument('uri', help='The service URI for the webhook to post notifications.')
        c.argument('headers', nargs='+', help="Space-separated custom headers in 'key[=value]' format that will be added to the webhook notifications. Use {} to clear existing headers.".format(quotes), validator=validate_headers)
        c.argument('actions', nargs='+', help='Space-separated list of actions that trigger the webhook to post notifications.', arg_type=get_enum_type(WebhookAction))
        c.argument('status', help='Indicates whether the webhook is enabled.', arg_type=get_enum_type(WebhookStatus))
        c.argument('scope', help="The scope of repositories where the event can be triggered. For example, 'foo:*' means events for all tags under repository 'foo'. 'foo:bar' means events for 'foo:bar' only. 'foo' is equivalent to 'foo:latest'. Empty means events for all repositories.")

    with self.argument_context('acr webhook create') as c:
        c.argument('webhook_name', completer=None)

    with self.argument_context('acr replication') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('replication_name', options_list=['--name', '-n'], help='The name of the replication.', completer=get_resource_name_completion_list(REPLICATION_RESOURCE_TYPE))

    with self.argument_context('acr replication create') as c:
        c.argument('replication_name', help='The name of the replication. Default to the location name.', completer=None)

    with self.argument_context('acr run') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.positional('source_location', help="The local source code directory path (e.g., './src') or the URL to a git repository (e.g., 'https://github.com/Azure-Samples/acr-build-helloworld-node.git') or a remote tarball (e.g., 'http://server/context.tar.gz'). If '/dev/null' is specified, the value will be set to None and ignored.", completer=FilesCompleter())
        c.argument('file', options_list=['--file', '-f'], help="The task template/definition file path relative to the source context. It can be '-' to pipe a file from the standard input.")
        c.argument('values', help="The task values file path relative to the source context.")
        c.argument('set_value', options_list=['--set'], help="Value in 'name[=value]' format. Multiples supported by passing --set multiple times.", action='append', validator=validate_set)
        c.argument('set_secret', help="Secret value in '--set name[=value]' format. Multiples supported by passing --set multiple times.", action='append', validator=validate_set_secret)
        c.argument('agent_pool_name', options_list=['--agent-pool'], help='The name of the agent pool.', is_preview=True)

    with self.argument_context('acr pack build') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('image_name', options_list=['--image', '-t'], help="The name and tag of the image using the format: '-t repo/image:tag'.")
        c.argument('builder', options_list=['--builder', '-b'], help="The name and tag of a Buildpack builder image.")
        c.argument('pack_image_tag', options_list=['--pack-image-tag'], help="The tag of the 'pack' runner image ('mcr.microsoft.com/oryx/pack').", is_preview=True)
        c.argument('pull', options_list=['--pull'], help="Pull the latest builder and run images before use.", action='store_true')
        c.positional('source_location', help="The local source code directory path (e.g., './src') or the URL to a git repository (e.g., 'https://github.com/Azure-Samples/acr-build-helloworld-node.git') or a remote tarball (e.g., 'http://server/context.tar.gz').", completer=FilesCompleter())
        c.argument('agent_pool_name', options_list=['--agent-pool'], help='The name of the agent pool.', is_preview=True)

    with self.argument_context('acr build') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.positional('source_location', help="The local source code directory path (e.g., './src') or the URL to a git repository (e.g., 'https://github.com/Azure-Samples/acr-build-helloworld-node.git') or a remote tarball (e.g., 'http://server/context.tar.gz').", completer=FilesCompleter())
        c.argument('no_push', help="Indicates whether the image built should be pushed to the registry.", action='store_true')
        c.argument('no_wait', help="Do not wait for the build to complete and return immediately after queuing the build.", action='store_true')
        c.argument('arg', options_list=['--build-arg'], help="Build argument in '--build-arg name[=value]' format. Multiples supported by passing --build-arg multiple times.", action='append', validator=validate_arg)
        c.argument('secret_arg', options_list=['--secret-build-arg'], help="Secret build argument in '--secret-build-arg name[=value]' format. Multiples supported by passing '--secret-build-arg name[=value]' multiple times.", action='append', validator=validate_secret_arg)
        c.argument('agent_pool_name', options_list=['--agent-pool'], help='The name of the agent pool.', is_preview=True)

    with self.argument_context('acr task') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('task_name', options_list=['--name', '-n'], help='The name of the task.', completer=get_resource_name_completion_list(TASK_RESOURCE_TYPE))
        c.argument('status', help='The current status of task.', arg_type=get_enum_type(TaskStatus))
        c.argument('with_secure_properties', help="Indicates whether the secure properties of a task should be returned.", action='store_true')

        # DockerBuildStep, FileTaskStep parameters
        c.argument('file', options_list=['--file', '-f'], help="Relative path of the the task/docker file to the source code root folder. Task files must be suffixed with '.yaml' or piped from the standard input using '-'.")
        c.argument('image', arg_type=image_by_tag_or_digest_type)
        c.argument('no_push', help="Indicates whether the image built should be pushed to the registry.", arg_type=get_three_state_flag())
        c.argument('no_cache', help='Indicates whether the image cache is enabled.', arg_type=get_three_state_flag())
        c.argument('values', help="The task values/parameters file path relative to the source context.")

        # common to DockerBuildStep, FileTaskStep and RunTaskStep
        c.argument('context_path', options_list=['--context', '-c'], help="The full URL to the source code repository (Requires '.git' suffix for a github repo). If '/dev/null' is specified, the value will be set to None and ignored.")
        c.argument('arg', help="Build argument in '--arg name[=value]' format. Multiples supported by passing '--arg` multiple times.", action='append', validator=validate_arg)
        c.argument('secret_arg', help="Secret build argument in '--secret-arg name[=value]' format. Multiples supported by passing --secret-arg multiple times.", action='append', validator=validate_secret_arg)
        c.argument('set_value', options_list=['--set'], help="Task value in '--set name[=value]' format. Multiples supported by passing --set multiple times.", action='append', validator=validate_set)
        c.argument('set_secret', help="Secret task value in '--set-secret name[=value]' format. Multiples supported by passing --set-secret multiple times.", action='append', validator=validate_set_secret)

        # Trigger parameters
        c.argument('source_trigger_name', arg_group='Trigger', help="The name of the source trigger.")
        c.argument('commit_trigger_enabled', arg_group='Trigger', help="Indicates whether the source control commit trigger is enabled.", arg_type=get_three_state_flag())
        c.argument('pull_request_trigger_enabled', arg_group='Trigger', help="Indicates whether the source control pull request trigger is enabled. The trigger is disabled by default.", arg_type=get_three_state_flag())
        c.argument('schedule', arg_group='Trigger', help="Schedule for a timer trigger represented as a cron expression. An optional trigger name can be specified using `--schedule name:schedule` format. Multiples supported by passing --schedule multiple times.", action='append')
        c.argument('git_access_token', arg_group='Trigger', help="The access token used to access the source control provider.")
        c.argument('base_image_trigger_name', arg_group='Trigger', help="The name of the base image trigger.")
        c.argument('base_image_trigger_enabled', arg_group='Trigger', help="Indicates whether the base image trigger is enabled.", arg_type=get_three_state_flag())
        c.argument('base_image_trigger_type', arg_group='Trigger', help="The type of the auto trigger for base image dependency updates.", arg_type=get_enum_type(BaseImageTriggerType))
        c.argument('update_trigger_endpoint', arg_group='Trigger', help="The full URL of the endpoint to receive base image update trigger notifications.", is_preview=True)
        c.argument('update_trigger_payload_type', arg_group='Trigger', help="Indicates whether to include metadata about the base image trigger in the payload alongwith the update trigger token, when a notification is sent.", arg_type=get_enum_type(UpdateTriggerPayloadType), is_preview=True)

        # Run related parameters
        c.argument('run_id', help='The unique run identifier.')

        # Run agent parameters
        c.argument('cpu', type=int, help='The CPU configuration in terms of number of cores required for the run.')

        # MSI parameter
        c.argument('assign_identity', nargs='*', help="Assigns managed identities to the task. Use '[system]' to refer to the system-assigned identity or a resource ID to refer to a user-assigned identity. Please see https://aka.ms/acr/tasks/task-create-managed-identity for more information.")

        # Agent Pool Parameter
        c.argument('agent_pool_name', options_list=['--agent-pool'], help='The name of the agent pool.', is_preview=True)

    with self.argument_context('acr task create') as c:
        c.argument('task_name', completer=None)

    with self.argument_context('acr task identity') as c:
        c.argument('identities', options_list=['--identities'], nargs='*', help="Assigns managed identities to the task. Use '[system]' to refer to the system-assigned identity or a resource ID to refer to a user-assigned identity.")

    with self.argument_context('acr task credential') as c:
        # Custom registry credentials
        c.argument('login_server', help="The login server of the custom registry. For instance, 'myregistry.azurecr.io'.", required=True)

    with self.argument_context('acr task run') as c:
        # Update trigger token parameters
        c.argument('update_trigger_token', help="The payload that will be passed back alongwith the base image trigger notification.", is_preview=True)

    with self.argument_context('acr task list-runs') as c:
        c.argument('run_status', help='The current status of run.', arg_type=get_enum_type(RunStatus))
        c.argument('top', help='Limit the number of latest runs in the results.')

    with self.argument_context('acr task update-run') as c:
        c.argument('no_archive', help='Indicates whether the run should be archived.', arg_type=get_three_state_flag())

    for scope in ['acr task credential add', 'acr task credential update']:
        with self.argument_context(scope) as c:
            c.argument('username', options_list=['--username', '-u'], help="The username to login to the custom registry. This can be plain text or a key vault secret URI.")
            c.argument('password', options_list=['--password', '-p'], help="The password to login to the custom registry. This can be plain text or a key vault secret URI.")
            c.argument('use_identity', help="The task managed identity used for the credential. Use '[system]' to refer to the system-assigned identity or a client id to refer to a user-assigned identity. Please see https://aka.ms/acr/tasks/cross-registry-authentication for more information.")

    with self.argument_context('acr task timer') as c:
        # Timer trigger parameters
        c.argument('timer_name', help="The name of the timer trigger.", required=True)
        c.argument('timer_schedule', options_list=['--schedule'], help="The schedule of the timer trigger represented as a cron expression.")
        c.argument('enabled', help="Indicates whether the timer trigger is enabled.", arg_type=get_three_state_flag())

    with self.argument_context('acr taskrun') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('taskrun_name', options_list=['--name', '-n'], help='The name of the taskrun.', completer=get_resource_name_completion_list(TASKRUN_RESOURCE_TYPE))

    with self.argument_context('acr helm') as c:
        c.argument('resource_group_name', deprecate_info=c.deprecate(hide=True))
        c.argument('repository', help=argparse.SUPPRESS)
        c.argument('version', help='The helm chart version.')

    with self.argument_context('acr helm show') as c:
        c.positional('chart', help='The helm chart name.')

    with self.argument_context('acr helm delete') as c:
        c.positional('chart', help='The helm chart name.')
        c.argument('prov', help='Only delete the provenance file.', action='store_true')

    with self.argument_context('acr helm push') as c:
        c.positional('chart_package', help="The helm chart package.", completer=FilesCompleter())
        c.argument('force', help='Overwrite the existing chart package.', action='store_true')

    with self.argument_context('acr helm install-cli') as c:
        c.argument('client_version', help='The target Helm CLI version. (Attention: Currently, Helm 3 does not work with "az acr helm" commands) ')
        c.argument('install_location', help='Path at which to install Helm CLI (Existing one at the same path will be overwritten)', default=_get_helm_default_install_location())
        c.argument('yes', help='Agree to the license of Helm, and do not prompt for confirmation.')

    with self.argument_context('acr network-rule') as c:
        c.argument('subnet', help='Name or ID of subnet. If name is supplied, `--vnet-name` must be supplied.')
        c.argument('vnet_name', help='Name of a virtual network.')
        c.argument('ip_address', help='IPv4 address or CIDR range.')

    with self.argument_context('acr check-health') as c:
        c.argument('ignore_errors', options_list=['--ignore-errors'], help='Provide all health checks, even if errors are found', action='store_true', required=False)

    with self.argument_context('acr scope-map') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('description', options_list=['--description'], help='Description for the scope map. Maximum 256 characters are allowed.', required=False)
        c.argument('scope_map_name', options_list=['--name', '-n'], help='The name of the scope map.', required=True)

    valid_actions = "Valid actions are {}".format({action.value for action in ScopeMapActions})
    with self.argument_context('acr scope-map update') as c:
        c.argument('add_repository', options_list=['--add'], nargs='+', action='append', required=False,
                   help='repository permissions to be added. Use the format "--add REPO [ACTION1 ACTION2 ...]" per flag. ' + valid_actions)
        c.argument('remove_repository', options_list=['--remove'], nargs='+', action='append', required=False,
                   help='respsitory permissions to be removed. Use the format "--remove REPO [ACTION1 ACTION2 ...]" per flag. ' + valid_actions)

    with self.argument_context('acr scope-map create') as c:
        c.argument('repository_actions_list', options_list=['--repository'], nargs='+', action='append', required=True,
                   help='repository permissions. Use the format "--repository REPO [ACTION1 ACTION2 ...]" per flag. ' + valid_actions)

    with self.argument_context('acr token') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('token_name', options_list=['--name', '-n'], help='The name of the token.', required=True)
        c.argument('scope_map_name', options_list=['--scope-map'], help='The name of the scope map associated with the token', required=False)
        c.argument('status', options_list=['--status'], arg_type=get_enum_type(TokenStatus),
                   help='The status of the token', required=False, default="enabled")

    with self.argument_context('acr token create') as c:
        c.argument('scope_map_name', options_list=['--scope-map'],
                   help='The name of the scope map with pre-configured repository permissions. Use "--repository" if you would like CLI to configure one for you')
        c.argument('repository_actions_list', options_list=['--repository'], nargs='+', action='append',
                   help='repository permissions. Use the format "--repository REPO [ACTION1 ACTION2 ...]" per flag. ' + valid_actions)
        c.argument('no_passwords', arg_type=get_three_state_flag(), help='Do not generate passwords, instead use "az acr token credential generate"')
        c.argument('expiration_in_days', help='Number of days for which the credentials will be valid. If not specified, the expiration will default to the max value "9999-12-31T23:59:59.999999+00:00"', type=int, required=False)

    with self.argument_context('acr token update') as c:
        c.argument('scope_map_name', options_list=['--scope-map'], help='The name of the scope map associated with the token. If not specified, running this command will disassociate the current scope map related to the token.', required=False)

    with self.argument_context('acr token credential generate') as c:
        c.argument('password1', options_list=['--password1'], help='Flag indicating if password1 should be generated.', action='store_true', required=False)
        c.argument('password2', options_list=['--password2'], help='Flag indicating if password2 should be generated.', action='store_true', required=False)
        c.argument('expiration_in_days', options_list=['--expiration-in-days', c.deprecate(target='--days', redirect='--expiration-in-days', hide=True)],
                   help='Number of days for which the credentials will be valid. If not specified, the expiration will default to the max value "9999-12-31T23:59:59.999999+00:00"', type=int, required=False)

    for scope in ['acr token create', 'acr token credential generate']:
        with self.argument_context(scope) as c:
            c.argument('expiration', validator=validate_expiration_time,
                       help='UTC time for which the credentials will be valid. In the format of %Y-%m-%dT%H:%M:%SZ, e.g. 2025-12-31T12:59:59Z')

    with self.argument_context('acr token credential delete') as c:
        c.argument('password1', options_list=['--password1'], help='Flag indicating if first password should be deleted', action='store_true', required=False)
        c.argument('password2', options_list=['--password2'], help='Flag indicating if second password should be deleted.', action='store_true', required=False)

    with self.argument_context('acr agentpool') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('agent_pool_name', options_list=['--name', '-n'], help='The name of the agent pool.')
        c.argument('count', options_list=['--count', '-c'], type=int, help='The count of the agent pool.')
        c.argument('tier', help='Sets the VM your agent pool will run on. Valid values are: S1(2 vCPUs, 3 MiB RAM), S2(4 vCPUs, 8 MiB RAM) or S3(8 vCPUs, 16 MiB RAM)')
        c.argument('os_type', options_list=['--os'], help='The os of the agent pool.', deprecate_info=c.deprecate(hide=True))
        c.argument('subnet_id', options_list=['--subnet-id'], help='The Virtual Network Subnet Resource Id of the agent machine.')
        c.argument('no_wait', help="Do not wait for the Agent Pool to complete action and return immediately after queuing the request.", action='store_true')

    with self.argument_context('acr agentpool show') as c:
        c.argument('queue_count', help="Get only the queue count", action='store_true')

    with self.argument_context('acr private-endpoint-connection') as c:
        # to match private_endpoint_connection_command_guideline.md guidelines
        c.argument('registry_name', options_list=['--registry-name', '-r'], help='The name of the container registry. You can configure the default registry name using `az configure --defaults acr=<registry name>`', completer=get_resource_name_completion_list(REGISTRY_RESOURCE_TYPE), configured_default='acr')
        c.argument('private_endpoint_connection_name', options_list=['--name', '-n'], help='The name of the private endpoint connection')

        c.argument('approval_description', options_list=['--description'], help='Approval description. For example, the reason for approval.')
        c.argument('rejection_description', options_list=['--description'], help='Rejection description. For example, the reason for rejection.')

    with self.argument_context('acr identity') as c:
        c.argument('identities', nargs='+', help="Space-separated identities. Use '[system]' to refer to the system assigned identity")

    with self.argument_context('acr encryption') as c:
        c.argument('key_encryption_key', help="key vault key uri")
        c.argument('identity', help="client id of managed identity, resource name or id of user assigned identity. Use '[system]' to refer to the system assigned identity")
コード例 #22
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('os_sku', type=str, options_list=['--os-sku'], completer=get_ossku_completion_list)
        c.argument('ssh_key_value', required=False, type=file_type, default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(), validator=validate_ssh_key)
        c.argument('aad_client_app_id')
        c.argument('aad_server_app_id')
        c.argument('aad_server_app_secret')
        c.argument('aad_tenant_id')
        c.argument('dns_service_ip')
        c.argument('docker_bridge_address')
        c.argument('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('nat_gateway_managed_outbound_ip_count', type=int, validator=validate_nat_gateway_managed_outbound_ip_count)
        c.argument('nat_gateway_idle_timeout', type=int, validator=validate_nat_gateway_idle_timeout)
        c.argument('outbound_type', arg_type=get_enum_type([CONST_OUTBOUND_TYPE_LOAD_BALANCER,
                                                            CONST_OUTBOUND_TYPE_USER_DEFINED_ROUTING,
                                                            CONST_OUTBOUND_TYPE_MANAGED_NAT_GATEWAY,
                                                            CONST_OUTBOUND_TYPE_USER_ASSIGNED_NAT_GATEWAY]))
        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('enable_msi_auth_for_monitoring', arg_type=get_three_state_flag(), is_preview=True)
        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('disable_public_fqdn', action='store_true')
        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('http_proxy_config', options_list=['--http-proxy-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_ultra_ssd', action='store_true')
        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('gpu_instance_profile', arg_type=get_enum_type(gpu_instance_profiles))
        c.argument('yes', options_list=['--yes', '-y'], help='Do not prompt for confirmation.', action='store_true')
        c.argument('workload_runtime', arg_type=get_enum_type(workload_runtimes), default=CONST_WORKLOAD_RUNTIME_OCI_CONTAINER)

    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('nat_gateway_managed_outbound_ip_count', type=int, validator=validate_nat_gateway_managed_outbound_ip_count)
        c.argument('nat_gateway_idle_timeout', type=int, validator=validate_nat_gateway_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('enable_public_fqdn', action='store_true')
        c.argument('disable_public_fqdn', 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.')

    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('os_sku', type=str, options_list=['--os-sku'], completer=get_ossku_completion_list)
            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('scale_down_mode', arg_type=get_enum_type([CONST_SCALE_DOWN_MODE_DELETE, CONST_SCALE_DOWN_MODE_DEALLOCATE]))
            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')
            c.argument('enable_ultra_ssd', action='store_true')
            c.argument('workload_runtime', arg_type=get_enum_type(workload_runtimes), default=CONST_WORKLOAD_RUNTIME_OCI_CONTAINER)
            c.argument('gpu_instance_profile', arg_type=get_enum_type(gpu_instance_profiles))

    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)
        c.argument('aks_custom_headers')

    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('scale_down_mode', arg_type=get_enum_type([CONST_SCALE_DOWN_MODE_DELETE, CONST_SCALE_DOWN_MODE_DEALLOCATE]))
        c.argument('tags', tags_type)
        c.argument('mode', 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 addon show') as c:
        c.argument('addon', options_list=['--addon', '-a'], validator=validate_addon)

    with self.argument_context('aks addon enable') as c:
        c.argument('addon', options_list=['--addon', '-a'], validator=validate_addon)
        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')
        c.argument('workspace_resource_id')
        c.argument('enable_msi_auth_for_monitoring', arg_type=get_three_state_flag(), is_preview=True)

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

    with self.argument_context('aks addon update') as c:
        c.argument('addon', options_list=['--addon', '-a'], validator=validate_addon)
        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')
        c.argument('workspace_resource_id')
        c.argument('enable_msi_auth_for_monitoring', arg_type=get_three_state_flag(), is_preview=True)

    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')
        c.argument('workspace_resource_id')
        c.argument('enable_msi_auth_for_monitoring', arg_type=get_three_state_flag(), is_preview=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'))
        c.argument('public_fqdn', default=False, action='store_true')

    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)
コード例 #23
0
ファイル: _params.py プロジェクト: johanste/azure-cli
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='+')

    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')
コード例 #24
0
def load_arguments(self, _):

    with self.argument_context('dnc controller show') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.',
            id_part='name')

    with self.argument_context('dnc controller create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.')
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   required=False,
                   validator=get_default_location_from_resource_group)
        c.argument('tags', tags_type)

    with self.argument_context('dnc controller delete') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.',
            id_part='name')

    with self.argument_context('dnc controller wait') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.',
            id_part='name')

    with self.argument_context('dnc orchestrator-instance-service show') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.',
            id_part='name')

    with self.argument_context(
            'dnc orchestrator-instance-service create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.')
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   required=False,
                   validator=get_default_location_from_resource_group)
        c.argument('tags', tags_type)
        c.argument(
            'type_',
            options_list=['--type'],
            arg_type=get_enum_type(['SystemAssigned', 'None']),
            help='The '
            'type of identity used for orchestrator cluster. Type \'SystemAssigned\' will use an implicitly '
            'created identity orchestrator clusters',
            arg_group='Identity')
        c.argument('orchestrator_app_id',
                   type=str,
                   help='AAD ID used with apiserver')
        c.argument('orchestrator_tenant_id',
                   type=str,
                   help='TenantID of server App ID')
        c.argument(
            'cluster_root_ca',
            type=str,
            help='RootCA certificate of kubernetes cluster base64 encoded')
        c.argument(
            'api_server_endpoint',
            type=str,
            help='K8s APIServer url. Either one of apiServerEndpoint or '
            'privateLinkResourceId can be specified')
        c.argument(
            'private_link_resource_id',
            options_list=['--priv-link-resource-id'],
            type=str,
            help='private link '
            'arm resource id. Either one of apiServerEndpoint or privateLinkResourceId can be specified'
        )
        c.argument('id_',
                   options_list=['--id'],
                   type=str,
                   help='controller arm resource id',
                   arg_group='Controller '
                   'Details')

    with self.argument_context(
            'dnc orchestrator-instance-service delete') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.',
            id_part='name')
        c.argument('force_delete',
                   arg_type=get_three_state_flag(),
                   help='Force delete resource')

    with self.argument_context('dnc orchestrator-instance-service wait') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.',
            id_part='name')

    with self.argument_context('dnc delegated-subnet-service show') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.',
            id_part='name')

    with self.argument_context('dnc delegated-subnet-service create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.')
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   required=False,
                   validator=get_default_location_from_resource_group)
        c.argument('tags', tags_type)
        c.argument('id_',
                   options_list=['--id'],
                   type=str,
                   help='controller arm resource id',
                   arg_group='Controller '
                   'Details')
        c.argument('subnet_details_id',
                   type=str,
                   help='subnet arm resource id',
                   arg_group='Subnet Details')

    with self.argument_context('dnc delegated-subnet-service delete') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.',
            id_part='name')
        c.argument('force_delete',
                   arg_type=get_three_state_flag(),
                   help='Force delete resource')

    with self.argument_context('dnc delegated-subnet-service wait') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument(
            'resource_name',
            type=str,
            help=
            'The name of the resource. It must be a minimum of 3 characters, '
            'and a maximum of 63.',
            id_part='name')
コード例 #25
0
ファイル: _params.py プロジェクト: sptramer/azure-cli
def load_arguments(self, _):
    with self.argument_context('bot') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('resource_name', options_list=['--name', '-n'], help='The resource name of the bot.', arg_type=name_arg_type)

    with self.argument_context('bot create') as c:
        c.argument('sku_name', options_list=['--sku'], arg_type=get_enum_type(['F0', 'S1']), help='The Sku of the bot.', arg_group='Registration bot Specific')
        c.argument('kind', options_list=['--kind', '-k'], arg_type=get_enum_type(['registration', 'function', 'webapp']), help='The kind of the bot.')
        c.argument('display_name', help='The display name of the bot. If not specified, defaults to the name of the bot.', arg_group='Registration bot Specific')
        c.argument('description', options_list=['--description', '-d'], help='The description of the bot.', arg_group='Registration bot Specific')
        c.argument('endpoint', options_list=['-e', '--endpoint'], help='The messaging endpoint of the bot.', arg_group='Registration bot Specific')
        c.argument('msa_app_id', options_list=['--appid'], help='The Microsoft account ID (MSA ID) to be used with the bot.')
        c.argument('password', options_list=['-p', '--password'], help='The Microsoft account (MSA) password for the bot.')
        c.argument('storageAccountName', options_list=['-s', '--storage'], help='Storage account name to be used with the bot. If not provided, a new account will be created.', arg_group='Web/Function bot Specific')
        c.argument('tags', arg_type=tags_type)
        c.argument('language', help='The language to be used to create the bot.', options_list=['--lang'], arg_type=get_enum_type(supported_languages), arg_group='Web/Function bot Specific')
        c.argument('appInsightsLocation', help='The location for the app insights to be used with the bot.', options_list=['--insights-location'], arg_group='Web/Function bot Specific',
                   arg_type=get_enum_type(['South Central US', 'East US', 'West US 2', 'North Europe', 'West Europe', 'Southeast Asia']))
        c.argument('version', options_list=['-v', '--version'], help='The Microsoft Bot Builder SDK version to be used to create the bot', arg_type=get_enum_type(['v3', 'v4']), arg_group='Web/Function bot Specific')

    with self.argument_context('bot publish') as c:
        c.argument('code_dir', options_list=['--code-dir'], help='The directory to upload bot code from.')
        c.argument('proj_name', help='Name of the start up project file name.')
        c.argument('version', options_list=['-v', '--version'],
                   help='The Microsoft Bot Builder SDK version of the bot.')

    with self.argument_context('bot download') as c:
        c.argument('file_save_path', options_list=['--save-path'], help='The directory to download bot code to.')

    with self.argument_context('bot show') as c:
        c.argument('bot_json', options_list=['--msbot'], help='Show the output as JSON compatible with a .bot file.', arg_type=get_three_state_flag())

    with self.argument_context('bot prepare-publish') as c:
        c.argument('proj_name', help='Name of the start up project file name. Required only for C#.')
        c.argument('sln_name', help='Name of the start up solution file name. Required only for C#.')
        c.argument('code_dir', options_list=['--code-dir'], help='The directory to download deployment scripts to.')
        c.argument('version', options_list=['-v', '--version'], help='The Microsoft Bot Builder SDK version to be used '
                                                                     'in the bot template that will be created.',
                   arg_type=get_enum_type(['v3', 'v4']), arg_group='Web/Function bot Specific')

    with self.argument_context('bot facebook create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state')
        c.argument('page_id', options_list=['--page-id'], help='Page ID of the Facebook page to be used for the bot.')
        c.argument('app_id', options_list=['--appid'], help='The Facebook application id.')
        c.argument('app_secret', options_list=['--secret'], help='The Facebook application secret.')
        c.argument('access_token', options_list=['--token'], help='The Facebook application access token.')

    with self.argument_context('bot email create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state')
        c.argument('email_address', options_list=['--email-address', '-a'], help='The email address for the bot.')
        c.argument('password', options_list=['--password', '-p'], help='The email password for the bot.')

    with self.argument_context('bot msteams create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state.')
        c.argument('enable_calling', help='Enable calling on Microsoft Teams.', arg_type=get_three_state_flag())
        c.argument('calling_web_hook', help='The calling web hook to use on Microsoft Teams.')

    with self.argument_context('bot skype create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state.')
        c.argument('enable_messaging', help='Enable messaging on Skype.', arg_type=get_three_state_flag())
        c.argument('enable_media_cards', help='Enable media cards on Skype.', arg_type=get_three_state_flag())
        c.argument('enable_video', help='Enable video on Skype.', arg_type=get_three_state_flag())
        c.argument('enable_calling', help='Enable calling on Skype.', arg_type=get_three_state_flag())
        c.argument('enable_screen_sharing', help='Enable screen sharing on Skype.', arg_type=get_three_state_flag())
        c.argument('enable_groups', help='Enable groups on Skype.', arg_type=get_three_state_flag())
        c.argument('groups_mode', help='select groups mode on Skype.')
        c.argument('calling_web_hook', help='The calling web hook to use on Skype.')

    with self.argument_context('bot kik create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state.')
        c.argument('user_name', options_list=['--user-name', '-u'], help='Kik user name.')
        c.argument('is_validated', help='Whether or not the Kik account has been validated for use with the bot.', arg_type=get_three_state_flag())
        c.argument('api_key', options_list=['--key'], help='The API key for the Kik account.')

    with self.argument_context('bot webchat create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state.')
        c.argument('site_name', options_list=['-s', '--site-name'], help='Name of the Webchat channel site.')
        c.argument('enable_preview', help='Enable preview features on the chat control.', arg_type=get_three_state_flag())

    with self.argument_context('bot directline create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state.')
        c.argument('site_name', options_list=['-s', '--site-name'], help='Name of the Directline channel site.')
        c.argument('is_v1_disabled', options_list=['--disablev1'], help='If true, v1 protocol will be disabled on the channel', arg_type=get_three_state_flag())
        c.argument('is_v3_disabled', options_list=['--disablev3'], help='If true, v3 protocol will be disabled on the channel.', arg_type=get_three_state_flag())

    with self.argument_context('bot telegram create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state.')
        c.argument('access_token', help='The access token for the Telegram account.')
        c.argument('is_validated', help='Whether or not the Telegram account has been validated for use with the bot.', arg_type=get_three_state_flag())

    with self.argument_context('bot sms create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state.')
        c.argument('account_sid', help='The account SID for the Twilio account.')
        c.argument('auth_token', help='The token token for the Twilio account.')
        c.argument('is_validated', help='Whether or not the Twilio account has been validated for use with the bot.', arg_type=get_three_state_flag())
        c.argument('phone', help='The phone number for the Twilio account.')

    with self.argument_context('bot slack create') as c:
        c.argument('is_disabled', options_list=['--add-disabled'], arg_type=get_three_state_flag(), help='Add the channel in a disabled state.')
        c.argument('client_secret', help='The client secret from Slack.')
        c.argument('client_id', help='The client ID from Slack.')
        c.argument('verification_token', help='The verification token from Slack.')
        c.argument('landing_page_url', help='The landing page url to redirect to after login.')

    with self.argument_context('bot authsetting') as c:
        c.argument('connection_name', options_list=['--setting-name', '-c'], help='Name of the oauth connection setting.', id_part='child_name_1')

    with self.argument_context('bot authsetting create') as c:
        c.argument('client_id', help='Client ID associated with the service provider setting.')
        c.argument('client_secret', help='Client secret associated with the service provider setting.')
        c.argument('scopes', options_list=['--provider-scope-string'], help='The scope string associated with the service provider setting.The string should be delimited as needed for the service provider.')
        c.argument('service_provider_name', options_list=['--service'], help='Name of the service provider. For a list of all service providers, use `az bot connection listserviceproviders`.')
        c.argument('parameters', help='Parameter values for service provider parameters. Usage: --parameters key=value key1=value1.', nargs='+')

    with self.argument_context('bot authsetting list-providers') as c:
        c.argument('as_raw_settings', options_list=['--as-raw'], help='Output the raw json for each service provider.', arg_type=get_three_state_flag())
        c.argument('name', options_list=['--provider-name'], help='Service provider name for which to fetch details.')

    for channel in ['facebook', 'email', 'msteams', 'skype', 'kik', 'webchat', 'directline', 'telegram', 'sms', 'slack']:
        with self.argument_context('bot {0} show'.format(channel)) as c:
            c.argument('show_secrets', options_list=['--with-secrets'], help='Show secrets in response for the channel.', arg_type=get_three_state_flag())
コード例 #26
0
def load_arguments(self, _):

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

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

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

    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 connection') as c:
        for dest in ['virtual_hub_name', 'resource_name']:
            c.argument(dest, vhub_name_type)
        for dest in ['item_name', 'connection_name']:
            c.argument(dest,
                       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',
                   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',
                   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.')

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

    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')
        c.argument('destination_type',
                   arg_type=get_enum_type(['Service', 'CIDR']),
                   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']),
            help='The type of next hops. Currently it only supports IP Address.'
        )
        c.argument('next_hops',
                   nargs='+',
                   help='Space-separated list of IP address of the next hop.')
        c.argument('index',
                   type=int,
                   help='List index of the item (starting with 1).')
    # 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'))
コード例 #27
0
def load_arguments(self, _):    # pylint: disable=too-many-statements

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

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

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

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

        with self.argument_context('mysql server vnet-rule update') as c:
            c.extra('vnet_name', options_list=['--vnet-name'], help='The virtual network name', validator=validate_subnet)
コード例 #28
0
def load_central_arguments(self, _):
    """
    Load CLI Args for Knack parser
    """
    with self.argument_context("iot central") as context:
        context.argument(
            "app_id",
            options_list=["--app-id", "-n"],
            help="The App ID of the IoT Central app you want to manage."
            ' You can find the App ID in the "About" page for your application under the help menu.',
        )
        context.argument("api_version", arg_type=api_version)
        context.argument(
            "token",
            options_list=["--token"],
            help="If you'd prefer to submit your request without authenticating against the Azure CLI, you can specify a valid"
            " user token to authenticate your request. You must specify the type of key as part of the request."
            " Learn more at https://aka.ms/iotcentraldocsapi",
        )
        context.argument(
            "central_dns_suffix",
            options_list=["--central-dns-suffix", "--central-api-uri"],
            help="The IoT Central DNS suffix associated with your application. Default value is: azureiotcentral.com",
        )
        context.argument(
            "device_id",
            options_list=["--device-id", "-d"],
            help="The ID of the target device, "
            "You can find the Device Id by clicking on the Connect button on the Device Details page.",
        )

    with self.argument_context("iot central device-template") as context:
        context.argument(
            "device_template_id",
            options_list=["--device-template-id", "--dtid"],
            help="The ID of the target device template. Example: somedevicetemplate",
        )
        context.argument(
            "content",
            options_list=["--content", "-k"],
            help="The device template definition. Provide path to JSON file or raw stringified JSON."
            " [File Path Example: ./path/to/file.json] [Example of stringified JSON: {<Device Template JSON>}]."
            " The request body must contain CapabilityModel.",
        )

    with self.argument_context("iot central device-template create") as context:
        context.argument(
            "device_template_id",
            options_list=["--device-template-id", "--dtid"],
            help="Unique ID for the Device template.",
        )

    with self.argument_context("iot central api-token") as context:
        context.argument(
            "token_id",
            options_list=["--token-id", "--tkid"],
            help="The IoT Central ID associated with this token, [0-9a-zA-Z\\-] allowed, max length limit to 40."
            " Specify an ID that you'll then use when modifying or deleting this token later via the CLI or API.",
        )
        context.argument("role", arg_type=role_type)

    with self.argument_context("iot central device compute-device-key") as context:
        context.argument(
            "primary_key",
            options_list=["--primary-key", "--pk"],
            help="The primary symmetric shared access key stored in base64 format. ",
        )

    with self.argument_context("iot central device") as context:
        context.argument(
            "template",
            options_list=["--template"],
            help="Central template id. Example: dtmi:ojpkindbz:modelDefinition:iild3tm_uo.",
        )
        context.argument(
            "simulated",
            options_list=["--simulated"],
            arg_type=get_three_state_flag(),
            help="Add this flag if you would like IoT Central to set this up as a simulated device. "
            "--template is required if this is true",
        )
        context.argument(
            "device_name",
            options_list=["--device-name"],
            help="Human readable device name. Example: Fridge",
        )
        context.argument(
            "interface_id",
            options_list=["--interface-id", "-i"],
            help="The name of the interface/component as specified in the device template.You can find it by navigating"
            " to Device Template and view the interface/component identity under the corresponding device capability.",
        )
        context.argument(
            "command_name",
            options_list=["--command-name", "--cn"],
            help="The command name as specified in the device template. Command name could be different from the Display"
            " Name of the command.",
        )
        context.argument(
            "content",
            options_list=["--content", "-k"],
            help="Configuration for request. "
            "Provide path to JSON file or raw stringified JSON. "
            "[File Path Example: ./path/to/file.json] "
            "[Stringified JSON Example: {'a': 'b'}] ",
        )

    with self.argument_context("iot central device create") as context:
        context.argument(
            "device_id",
            options_list=["--device-id", "-d"],
            help="Provide a unique identifier for the device."
            " A case-sensitive string (up to 128 characters long) of ASCII 7-bit alphanumeric characters plus"
            " certain special characters: - . + % _ # * ? ! ( ) , : = @ $ '",
        )
    with self.argument_context("iot central device manual-failover") as context:
        context.argument(
            "ttl_minutes",
            type=int,
            options_list=["--ttl-minutes", "--ttl"],
            help="A positive integer. TTL in minutes to move device back to the original hub."
            "Has default value in backend. See documentation on what the latest backend default time to live value"
            "by visiting https://github.com/iot-for-all/iot-central-high-availability-clients#readme",
        )

    with self.argument_context("iot central user") as context:
        context.argument(
            "tenant_id",
            options_list=["--tenant-id", "--tnid"],
            help="Tenant ID for service principal to be added to the app. Object ID must also be specified. ",
        )
        context.argument(
            "object_id",
            options_list=["--object-id", "--oid"],
            help="Object ID for service principal to be added to the app. Tenant ID must also be specified. ",
        )
        context.argument(
            "email",
            options_list=["--email"],
            help="Email address of user to be added to the app. ",
        )
        context.argument(
            "assignee",
            options_list=["--user-id", "--assignee"],
            help="ID associated with the user. ",
        )
        context.argument("role", arg_type=role_type)

    with self.argument_context("iot central diagnostics") as context:
        context.argument("timeout", arg_type=event_timeout_type)
        context.argument("properties", arg_type=event_msg_prop_type)
        context.argument("minimum_severity", arg_type=severity_type)
        context.argument("style", arg_type=style_type)
        context.argument(
            "duration",
            options_list=["--duration", "--dr"],
            type=int,
            help="Maximum duration to receive messages from target device before terminating connection."
            "Use 0 for infinity.",
        )
        context.argument(
            "max_messages",
            options_list=["--max-messages", "--mm"],
            type=int,
            help="Maximum number of messages to recieve from target device before terminating connection."
            "Use 0 for infinity.",
        )
        context.argument(
            "module_id",
            options_list=["--module-id", "-m"],
            help="Provide IoT Edge Module ID if the device type is IoT Edge.",
        )

    with self.argument_context("iot central role") as context:
        context.argument(
            "role_id",
            options_list=["--role-id", "-r"],
            help="Provide a unique identifier for the role"
        )
コード例 #29
0
ファイル: _params.py プロジェクト: johanste/azure-cli
    arg_group=sku_component_arg_group,
    options_list=['--family', '-f'])

elastic_pool_id_param_type = CLIArgumentType(
    arg_group=sku_arg_group,
    options_list=['--elastic-pool'])

max_size_bytes_param_type = CLIArgumentType(
    options_list=['--max-size'],
    type=SizeWithUnitConverter('B', result_type=int),
    help='The max storage size. If no unit is specified, defaults to bytes (B).')

zone_redundant_param_type = CLIArgumentType(
    options_list=['--zone-redundant', '-z'],
    help='Specifies whether to enable zone redundancy',
    arg_type=get_three_state_flag())

managed_instance_param_type = CLIArgumentType(
    options_list=['--managed-instance', '--mi'],
    help='Name of the Azure SQL managed instance.')

storage_param_type = CLIArgumentType(
    options_list=['--storage'],
    type=SizeWithUnitConverter('GB', result_type=int, unit_map=dict(B=1.0 / (1024 * 1024 * 1024),
                                                                    kB=1.0 / (1024 * 1024),
                                                                    MB=1.0 / 1024,
                                                                    GB=1,
                                                                    TB=1024)),
    help='The storage size. If no unit is specified, defaults to gigabytes (GB).',
    validator=validate_managed_instance_storage_size)
コード例 #30
0
ファイル: _params.py プロジェクト: will373793/azure-cli
    def _complex_params(command_group):
        server_name_help = "Name of the server. The name can contain only lowercase letters, numbers, and the hyphen (-) character. " + \
                           "Minimum 3 characters and maximum 63 characters."
        server_name_scope = ['{}'.format(command_group)]
        server_name_setter_arg_type = CLIArgumentType(metavar='NAME', help=server_name_help, id_part='name',
                                                      local_context_attribute=LocalContextAttribute(name='server_name', actions=[LocalContextAction.SET], scopes=server_name_scope))
        server_name_getter_arg_type = CLIArgumentType(metavar='NAME', help=server_name_help, id_part='name',
                                                      local_context_attribute=LocalContextAttribute(name='server_name', actions=[LocalContextAction.GET], scopes=server_name_scope))
        server_name_arg_type = CLIArgumentType(metavar='NAME', help=server_name_help, id_part='name',
                                               local_context_attribute=LocalContextAttribute(name='server_name', actions=[LocalContextAction.SET, LocalContextAction.GET], scopes=server_name_scope))
        administrator_login_arg_type = CLIArgumentType(metavar='NAME',
                                                       local_context_attribute=LocalContextAttribute(name='administrator_login', actions=[LocalContextAction.GET, LocalContextAction.SET], scopes=server_name_scope))

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

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

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

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

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

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

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

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

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

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

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

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

        with self.argument_context('{} server configuration set'.format(command_group)) as c:
            c.argument('value', help='Value of the configuration. If not provided, configuration value will be set to default.', validator=configuration_value_validator)
            c.argument('configuration_name', options_list=['--name', '-n'], id_part='child_name_1', help='The name of the configuration')
            c.ignore('source')

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

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

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

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

        with self.argument_context('{} db'.format(command_group)) as c:
            c.argument('database_name', options_list=['--name', '-n'], help='The name of the database')
            c.argument('charset', options_list=['--charset'], help='The charset of the database')
            c.argument('collation', options_list=['--collation'], help='The collation of the database')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    firewall_name_type = CLIArgumentType(
        options_list=['--firewall-name', '-f'],
        metavar='NAME',
        help='Azure Firewall name.',
        id_part='name',
        completer=get_resource_name_completion_list(
            'Microsoft.Network/azureFirewalls'))
    collection_name_type = CLIArgumentType(
        options_list=['--collection-name', '-c'],
        help='Name of the rule collection.',
        id_part='child_name_1')
    virtual_network_name_type = CLIArgumentType(
        options_list='--vnet-name',
        metavar='NAME',
        help='The virtual network (VNet) name.',
        completer=get_resource_name_completion_list(
            'Microsoft.Network/virtualNetworks'))

    # region AzureFirewalls
    with self.argument_context('network firewall') as c:
        c.argument('azure_firewall_name',
                   firewall_name_type,
                   options_list=['--name', '-n'],
                   id_part='name')
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('description', help='Rule description.')
        c.argument(
            'destination_addresses',
            nargs='+',
            help=
            "Space-separated list of destination IP addresses. Use '*' to match all."
        )
        c.argument('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"'
        )

    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')
        c.argument(
            'require_dns_proxy_for_network_rules',
            arg_type=get_three_state_flag(),
            help=
            'Requires DNS Proxy functionality for FQDNs within Network Rules')

    with self.argument_context('network firewall threat-intel-whitelist') as c:
        c.argument('ip_addresses',
                   nargs='+',
                   validator=process_threat_intel_whitelist_ip_addresses,
                   help='Space-separated list of IPv4 addresses.')
        c.argument('fqdns',
                   nargs='+',
                   validator=process_threat_intel_whitelist_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).',
                type=int)

        with self.argument_context('network firewall {} collection'.format(
                item['name'])) as c:
            c.argument('item_name', collection_name_type)
            c.argument('resource_name', firewall_name_type)

        with self.argument_context(
                'network firewall {} collection list'.format(
                    item['name'])) as c:
            c.argument('item_name', collection_name_type)
            c.argument('resource_name', firewall_name_type, id_part=None)

    for scope in ['network-rule', 'application-rule']:
        with self.argument_context('network firewall {}'.format(scope),
                                   arg_group='Collection') as c:
            c.argument('action',
                       arg_type=get_enum_type(AzureFirewallRCActionType),
                       help='The action to apply for the rule collection.')

    with self.argument_context('network firewall nat-rule',
                               arg_group='Collection') as c:
        c.argument('action',
                   arg_type=get_enum_type(AzureFirewallNatRCActionType),
                   help='The action to apply for the rule collection.')

    with self.argument_context('network firewall ip-config') as c:
        c.argument('item_name',
                   options_list=['--name', '-n'],
                   help='Name of the IP configuration.',
                   id_part='child_name_2')
        c.argument('resource_name', firewall_name_type)
        c.argument('azure_firewall_name', firewall_name_type)
        c.argument('subnet',
                   validator=get_subnet_validator(),
                   help=argparse.SUPPRESS)
        c.argument(
            'virtual_network_name',
            virtual_network_name_type,
            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.')

    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_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_group_name',
            options_list=['--rule-collection-group-name'],
            help='The name of the Firewall Policy Rule Collection Group.')
        c.argument(
            'rule_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'
        )
        c.argument('description',
                   arg_group='Common Rule',
                   help='The description of rule.')
        c.argument('destination_addresses',
                   arg_group='Common Rule',
                   nargs='+',
                   help="Space-separated list of destination IP addresses.")
        c.argument('source_addresses',
                   arg_group='Common Rule',
                   nargs='+',
                   help="Space-separated list of source IP addresses.")
        c.argument('condition_name',
                   options_list=['--rule-name'],
                   arg_group='Common Rule',
                   help='The name of rule')
        c.argument('condition_type',
                   options_list=['--rule-type'],
                   arg_group='Common Rule',
                   arg_type=get_enum_type(["ApplicationRule", "NetworkRule"]),
                   help='The type of rule')
        c.argument('translated_address',
                   arg_group='Nat Collection',
                   help='Translated address for this NAT rule collection.')
        c.argument('translated_port',
                   arg_group='Nat Collection',
                   help='Translated port for this NAT rule collection.')
        c.argument('destination_ports',
                   arg_group='Network Rule',
                   nargs='+',
                   help="Space-separated list of destination ports.")
        c.argument('ip_protocols',
                   arg_group='Network Rule',
                   nargs='+',
                   arg_type=get_enum_type(["TCP", "UDP", "Any", "ICMP"]),
                   help="Space-separated list of IP protocols")
        c.argument('target_fqdns',
                   nargs='+',
                   arg_group='Application Rule',
                   help='Space-separated list of FQDNs for this rule.',
                   validator=validate_rule_group_collection)
        c.argument('fqdn_tags',
                   nargs='+',
                   arg_group='Application Rule',
                   help='Space-separated list of FQDN tags for this rule.',
                   validator=validate_rule_group_collection)
        c.argument(
            'protocols',
            nargs='+',
            arg_group='Application Rule',
            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 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_name',
            options_list=['--collection-name'],
            help=
            'The name of the rule collection in Firewall Policy Rule Collection Group.'
        )
        c.argument('condition_name',
                   options_list=['--name', '-n'],
                   arg_group='Common Rule',
                   help='The name of rule')
コード例 #32
0
ファイル: _params.py プロジェクト: johanste/azure-cli
def load_arguments(self, _):
    JsonWebKeyOperation = get_sdk(self.cli_ctx, ResourceType.DATA_KEYVAULT, 'models.key_vault_client_enums#JsonWebKeyOperation')
    KeyAttributes = get_sdk(self.cli_ctx, ResourceType.DATA_KEYVAULT, 'models.key_attributes#KeyAttributes')
    JsonWebKeyType = get_sdk(self.cli_ctx, ResourceType.DATA_KEYVAULT, 'models.key_vault_client_enums#JsonWebKeyType')
    JsonWebKeyCurveName = get_sdk(self.cli_ctx, ResourceType.DATA_KEYVAULT, 'models.key_vault_client_enums#JsonWebKeyCurveName')
    SasTokenType = get_sdk(self.cli_ctx, ResourceType.DATA_KEYVAULT, 'models.key_vault_client_enums#SasTokenType')
    SasDefinitionAttributes = get_sdk(self.cli_ctx, ResourceType.DATA_KEYVAULT, 'models.sas_definition_attributes#SasDefinitionAttributes')
    SecretAttributes = get_sdk(self.cli_ctx, ResourceType.DATA_KEYVAULT, 'models.secret_attributes#SecretAttributes')
    CertificateAttributes = get_sdk(self.cli_ctx, ResourceType.DATA_KEYVAULT, 'models.certificate_attributes#CertificateAttributes')
    StorageAccountAttributes = get_sdk(self.cli_ctx, ResourceType.DATA_KEYVAULT, 'models.storage_account_attributes#StorageAccountAttributes')
    SkuName = get_sdk(self.cli_ctx, ResourceType.MGMT_KEYVAULT, 'models.key_vault_management_client_enums#SkuName')
    KeyPermissions = get_sdk(self.cli_ctx, ResourceType.MGMT_KEYVAULT, 'models.key_vault_management_client_enums#KeyPermissions')
    SecretPermissions = get_sdk(self.cli_ctx, ResourceType.MGMT_KEYVAULT, 'models.key_vault_management_client_enums#SecretPermissions')
    CertificatePermissions = get_sdk(self.cli_ctx, ResourceType.MGMT_KEYVAULT, 'models.key_vault_management_client_enums#CertificatePermissions')
    StoragePermissions = get_sdk(self.cli_ctx, ResourceType.MGMT_KEYVAULT, 'models.key_vault_management_client_enums#StoragePermissions')
    NetworkRuleBypassOptions = get_sdk(self.cli_ctx, ResourceType.MGMT_KEYVAULT, 'models.key_vault_management_client_enums#NetworkRuleBypassOptions')
    NetworkRuleAction = get_sdk(self.cli_ctx, ResourceType.MGMT_KEYVAULT, 'models.key_vault_management_client_enums#NetworkRuleAction')
    # ARGUMENT DEFINITIONS
    vault_name_type = CLIArgumentType(
        help='Name of the key vault.', options_list=['--vault-name'], metavar='NAME', id_part=None,
        completer=get_resource_name_completion_list('Microsoft.KeyVault/vaults'))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # region KeyVault Storage Account

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('keyvault certificate issuer', arg_group='Organization Detail') as c:
        c.argument('organization_id')
        c.argument('admin_first_name')
        c.argument('admin_last_name')
        c.argument('admin_email')
        c.argument('admin_phone')
コード例 #33
0
ファイル: _params.py プロジェクト: pichandwork/azure-cli
def load_arguments(self, _):
    StorageAccountTypes, UpgradeMode, CachingTypes = self.get_models('StorageAccountTypes', 'UpgradeMode', 'CachingTypes')
    OperatingSystemTypes = self.get_models('OperatingSystemTypes')

    # REUSABLE ARGUMENT DEFINITIONS
    name_arg_type = CLIArgumentType(options_list=['--name', '-n'], metavar='NAME')
    multi_ids_type = CLIArgumentType(nargs='+')
    existing_vm_name = CLIArgumentType(overrides=name_arg_type,
                                       configured_default='vm',
                                       help="The name of the Virtual Machine. You can configure the default using `az configure --defaults vm=<name>`",
                                       completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachines'), id_part='name')
    existing_disk_name = CLIArgumentType(overrides=name_arg_type, help='The name of the managed disk', completer=get_resource_name_completion_list('Microsoft.Compute/disks'), id_part='name')
    existing_snapshot_name = CLIArgumentType(overrides=name_arg_type, help='The name of the snapshot', completer=get_resource_name_completion_list('Microsoft.Compute/snapshots'), id_part='name')
    vmss_name_type = CLIArgumentType(name_arg_type,
                                     configured_default='vmss',
                                     completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'),
                                     help="Scale set name. You can configure the default using `az configure --defaults vmss=<name>`",
                                     id_part='name')

    extension_instance_name_type = CLIArgumentType(help="Name of the vm's instance of the extension. Default: name of the extension.")

    if StorageAccountTypes:
        disk_sku = CLIArgumentType(arg_type=get_enum_type(StorageAccountTypes))
    else:
        # StorageAccountTypes introduced in api version 2016_04_30_preview of Resource.MGMT.Compute package..
        # However, 2017-03-09-profile targets version 2016-03-30 of compute package.
        disk_sku = CLIArgumentType(arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS']))

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

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

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

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

    # region Disks
    with self.argument_context('disk') as c:
        c.argument('zone', zone_type, min_api='2017-03-30', options_list=['--zone'])  # TODO: --size-gb currently has claimed -z. We can do a breaking change later if we want to.
        c.argument('disk_name', existing_disk_name, completer=get_resource_name_completion_list('Microsoft.Compute/disks'))
        c.argument('name', arg_type=name_arg_type)
        c.argument('sku', arg_type=disk_sku, help='Underlying storage SKU')
        c.argument('os_type', arg_type=get_enum_type(OperatingSystemTypes), help='The Operating System type of the Disk.')
        c.argument('disk_iops_read_write', type=int, min_api='2018-06-01', help='The number of IOPS allowed for this disk. Only settable for UltraSSD disks. One operation can transfer between 4k and 256k bytes')
        c.argument('disk_mbps_read_write', type=int, min_api='2018-06-01', help="The bandwidth allowed for this disk. Only settable for UltraSSD disks. MBps means millions of bytes per second with ISO notation of powers of 10")
    # endregion

    # region Snapshots
    with self.argument_context('snapshot', resource_type=ResourceType.MGMT_COMPUTE, operation_group='snapshots') as c:
        c.argument('snapshot_name', existing_snapshot_name, id_part='name', completer=get_resource_name_completion_list('Microsoft.Compute/snapshots'))
        c.argument('name', arg_type=name_arg_type)
        if self.supported_api_version(min_api='2018-04-01', operation_group='snapshots'):
            c.argument('sku', arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS', 'Standard_ZRS']))
        else:
            c.argument('sku', arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS']))
    # endregion

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

    with self.argument_context('image create') as c:
        # here we collpase all difference image sources to under 2 common arguments --os-disk-source --data-disk-sources
        c.argument('name', arg_type=name_arg_type, help='new image name')
        c.argument('source', help='OS disk source from the same region, including a virtual machine ID or name, OS disk blob URI, managed OS disk ID or name, or OS snapshot ID or name')
        c.argument('data_disk_sources', nargs='+', help='Space-separated list of data disk sources, including unmanaged blob URI, managed disk ID or name, or snapshot ID or name')
        c.argument('zone_resilient', min_api='2017-12-01', arg_type=get_three_state_flag(), help='Specifies whether an image is zone resilient or not. '
                   'Default is false. Zone resilient images can be created only in regions that provide Zone Redundant Storage')
        c.argument('storage_sku', arg_type=disk_sku, help='The SKU of the storage account with which to create the VM image. Unused if source VM is specified.')
        c.argument('os_disk_caching', arg_type=get_enum_type(CachingTypes), help="Storage caching type for the image's OS disk.")
        c.ignore('source_virtual_machine', 'os_blob_uri', 'os_disk', 'os_snapshot', 'data_blob_uris', 'data_disks', 'data_snapshots')
    # endregion

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

    with self.argument_context('vm availability-set create') as c:
        c.argument('availability_set_name', name_arg_type, validator=get_default_location_from_resource_group, help='Name of the availability set')
        c.argument('platform_update_domain_count', type=int, help='Update Domain count. If unspecified, the server will pick the most optimal number like 5.')
        c.argument('platform_fault_domain_count', type=int, help='Fault Domain count.')
        c.argument('validate', help='Generate and validate the ARM template without creating any resources.', action='store_true')
        c.argument('unmanaged', action='store_true', min_api='2016-04-30-preview', help='contained VMs should use unmanaged disks')

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

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

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

    with self.argument_context('vm update') as c:
        c.argument('os_disk', min_api='2017-12-01', help="Managed OS disk ID or name to swap to")
        c.argument('write_accelerator', nargs='*', min_api='2017-12-01',
                   help="enable/disable disk write accelerator. Use singular value 'true/false' to apply across, or specify individual disks, e.g.'os=true 1=true 2=true' for os disk and data disks with lun of 1 & 2")
        c.argument('disk_caching', nargs='*', help="Use singular value to apply across, or specify individual disks, e.g. 'os=ReadWrite 0=None 1=ReadOnly' should enable update os disk and 2 data disks")

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

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

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

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

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

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

    with self.argument_context('vm disk attach') as c:
        c.argument('enable_write_accelerator', min_api='2017-12-01', action='store_true', help='enable write accelerator')
        c.argument('disk', options_list=['--name', '-n', c.deprecate(target='--disk', redirect='--name', hide=True)],
                   help="The name or ID of the managed disk", validator=validate_vm_disk, id_part='name',
                   completer=get_resource_name_completion_list('Microsoft.Compute/disks'))

    with self.argument_context('vm disk detach') as c:
        c.argument('disk_name', arg_type=name_arg_type, help='The data disk name.')

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

    with self.argument_context('vm extension') as c:
        c.argument('vm_extension_name', name_arg_type, completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachines/extensions'), help='Name of the extension.', id_part='child_name_1')
        c.argument('vm_name', arg_type=existing_vm_name, options_list=['--vm-name'], id_part='name')
        c.argument('expand', deprecate_info=c.deprecate(expiration='2.1.0', hide=True))

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

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

    with self.argument_context('vm secret list') as c:
        c.argument('vm_name', arg_type=existing_vm_name, id_part=None)

    with self.argument_context('vm image') as c:
        c.argument('publisher_name', options_list=['--publisher', '-p'])
        c.argument('publisher', options_list=['--publisher', '-p'], help='image publisher')
        c.argument('offer', options_list=['--offer', '-f'], help='image offer')
        c.argument('plan', help='image billing plan')
        c.argument('sku', options_list=['--sku', '-s'], help='image sku')
        c.argument('version', help="image sku's version")
        c.argument('urn', help="URN, in format of 'publisher:offer:sku:version'. If specified, other argument values can be omitted")

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

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

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

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

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

    with self.argument_context('vm unmanaged-disk attach') as c:
        c.argument('disk_name', options_list=['--name', '-n'], help='The data disk name.')
        c.argument('size_gb', options_list=['--size-gb', '-z'], help='size in GB. Max size: 4095 GB (certain preview disks can be larger).', type=int)

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

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

    with self.argument_context('vm unmanaged-disk list') as c:
        c.argument('vm_name', options_list=['--vm-name', '--name', '-n'], arg_type=existing_vm_name, id_part=None)

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

    with self.argument_context('vm list-skus') as c:
        c.argument('size', options_list=['--size', '-s'], help="size name, partial name is accepted")
        c.argument('zone', options_list=['--zone', '-z'], arg_type=get_three_state_flag(), help="show all vm size supporting availability zones")
        c.argument('show_all', options_list=['--all'], arg_type=get_three_state_flag(),
                   help="show all information including vm sizes not available under the current subscription")
        c.argument('resource_type', options_list=['--resource-type', '-r'], help='resource types e.g. "availabilitySets", "snapshots", "disk", etc')

    with self.argument_context('vm restart') as c:
        c.argument('force', action='store_true', help='Force the VM to restart by redeploying it. Use if the VM is unresponsive.')
    # endregion

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

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

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

    with self.argument_context('vmss create') as c:
        VMPriorityTypes = self.get_models('VirtualMachinePriorityTypes', resource_type=ResourceType.MGMT_COMPUTE)
        VirtualMachineEvictionPolicyTypes = self.get_models('VirtualMachineEvictionPolicyTypes', resource_type=ResourceType.MGMT_COMPUTE)
        c.argument('name', name_arg_type)
        c.argument('nat_backend_port', default=None, help='Backend port to open with NAT rules.  Defaults to 22 on Linux and 3389 on Windows.')
        c.argument('single_placement_group', arg_type=get_three_state_flag(), help="Enable replicate using fault domains within the same cluster. Default to 'false' for any zonals, or with 100+ instances"
                   " See https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-placement-groups for details")
        c.argument('platform_fault_domain_count', type=int, help='Fault Domain count for each placement group in the availability zone', min_api='2017-12-01')
        c.argument('vmss_name', name_arg_type, id_part=None, help='Name of the virtual machine scale set.')
        c.argument('instance_count', help='Number of VMs in the scale set.', type=int)
        c.argument('disable_overprovision', help='Overprovision option (see https://azure.microsoft.com/en-us/documentation/articles/virtual-machine-scale-sets-overview/ for details).', action='store_true')
        c.argument('upgrade_policy_mode', help=None, arg_type=get_enum_type(UpgradeMode))
        c.argument('health_probe', help='(Preview) probe name from the existing load balancer, mainly used for rolling upgrade')
        c.argument('vm_sku', help='Size of VMs in the scale set. Default to "Standard_DS1_v2". See https://azure.microsoft.com/en-us/pricing/details/virtual-machines/ for size info.')
        c.argument('nsg', help='Name or ID of an existing Network Security Group.', arg_group='Network')
        c.argument('priority', resource_type=ResourceType.MGMT_COMPUTE, min_api='2017-12-01', arg_type=get_enum_type(VMPriorityTypes, default=None),
                   help="Priority. Use 'Low' to run short-lived workloads in a cost-effective way")
        c.argument('eviction_policy', resource_type=ResourceType.MGMT_COMPUTE, min_api='2017-12-01', arg_type=get_enum_type(VirtualMachineEvictionPolicyTypes, default=None),
                   help="(PREVIEW) The eviction policy for virtual machines in a low priority scale set.")
        c.argument('application_security_groups', resource_type=ResourceType.MGMT_COMPUTE, min_api='2018-06-01', nargs='+', options_list=['--asgs'], help='Space-separated list of existing application security groups to associate with the VM.', arg_group='Network', validator=validate_asg_names_or_ids)

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

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

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

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

    with self.argument_context('vmss disk') as c:
        options_list = ['--vmss-name'] + [c.deprecate(target=opt, redirect='--vmss-name', hide=True)for opt in name_arg_type.settings['options_list']]
        new_vmss_name_type = CLIArgumentType(overrides=vmss_name_type, options_list=options_list)

        c.argument('lun', type=int, help='0-based logical unit number (LUN). Max value depends on the Virtual Machine instance size.')
        c.argument('size_gb', options_list=['--size-gb', '-z'], help='size in GB. Max size: 4095 GB (certain preview disks can be larger).', type=int)
        c.argument('vmss_name', new_vmss_name_type, completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'))
        c.argument('disk', validator=validate_vmss_disk, help='existing disk name or ID to attach or detach from VM instances',
                   min_api='2017-12-01', completer=get_resource_name_completion_list('Microsoft.Compute/disks'))
        c.argument('instance_id', help='Scale set VM instance id', min_api='2017-12-01')
        c.argument('sku', arg_type=disk_sku, help='Underlying storage SKU')

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

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

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

    with self.argument_context('vmss nic list') as c:
        c.argument('virtual_machine_scale_set_name', arg_type=vmss_name_type, options_list=['--vmss-name'], id_part=None)
    # endregion

    # region VM & VMSS Shared
    for scope in ['vm', 'vmss']:
        with self.argument_context(scope) as c:
            c.argument('no_auto_upgrade', arg_type=get_three_state_flag(), help='If set, the extension service will not automatically pick or upgrade to the latest minor version, even if the extension is redeployed.')

        with self.argument_context('{} run-command'.format(scope)) as c:
            c.argument('command_id', completer=get_vm_run_command_completion_list, help="The command id. Use 'az {} run-command list' to get the list".format(scope))
            if scope == 'vmss':
                c.argument('vmss_name', vmss_name_type)

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

    for scope in ['vm identity assign', 'vmss identity assign']:
        with self.argument_context(scope) as c:
            c.argument('assign_identity', options_list=['--identities'], nargs='*', help="Space-separated identities to assign. Use '{0}' to refer to the system assigned identity. Default: '{0}'".format(MSI_LOCAL_ID))
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

    for scope in ['vm identity remove', 'vmss identity remove']:
        with self.argument_context(scope) as c:
            c.argument('identities', nargs='+', help="Space-separated identities to remove. Use '{0}' to refer to the system assigned identity. Default: '{0}'".format(MSI_LOCAL_ID))
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

    for scope in ['vm identity show', 'vmss identity show']:
        with self.argument_context(scope) as c:
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

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

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

        with self.argument_context(scope, arg_group='Storage') as c:
            if StorageAccountTypes:
                allowed_values = ", ".join([sku.value for sku in StorageAccountTypes])
            else:
                allowed_values = ", ".join(['Premium_LRS', 'Standard_LRS'])

            usage = 'Usage: [--storage-sku SKU | --storage-sku ID=SKU ID=SKU ID=SKU...], where each ID is "os" or a 0-indexed lun.'
            allowed_values = 'Allowed values: {}.'.format(allowed_values)
            storage_sku_help = 'The SKU of the storage account with which to persist VM. Use a singular sku that would be applied across all disks, ' \
                               'or specify individual disks. {} {}'.format(usage, allowed_values)

            c.argument('os_disk_name', help='The name of the new VM OS disk.')
            c.argument('os_type', help='Type of OS installed on a custom VHD. Do not use when specifying an URN or URN alias.', arg_type=get_enum_type(['windows', 'linux']))
            c.argument('storage_account', help="Only applicable when used with `--use-unmanaged-disk`. The name to use when creating a new storage account or referencing an existing one. If omitted, an appropriate storage account in the same resource group and location will be used, or a new one will be created.")
            c.argument('storage_sku', nargs='+', help=storage_sku_help)
            c.argument('storage_container_name', help="Only applicable when used with `--use-unmanaged-disk`. Name of the storage container for the VM OS disk. Default: vhds")
            c.ignore('os_publisher', 'os_offer', 'os_sku', 'os_version', 'storage_profile')
            c.argument('use_unmanaged_disk', action='store_true', help='Do not use managed disk to persist VM')
            c.argument('data_disk_sizes_gb', nargs='+', type=int, help='space-separated empty managed data disk sizes in GB to create')
            c.ignore('disk_info', 'storage_account_type', 'public_ip_address_type', 'nsg_type', 'nic_type', 'vnet_type', 'load_balancer_type', 'app_gateway_type')
            c.argument('os_caching', options_list=[self.deprecate(target='--storage-caching', redirect='--os-disk-caching', hide=True), '--os-disk-caching'], help='Storage caching type for the VM OS disk. Default: ReadWrite', arg_type=get_enum_type(CachingTypes))
            c.argument('data_caching', options_list=['--data-disk-caching'], nargs='+',
                       help="storage caching type for data disk(s), including 'None', 'ReadOnly', 'ReadWrite', etc. Use a singular value to apply on all disks, or use '<lun>=<vaule1> <lun>=<value2>' to configure individual disk")
            c.argument('ultra_ssd_enabled', arg_type=get_three_state_flag(), min_api='2018-06-01',
                       help='(PREVIEW) Enables or disables the capability to have 1 or more managed data disks with UltraSSD_LRS storage account')
            c.argument('ephemeral_os_disk', arg_type=get_three_state_flag(), min_api='2018-06-01',
                       help='(Preview) Allows you to create an OS disk directly on the host node, providing local disk performance and faster VM/VMSS reimage time.')

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

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

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

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

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

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

    with self.argument_context('vm extension set') as c:
        c.argument('force_update', action='store_true', help='force to update even if the extension configuration has not changed.')
        c.argument('extension_instance_name', extension_instance_name_type, arg_group='Resource Id')

    with self.argument_context('vmss extension set', min_api='2017-12-01') as c:
        c.argument('force_update', action='store_true', help='force to update even if the extension configuration has not changed.')
        c.argument('extension_instance_name', extension_instance_name_type)
        c.argument('provision_after_extensions', nargs='+', help='Space-separated list of extension names after which this extension should be provisioned. These extensions must already be set on the vm.')

    for scope in ['vm extension image', 'vmss extension image']:
        with self.argument_context(scope) as c:
            c.argument('image_location', options_list=['--location', '-l'], help='Image location.')
            c.argument('name', help='Image name', id_part=None)
            c.argument('publisher_name', options_list=['--publisher', '-p'], help='Image publisher name')
            c.argument('type', options_list=['--name', '-n'], help='Name of the extension')
            c.argument('latest', action='store_true', help='Show the latest version only.')
            c.argument('version', help='Extension version')
            c.argument('orderby', help="the $orderby odata query option")
            c.argument('top', help='the $top odata query option')

    for scope in ['vm create', 'vm update', 'vmss create', 'vmss update']:
        with self.argument_context(scope) as c:
            c.argument('license_type', help="license type if the Windows image or disk used was licensed on-premises", arg_type=get_enum_type(['Windows_Server', 'Windows_Client', 'None']))

    with self.argument_context('sig') as c:
        c.argument('gallery_name', options_list=['--gallery-name', '-r'], help='gallery name')
        c.argument('gallery_image_name', options_list=['--gallery-image-definition', '-i'], help='gallery image definition')
        c.argument('gallery_image_version', options_list=['--gallery-image-version', '-e'], help='gallery image version')

    for scope in ['sig show', 'sig image-definition show', 'sig image-definition delete']:
        with self.argument_context(scope) as c:
            c.argument('gallery_name', options_list=['--gallery-name', '-r'], id_part='name', help='gallery name')
            c.argument('gallery_image_name', options_list=['--gallery-image-definition', '-i'], id_part='child_name_1', help='gallery image definition')

    with self.argument_context('sig image-definition create') as c:
        c.argument('offer', options_list=['--offer', '-f'], help='image offer')
        c.argument('sku', options_list=['--sku', '-s'], help='image sku')
        c.argument('publisher', options_list=['--publisher', '-p'], help='image publisher')
        c.argument('os_type', arg_type=get_enum_type(['Windows', 'Linux']), help='the type of the OS that is included in the disk if creating a VM from user-image or a specialized VHD')
        c.ignore('os_state')  # service is not ready
        c.argument('minimum_cpu_core', type=int, arg_group='Recommendation', help='minimum cpu cores')
        c.argument('maximum_cpu_core', type=int, arg_group='Recommendation', help='maximum cpu cores')
        c.argument('minimum_memory', type=int, arg_group='Recommendation', help='minimum memory in MB')
        c.argument('maximum_memory', type=int, arg_group='Recommendation', help='maximum memory in MB')

        c.argument('plan_publisher', help='plan publisher', arg_group='Purchase plan')
        c.argument('plan_name', help='plan name', arg_group='Purchase plan')
        c.argument('plan_product', help='plan product', arg_group='Purchase plan')

        c.argument('eula', help='The Eula agreement for the gallery image')
        c.argument('privacy_statement_uri', help='The privacy statement uri')
        c.argument('release_note_uri', help='The release note uri')
        c.argument('end_of_life_date', help="the end of life date, e.g. '2020-12-31'")
        c.argument('disallowed_disk_types', nargs='*', help='disk types which would not work with the image, e.g., Standard_LRS')

    with self.argument_context('sig create') as c:
        c.argument('description', help='the description of the gallery')
    with self.argument_context('sig update') as c:
        c.ignore('gallery')
    with self.argument_context('sig image-definition create') as c:
        c.argument('description', help='the description of the gallery image definition')
    with self.argument_context('sig image-definition update') as c:
        c.ignore('gallery_image')

    with self.argument_context('sig image-version') as c:
        deprecated_option = c.deprecate(target='--gallery-image-version-name', redirect='--gallery-image-version', hide=True, expiration="2.1.0")
        c.argument('gallery_image_version_name', options_list=['--gallery-image-version', '-e', deprecated_option], )

    with self.argument_context('sig image-version create') as c:
        c.argument('gallery_image_version', options_list=['--gallery-image-version', '-e'],
                   help='Gallery image version in semantic version pattern. The allowed characters are digit and period. Digits must be within the range of a 32-bit integer, e.g. <MajorVersion>.<MinorVersion>.<Patch>')
        c.argument('description', help='the description of the gallery image version')
        c.argument('managed_image', help='image name(if in the same resource group) or resource id')
        c.argument('exclude_from_latest', arg_type=get_three_state_flag(), help='The flag means that if it is set to true, people deploying VMs with version omitted will not use this version.')
        c.argument('version', help='image version')
        c.argument('end_of_life_date', help="the end of life date, e.g. '2020-12-31'")

    with self.argument_context('sig image-version show') as c:
        c.argument('expand', help="The expand expression to apply on the operation, e.g. 'ReplicationStatus'")
    for scope in ['sig image-version create', 'sig image-version update']:
        with self.argument_context(scope) as c:
            c.argument('target_regions', nargs='*', validator=process_gallery_image_version_namespace,
                       help='Space-separated list of regions and their replica counts. Use "<region>=<replica count>" to set the replica count for each region. If only the region is specified, the default replica count will be used.')
            c.argument('replica_count', help='The default number of replicas to be created per region. To set regional replication counts, use --target-regions', type=int)
コード例 #34
0
ファイル: _params.py プロジェクト: yugangw-msft/azure-cli
def load_arguments(self, _):
    from ._completers import subnet_completion_list
    from knack.arguments import CLIArgumentType
    from azure.mgmt.hdinsight.models import Tier, JsonWebKeyEncryptionAlgorithm
    node_size_type = CLIArgumentType(arg_group='Node',
                                     help='The size of the node. See also: https://docs.microsoft.com/en-us/azure/'
                                          'hdinsight/hdinsight-hadoop-provision-linux-clusters#configure-cluster-size')

    # cluster
    with self.argument_context('hdinsight') as c:

        # Cluster
        c.argument('cluster_name', arg_type=name_type,
                   completer=get_resource_name_completion_list('Microsoft.HDInsight/clusters'),
                   help='The name of the cluster.')
        c.argument('tags', tags_type)
        c.argument('cluster_version', options_list=['--version', '-v'], arg_group='Cluster',
                   help='The HDInsight cluster version. See also: https://docs.microsoft.com/en-us/azure/'
                        'hdinsight/hdinsight-component-versioning#supported-hdinsight-versions')
        c.argument('cluster_type', options_list=['--type', '-t'], arg_group='Cluster',
                   completer=get_generic_completion_list(known_cluster_types),
                   help='Type of HDInsight cluster, like: {}. '
                        'See also: https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-'
                        'hadoop-provision-linux-clusters#cluster-types'.format(', '.join(known_cluster_types)))
        c.argument('component_version', arg_group='Cluster', nargs='*', validator=validate_component_version,
                   help='The versions of various Hadoop components, in space-'
                        'separated versions in \'component=version\' format. Example: '
                        'Spark=2.0 Hadoop=2.7.3 '
                        'See also: https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight'
                        '-component-versioning#hadoop-components-available-with-different-'
                        'hdinsight-versions')
        c.argument('cluster_configurations', arg_group='Cluster',
                   help='Extra configurations of various components, in JSON.')
        c.argument('cluster_tier', arg_type=get_enum_type(Tier), arg_group='Cluster',
                   help='The tier of the cluster')
        c.argument('esp', arg_group='Cluster', arg_type=get_three_state_flag(),
                   help='Specify to create cluster with Enterprise Security Package')

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

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

        # Node
        c.argument('headnode_size', arg_type=node_size_type)
        c.argument('workernode_size', arg_type=node_size_type)
        c.argument('workernode_data_disks_per_node', arg_group='Node',
                   help='The number of data disks to use per worker node.')
        c.argument('workernode_data_disk_storage_account_type', arg_group='Node',
                   arg_type=get_enum_type(['standard_lrs', 'premium_lrs']),
                   help='The type of storage account that will be used for the data disks: standard_lrs or premium_lrs')
        c.argument('workernode_data_disk_size', arg_group='Node',
                   help='The size of the data disk in GB, e.g. 1023.')
        c.argument('zookeepernode_size', arg_type=node_size_type)
        c.argument('edgenode_size', arg_type=node_size_type)
        c.argument('workernode_count', options_list=['--size', '-s'], arg_group='Node',
                   help='The number of worker nodes in the cluster.')

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

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

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

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

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

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

    # application
    with self.argument_context('hdinsight application') as c:
        c.argument('application_name', arg_group='Application', help='The constant value for the application name.')
        c.argument('application_type', arg_group='Application', help='The application type.')
        c.argument('marketplace_identifier', arg_group='Application', help='The marketplace identifier.')
        c.argument('https_endpoint_access_mode', arg_group='HTTPS Endpoint',
                   help='The access mode for the application.')
        c.argument('https_endpoint_destination_port', arg_group='HTTPS Endpoint',
                   help='The destination port to connect to.')
        c.argument('https_endpoint_location', arg_group='HTTPS Endpoint', help='The location of the endpoint.')
        c.argument('https_endpoint_public_port', arg_group='HTTPS Endpoint', help='The public port to connect to.')
        c.argument('ssh_endpoint_destination_port', arg_group='SSH Endpoint',
                   help='The destination port to connect to.')
        c.argument('ssh_endpoint_location', arg_group='SSH Endpoint', help='The location of the endpoint.')
        c.argument('ssh_endpoint_public_port', arg_group='SSH Endpoint', help='The public port to connect to.')
        c.argument('tags', tags_type)
        c.argument('ssh_password', options_list=['--ssh-password', '-P'], arg_group='SSH',
                   help='SSH password for the cluster nodes.')

    # script action
    with self.argument_context('hdinsight script-action') as c:
        c.argument('roles', arg_group='Script Action',
                   completer=get_generic_completion_list(known_role_types),
                   help='A comma-delimited list of roles (nodes) where the script will be executed. '
                        'Valid roles are {}.'.format(', '.join(known_role_types)))
        c.argument('persist_on_success', arg_group='Script Action', help='If the scripts needs to be persisted.')
        c.argument('persisted', arg_group='Script Action', help='If only list persisted script actions.')
        c.argument('script_name', options_list='--script-action-name', arg_group='Script Action',
                   help='The name of the script action.')

    # OMS
    with self.argument_context('hdinsight oms') as c:
        c.argument('workspace_id', arg_group='OMS', help='The Operations Management Suite (OMS) workspace ID.')
        c.argument('primary_key', arg_group='OMS', help='The Operations Management Suite (OMS) workspace key.')
コード例 #35
0
ファイル: _params.py プロジェクト: tjacobhi/azure-cli
def load_arguments(self, _):  # pylint: disable=too-many-statements

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

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

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

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

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

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

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

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

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

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

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

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

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

            c.argument(
                'server_name',
                options_list=['--name', '-n'],
                id_part='name',
                help=
                'Name of the server. The name can contain only lowercase letters, numbers, and the hyphen (-) character. Minimum 3 characters and maximum 63 characters.'
            )
            c.argument(
                'administrator_login',
                options_list=['--admin-user', '-u'],
                help=
                'Administrator username for the server. Once set, it cannot be changed.'
            )
            c.argument(
                'administrator_login_password',
                options_list=['--admin-password', '-p'],
                help=
                'The password of the administrator. Minimum 8 characters and maximum 128 characters. Password must contain characters from three of the following categories: English uppercase letters, English lowercase letters, numbers, and non-alphanumeric characters.'
            )
            c.argument(
                'ssl_enforcement',
                arg_type=get_enum_type(['Enabled', 'Disabled']),
                options_list=['--ssl-enforcement'],
                help=
                'Enable or disable ssl enforcement for connections to server. Default is Enabled.'
            )
            c.argument(
                'public_network_access',
                arg_type=get_enum_type(['Enabled', 'Disabled']),
                options_list=['--public-network-access'],
                help=
                'Set whether public network access to server is allowed or not. When false, only connections made through Private Links can reach this server.'
            )
            c.argument('tier',
                       arg_type=get_enum_type(
                           ['Basic', 'GeneralPurpose', 'MemoryOptimized']),
                       options_list=['--performance-tier'],
                       help='The performance tier of the server.')
            c.argument('capacity',
                       options_list=['--vcore'],
                       type=int,
                       help='Number of vcore.')
            c.argument('family',
                       options_list=['--family'],
                       arg_type=get_enum_type(['Gen4', 'Gen5']),
                       help='Hardware generation.')
            c.argument(
                'storage_mb',
                options_list=['--storage-size'],
                type=int,
                help=
                'The storage capacity of the server (unit is megabytes). Minimum 5120 and increases in 1024 increments. Default is 51200.'
            )
            c.argument(
                'backup_retention',
                options_list=['--backup-retention'],
                type=int,
                help=
                'The number of days a backup is retained. Range of 7 to 35 days. Default is 7 days.',
                validator=retention_validator)
            c.argument(
                'auto_grow',
                arg_type=get_enum_type(['Enabled', 'Disabled']),
                options_list=['--auto-grow'],
                help=
                'Enable or disable autogrow of the storage. Default value is Enabled.'
            )
            c.argument(
                'assign_identity',
                options_list=['--assign-identity'],
                help=
                'Generate and assign an Azure Active Directory Identity for this server for use with key management services like Azure KeyVault.'
            )
            c.argument('tags', tags_type)

            if scope == 'mariadb server':
                c.ignore('assign_identity')

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

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

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

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

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

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

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

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

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

    for scope in ['mysql server key', 'postgres server key']:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--name', '-s'])
            c.argument(
                'kid',
                options_list=['--kid', '-k'],
                help=
                'The Azure Key Vault key identifier of the server key. An example key identifier is "https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901"'
            )
コード例 #36
0
ファイル: _params.py プロジェクト: derekbekoe/azure-cli
def load_arguments(self, _):  # pylint: disable=too-many-statements
    with self.argument_context('acr') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location', arg_type=get_location_type(self.cli_ctx))
        c.argument('tags', arg_type=tags_type)
        c.argument('registry_name', options_list=['--name', '-n'], help='The name of the container registry. You can configure the default registry name using `az configure --defaults acr=<registry name>`', completer=get_resource_name_completion_list(REGISTRY_RESOURCE_TYPE), configured_default='acr')
        c.argument('storage_account_name', help='Provide the name of an existing storage account if you\'re recreating a container registry over a previous registry created storage account. Only applicable to Classic SKU.', completer=get_resource_name_completion_list(STORAGE_RESOURCE_TYPE))
        c.argument('sku', help='The SKU of the container registry', choices=MANAGED_REGISTRY_SKU + CLASSIC_REGISTRY_SKU)
        c.argument('admin_enabled', help='Indicates whether the admin user is enabled', arg_type=get_three_state_flag())
        c.argument('password_name', help='The name of password to regenerate', choices=['password', 'password2'])
        c.argument('username', options_list=['--username', '-u'], help='The username used to log into a container registry')
        c.argument('password', options_list=['--password', '-p'], help='The password used to log into a container registry')
        c.argument('image_names', options_list=['--image', '-t'], help="The image repository and optionally a tag in the 'repository:tag' format.", action='append')
        c.argument('docker_file_path', options_list=['--file', '-f'], help="The relative path of the the docker file to the source code root folder.")
        c.argument('build_arg', help="Build argument in 'name[=value]' format.", action='append', validator=validate_build_arg)
        c.argument('secret_build_arg', help="Secret build argument in 'name[=value]' format.", action='append', validator=validate_secret_build_arg)
        c.argument('no_push', help="Indicates whether the image built should be pushed to the registry.", arg_type=get_three_state_flag())
        c.argument('no_logs', help="Do not show logs after successfully queuing the build.", action='store_true')

    with self.argument_context('acr repository delete') as c:
        c.argument('manifest', nargs='?', required=False, const='', default=None, help=argparse.SUPPRESS)
        c.argument('yes', options_list=['--yes', '-y'], action='store_true', help='Do not prompt for confirmation')
        c.argument('repository', help="The name of the repository to delete")
        c.argument('tag', help=argparse.SUPPRESS)
        c.argument('image', help="The name of the image to delete. May include a tag in the format 'name:tag' or digest in the format 'name@digest'.")

    with self.argument_context('acr repository untag') as c:
        c.argument('image', help="The name of the image to untag. May include a tag in the format 'name:tag'.")

    with self.argument_context('acr repository show-manifests') as c:
        c.argument('repository', help='The repository to obtain manifests from.')

    with self.argument_context('acr repository show-tags') as c:
        c.argument('repository', help='The repository to obtain tags from.')

    with self.argument_context('acr create') as c:
        c.argument('registry_name', completer=None, validator=validate_registry_name)
        c.argument('deployment_name', arg_type=deployment_name_type, validator=None)
        c.argument('location', arg_type=get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)

    with self.argument_context('acr check-name') as c:
        c.argument('registry_name', completer=None)

    with self.argument_context('acr webhook') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('webhook_name', options_list=['--name', '-n'], help='The name of the webhook', completer=get_resource_name_completion_list(WEBHOOK_RESOURCE_TYPE))
        c.argument('uri', help='The service URI for the webhook to post notifications.')
        c.argument('headers', nargs='+', help="Space-separated custom headers in 'key[=value]' format that will be added to the webhook notifications. Use {} to clear existing headers.".format(quotes), validator=validate_headers)
        c.argument('actions', nargs='+', help='Space-separated list of actions that trigger the webhook to post notifications.', choices=['push', 'delete'])
        c.argument('status', help='Indicates whether the webhook is enabled.', choices=['enabled', 'disabled'])
        c.argument('scope', help="The scope of repositories where the event can be triggered. For example, 'foo:*' means events for all tags under repository 'foo'. 'foo:bar' means events for 'foo:bar' only. 'foo' is equivalent to 'foo:latest'. Empty means events for all repositories.")

    with self.argument_context('acr webhook create') as c:
        c.argument('webhook_name', completer=None)

    with self.argument_context('acr replication') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.argument('replication_name', options_list=['--name', '-n'], help='The name of the replication.', completer=get_resource_name_completion_list(REPLICATION_RESOURCE_TYPE))

    with self.argument_context('acr replication create') as c:
        c.argument('replication_name', help='The name of the replication. Default to the location name.', completer=None)

    with self.argument_context('acr build') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        c.positional('source_location', help="The local source code directory path (e.g., './src') or the URL to a git repository (e.g., 'https://github.com/Azure-Samples/acr-build-helloworld-node.git') or a remote tarball (e.g., 'http://server/context.tar.gz').", completer=FilesCompleter())
        c.argument('timeout', help='The build timeout in seconds.')

    with self.argument_context('acr build-task') as c:
        c.argument('registry_name', options_list=['--registry', '-r'])
        # build task parameters
        c.argument('build_task_name', options_list=['--name', '-n'], help='The name of the build task.', completer=get_resource_name_completion_list(BUILD_TASK_RESOURCE_TYPE))
        c.argument('alias', help='The alternative name for build task. Default to the build task name.')
        c.argument('status', help='The current status of build task.', choices=[BuildTaskStatus.enabled.value, BuildTaskStatus.disabled.value])
        c.argument('os_type', options_list=['--os'], help='The operating system type required for the build.', choices=[OsType.linux.value, OsType.windows.value])
        c.argument('cpu', type=int, help='The CPU configuration in terms of number of cores required for the build.')
        c.argument('timeout', type=int, help='Build timeout in seconds.')
        c.argument('repository_url', options_list=['--context', '-c'], help="The full URL to the source code respository.")
        c.argument('commit_trigger_enabled', help="Indicates whether the source control commit trigger is enabled.", arg_type=get_three_state_flag())
        c.argument('git_access_token', help="The access token used to access the source control provider.")
        # build step parameters
        c.argument('step_name', help='The name of the build step.', completer=get_resource_name_completion_list(BUILD_STEP_RESOURCE_TYPE))
        c.argument('branch', help="The source control branch name.")
        c.argument('no_cache', help='Indicates whether the image cache is enabled.', arg_type=get_three_state_flag())
        c.argument('base_image_trigger', help="The type of the auto trigger for base image dependency updates.", choices=[BaseImageTriggerType.all.value,
                                                                                                                          BaseImageTriggerType.runtime.value,
                                                                                                                          BaseImageTriggerType.none.value])
        # build parameters
        c.argument('top', help='Limit the number of latest builds in the results.')
        c.argument('build_id', help='The unique build identifier.')
        c.argument('build_status', help='The current status of build.', choices=[BuildStatus.queued.value,
                                                                                 BuildStatus.started.value,
                                                                                 BuildStatus.running.value,
                                                                                 BuildStatus.succeeded.value,
                                                                                 BuildStatus.failed.value,
                                                                                 BuildStatus.canceled.value,
                                                                                 BuildStatus.error.value,
                                                                                 BuildStatus.timeout.value])

    with self.argument_context('acr build-task create') as c:
        c.argument('build_task_name', completer=None)
コード例 #37
0
ファイル: _params.py プロジェクト: adilliadil/azure-cli
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. The value must be an escaped JSON string.",
        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)

    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']))
        c.argument(
            'endpoint',
            help=
            'If auth mode is "login", provide endpoint URL of the App Configuration. The endpoint can be retrieved using "az appconfig show" command. You can configure the default endpoint using `az configure --defaults appconfig_endpoint=<endpoint>`',
            configured_default='appconfig_endpoint')
        c.argument(
            'auth_mode',
            arg_type=get_enum_type(['login', 'key']),
            configured_default='appconfig_auth_mode',
            validator=validate_auth_mode,
            help=
            'This parameter can be used for indicating how a data operation is to be authorized. '
            +
            'If the auth mode is "key", provide connection string or store name and your account access keys will be retrieved for authorization. '
            +
            'If the auth mode is "login", provide the store endpoint or store name and your "az login" credentials will be used for authorization. '
            +
            'You can configure the default auth mode using `az configure --defaults appconfig_auth_mode=<auth_mode>`. '
            +
            'For more information, see https://docs.microsoft.com/en-us/azure/azure-app-configuration/concept-enable-rbac'
        )

    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,
            help=
            'Space-separated list of managed identities to be assigned. Use "[system]" to refer to system-assigned managed identity or a resource ID to refer to user-assigned managed identity. If this argument is provided without any value, system-assigned managed identity will be assigned by default. If this argument is not provided, no managed identities will be assigned to this App Configuration store.'
        )
        c.argument(
            'enable_public_network',
            options_list=['--enable-public-network', '-e'],
            arg_type=get_three_state_flag(),
            is_preview=True,
            help=
            'When true, requests coming from public networks have permission to access this store while private endpoint is enabled. When false, only requests made through Private Links can reach this store.'
        )
        c.argument(
            'disable_local_auth',
            arg_type=get_three_state_flag(),
            is_preview=True,
            help=
            'Disable all authentication methods other than AAD authentication.'
        )

    with self.argument_context('appconfig update') as c:
        c.argument('tags', arg_type=tags_type)
        c.argument(
            'enable_public_network',
            options_list=['--enable-public-network', '-e'],
            arg_type=get_three_state_flag(),
            is_preview=True,
            help=
            'When true, requests coming from public networks have permission to access this store while private endpoint is enabled. When false, only requests made through Private Links can reach this store.'
        )
        c.argument(
            'disable_local_auth',
            arg_type=get_three_state_flag(),
            is_preview=True,
            help=
            'Disable all authentication methods other than AAD authentication.'
        )

    with self.argument_context('appconfig update',
                               arg_group='Customer Managed Key') 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 managed identity by default.'
        )

    with self.argument_context('appconfig identity assign') as c:
        c.argument(
            'identities',
            arg_type=identities_arg_type,
            help=
            "Accept system-assigned or user-assigned managed identities separated by spaces. Use '[system]' to refer to system-assigned managed identity or a resource ID to refer to user-assigned managed identity. If this argument is not provided or this argument is provided without any value, system-assigned managed identity will be used by default."
        )

    with self.argument_context('appconfig identity remove') as c:
        c.argument(
            'identities',
            arg_type=identities_arg_type,
            help=
            "Accept system-assigned or user-assigned managed identities separated by spaces. Use '[system]' to refer to system-assigned managed identity, '[all]' for all managed identities or a resource ID to refer user-assigned managed identity. If this argument is not provided or this argument is provided without any value, system-assigned managed identity will be removed by default."
        )

    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 if --separator is provided. 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. 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."
        )
        c.argument(
            'src_endpoint',
            help=
            'If --src-auth-mode is "login", provide endpoint URL of the source App Configuration.'
        )
        c.argument(
            'src_auth_mode',
            arg_type=get_enum_type(['login', 'key']),
            help=
            'Auth mode for connecting to source App Configuration. For details, refer to "--auth-mode" argument.'
        )

    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 key-value pairs to json or yaml file. 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 key-value pairs to json or yaml file. 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."
        )
        c.argument(
            'dest_endpoint',
            help=
            'If --dest-auth-mode is "login", provide endpoint URL of the destination App Configuration.'
        )
        c.argument(
            'dest_auth_mode',
            arg_type=get_enum_type(['login', 'key']),
            help=
            'Auth mode for connecting to destination App Configuration. For details, refer to "--auth-mode" argument.'
        )

    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. Use '\\0' for null label."
        )

    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.")
コード例 #38
0
ファイル: _params.py プロジェクト: zhangyan133/azure-cli
def load_arguments(self, _):
    # synapse workspace
    for scope in ['show', 'create', 'update', 'delete', 'activate']:
        with self.argument_context('synapse workspace ' + scope) as c:
            c.argument('workspace_name', arg_type=name_type, id_part='name', help='The workspace name.')

    for scope in ['create', 'update']:
        with self.argument_context('synapse workspace ' + scope) as c:
            c.argument('sql_admin_login_password', options_list=['--sql-admin-login-password', '-p'],
                       help='The sql administrator login password.')
            c.argument('tags', arg_type=tags_type)
            c.argument('allowed_aad_tenant_ids', options_list=['--allowed-tenant-ids'], nargs='+', help="The approved Azure AD tenants which outbound data traffic allowed to. The Azure AD tenant of the current user will be included by default. Use ""(\'""\' in PowerShell) to disable all allowed tenant ids.")
            c.argument('key_name', help='The workspace customer-managed key display name. All existing keys can be found using "az synapse workspace key list" cmdlet.')

    with self.argument_context('synapse workspace create') as c:
        c.argument('location', get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)
        c.argument("storage_account", validator=validate_storage_account,
                   help='The data lake storage account name or resource id.')
        c.argument('file_system', help='The file system of the data lake storage account.')
        c.argument('sql_admin_login_user', options_list=['--sql-admin-login-user', '-u'],
                   help='The sql administrator login user name.')
        c.argument('enable_managed_virtual_network', options_list=['--enable-managed-vnet',
                                                                   '--enable-managed-virtual-network'],
                   arg_type=get_three_state_flag(),
                   help='The flag indicates whether enable managed virtual network.')
        c.argument('prevent_data_exfiltration', arg_type=get_three_state_flag(),
                   help='The flag indicates whether enable data exfiltration.', options_list=['--prevent-exfiltration', '--prevent-data-exfiltration'])
        c.argument('key_identifier', help='The customer-managed key used to encrypt all data at rest in the workspace. Key identifier should be in the format of: https://{keyvaultname}.vault.azure.net/keys/{keyname}.', options_list=['--key-identifier', '--cmk'])

    with self.argument_context('synapse workspace check-name') as c:
        c.argument('name', arg_type=name_type, help='The name you wanted to check.')

    # synapse spark pool
    with self.argument_context('synapse spark pool') as c:
        c.argument('workspace_name', id_part='name', help='The workspace name.')

    with self.argument_context('synapse spark pool list') as c:
        c.argument('workspace_name', id_part=None, help='The workspace name.')

    for scope in ['show', 'create', 'update', 'delete']:
        with self.argument_context('synapse spark pool ' + scope) as c:
            c.argument('spark_pool_name', arg_type=name_type, id_part='child_name_1',
                       help='The name of the Spark pool.')

    with self.argument_context('synapse spark pool create') as c:
        # Node
        c.argument('node_count', type=int, arg_group='Node', help='The number of node.')
        c.argument('node_size_family', arg_group='Node', help='The node size family.')
        c.argument('node_size', arg_group='Node', arg_type=get_enum_type(['Small', 'Medium', 'Large']),
                   help='The node size.')

        # AutoScale
        c.argument('enable_auto_scale', arg_type=get_three_state_flag(), arg_group='AutoScale',
                   help='The flag of enabling auto scale.')
        c.argument('max_node_count', type=int, arg_group='AutoScale', help='The max node count.')
        c.argument('min_node_count', type=int, arg_group='AutoScale', help='The min node count.')

        # AutoPause
        c.argument('enable_auto_pause', arg_type=get_three_state_flag(), arg_group='AutoPause',
                   help='The flag of enabling auto pause.')
        c.argument('delay', arg_group='AutoPause', help='The delay time whose unit is minute.')

        # Environment Configuration
        c.argument('library_requirements', arg_group='Environment Configuration',
                   help='The library requirements file.')

        # Default Folder
        c.argument('spark_events_folder', arg_group='Default Folder', help='The Spark events folder.')
        c.argument('spark_log_folder', arg_group='Default Folder', help='The default Spark log folder.')

        # Component Version
        c.argument('spark_version', arg_group='Component Version', help='The supported Spark version is 2.4 now.')

        c.argument('tags', arg_type=tags_type)

    with self.argument_context('synapse spark pool update') as c:
        c.argument('tags', arg_type=tags_type)
        # Node
        c.argument('node_count', type=int, arg_group='Node', help='The number of node.')
        c.argument('node_size_family', arg_group='Node', help='The node size family.')

        c.argument('node_size', arg_group='Node', arg_type=get_enum_type(['Small', 'Medium', 'Large']),
                   help='The node size.')
        # AutoScale
        c.argument('enable_auto_scale', arg_type=get_three_state_flag(), arg_group='AutoScale',
                   help='The flag of enabling auto scale.')
        c.argument('max_node_count', type=int, arg_group='AutoScale', help='The max node count.')
        c.argument('min_node_count', type=int, arg_group='AutoScale', help='The min node count.')

        # AutoPause
        c.argument('enable_auto_pause', arg_type=get_three_state_flag(), arg_group='AutoPause',
                   help='The flag of enabling auto pause.')
        c.argument('delay', arg_group='AutoPause', help='The delay time whose unit is minute.')

        # Environment Configuration
        c.argument('library_requirements', arg_group='Environment Configuration',
                   help='The library requirements file.')
        c.argument('force', arg_type=get_three_state_flag(), help='The flag of force operation.')

    # synapse sql pool
    with self.argument_context('synapse sql pool') as c:
        c.argument('workspace_name', id_part='name', help='The workspace name.')

    with self.argument_context('synapse sql pool list') as c:
        c.argument('workspace_name', id_part=None, help='The workspace name.')

    with self.argument_context('synapse sql pool list-deleted') as c:
        c.argument('workspace_name', id_part=None, help='The workspace name.')

    for scope in ['show', 'create', 'delete', 'update', 'pause', 'resume', 'restore', 'show-connection-string']:
        with self.argument_context('synapse sql pool ' + scope) as c:
            c.argument('sql_pool_name', arg_type=name_type, id_part='child_name_1', help='The SQL pool name.')

    with self.argument_context('synapse sql pool create') as c:
        c.argument('performance_level', help='The performance level.')
        c.argument('source_database_id', help='The source database id.')
        c.argument('recoverable_database_id', help='The recoverable database id.')
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('synapse sql pool update') as c:
        c.argument('sku_name', options_list=['--performance-level'], help='The performance level.')
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('synapse sql pool restore') as c:
        c.argument('performance_level', help='The performance level.')
        c.argument('destination_name', options_list=['--dest-name', '--destination-name'],
                   help='Name of the sql pool that will be created as the restore destination.')

        restore_point_arg_group = 'Restore Point'
        c.argument('restore_point_in_time',
                   options_list=['--time', '-t'],
                   arg_group=restore_point_arg_group,
                   help='The point in time of the source database that will be restored to create the new database. Must be greater than or equal to the source database\'s earliestRestoreDate value. Either --time or --deleted-time (or both) must be specified. {0}'.format(
                       time_format_help))
        c.argument('source_database_deletion_date',
                   options_list=['--deleted-time'],
                   arg_group=restore_point_arg_group,
                   help='If specified, restore from a deleted database instead of from an existing database. Must match the deleted time of a deleted database in the same server. Either --time or --deleted-time (or both) must be specified. {0}'.format(
                       time_format_help))

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

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

    # synapse sql pool classification
    with self.argument_context('synapse sql pool classification') as c:
        c.argument('sql_pool_name', arg_type=name_type, id_part='child_name_1', help='The SQL pool name.')

    with self.argument_context('synapse sql pool classification list') as c:
        c.argument('workspace_name', id_part=None, help='The workspace name.')

    with self.argument_context('synapse sql pool classification recommendation list') as c:
        c.argument('workspace_name', id_part=None, help='The workspace name.')
        c.argument('include_disabled_recommendations', options_list=['--included-disabled'],
                   arg_type=get_three_state_flag(),
                   help='Indicates whether the result should include disabled recommendations')

    for scope in ['show', 'create', 'update', 'delete', 'recommendation enable', 'recommendation disable']:
        with self.argument_context('synapse sql pool classification ' + scope) as c:
            c.argument('schema_name', help='The name of schema.', options_list=['--schema'])
            c.argument('table_name', help='The name of table.', options_list=['--table'])
            c.argument('column_name', help='The name of column.', options_list=['--column'])
            c.argument('information_type', help='The information type.')
            c.argument('label_name', help='The label name.', options_list=['--label'])

    # synapse sql pool tde
    with self.argument_context('synapse sql pool tde') as c:
        c.argument('sql_pool_name', arg_type=name_type, id_part='child_name_1', help='The SQL pool name.')
        c.argument('status', arg_type=get_enum_type(TransparentDataEncryptionStatus),
                   required=True, help='Status of the transparent data encryption.')

    # synapse sql pool threat-policy
    with self.argument_context('synapse sql pool threat-policy') as c:
        c.argument('sql_pool_name', arg_type=name_type, id_part='child_name_1', help='The SQL pool name.')

    with self.argument_context('synapse sql pool threat-policy update') as c:
        _configure_security_or_audit_policy_storage_params(c)
        notification_arg_group = 'Notification'

        c.argument('state',
                   arg_group=policy_arg_group,
                   help='Threat detection policy state',
                   arg_type=get_enum_type(SecurityAlertPolicyState))
        c.argument('retention_days',
                   type=int,
                   arg_group=policy_arg_group,
                   help='The number of days to retain threat detection logs.')
        c.argument('disabled_alerts',
                   arg_group=policy_arg_group,
                   help='List of disabled alerts.',
                   nargs='+')
        c.argument('email_addresses',
                   arg_group=notification_arg_group,
                   help='List of email addresses that alerts are sent to.',
                   nargs='+')
        c.argument('email_account_admins',
                   arg_group=notification_arg_group,
                   help='Whether the alert is sent to the account administrators.',
                   arg_type=get_three_state_flag())

    # synapse sql pool audit-policy
    with self.argument_context('synapse sql pool audit-policy') as c:
        c.argument('sql_pool_name', arg_type=name_type, id_part='child_name_1', help='The SQL pool name.')

    for scope in ['synapse sql pool audit-policy', 'synapse sql audit-policy']:
        with self.argument_context(scope + ' update') as c:
            _configure_security_or_audit_policy_storage_params(c)
            c.argument('storage_account_subscription_id', arg_group=storage_arg_group,
                       options_list=['--storage-subscription'],
                       help='The subscription id of storage account')
            c.argument('is_storage_secondary_key_in_use', arg_group=storage_arg_group,
                       arg_type=get_three_state_flag(), options_list=['--use-secondary-key'],
                       help='Indicates whether using the secondary storeage key or not')
            c.argument('is_azure_monitor_target_enabled', options_list=['--enable-azure-monitor'],
                       help='Whether enabling azure monitor target or not.',
                       arg_type=get_three_state_flag())
            c.argument('state',
                       arg_group=policy_arg_group,
                       help='Auditing policy state',
                       arg_type=get_enum_type(BlobAuditingPolicyState))
            c.argument('audit_actions_and_groups',
                       options_list=['--actions'],
                       arg_group=policy_arg_group,
                       help='List of actions and action groups to audit.',
                       nargs='+')
            c.argument('retention_days',
                       type=int,
                       arg_group=policy_arg_group,
                       help='The number of days to retain audit logs.')

    with self.argument_context('synapse sql audit-policy update') as c:
        c.argument('queue_delay_milliseconds', type=int,
                   options_list=['--queue-delay-time', '--queue-delay-milliseconds'],
                   help='The amount of time in milliseconds that can elapse before audit actions are forced to be processed')

    with self.argument_context('synapse sql ad-admin') as c:
        c.argument('workspace_name', help='The workspace name.')
    for scope in ['create', 'update']:
        with self.argument_context('synapse sql ad-admin ' + scope) as c:
            c.argument('login_name', options_list=['--display-name', '-u'],
                       help='Display name of the Azure AD administrator user or group.')
            c.argument('object_id', options_list=['--object-id', '-i'],
                       help='The unique ID of the Azure AD administrator.')

    # synapse workspace firewall-rule
    with self.argument_context('synapse workspace firewall-rule') as c:
        c.argument('workspace_name', id_part='name', help='The workspace name.')

    with self.argument_context('synapse workspace firewall-rule list') as c:
        c.argument('workspace_name', id_part=None, help='The workspace name.')

    for scope in ['show', 'create', 'update', 'delete']:
        with self.argument_context('synapse workspace firewall-rule ' + scope) as c:
            c.argument('rule_name', arg_type=name_type, id_part='child_name_1', help='The IP firewall rule name')

    for scope in ['create', 'update']:
        with self.argument_context('synapse workspace firewall-rule ' + scope) as c:
            c.argument('start_ip_address', help='The start IP address of the firewall rule. Must be IPv4 format.')
            c.argument('end_ip_address', help='The end IP address of the firewall rule. Must be IPv4 format. '
                                              'Must be greater than or equal to startIpAddress.')

    # synapse workspace key
    with self.argument_context('synapse workspace key') as c:
        c.argument('workspace_name', id_part='name', help='The workspace name.')

    with self.argument_context('synapse workspace key list') as c:
        c.argument('workspace_name', id_part=None, help='The workspace name.')

    for scope in ['show', 'create', 'delete', 'update']:
        with self.argument_context('synapse workspace key ' + scope) as c:
            c.argument('key_name', arg_type=name_type, id_part='child_name_1', help='The workspace customer-managed key display name. All existing keys can be found using /"az synapse workspace key list/" cmdlet.')

    with self.argument_context('synapse workspace key create') as c:
        c.argument('key_identifier', help='The Key Vault Url of the workspace encryption key. should be in the format of: https://{keyvaultname}.vault.azure.net/keys/{keyname}.')

    with self.argument_context('synapse workspace key update') as c:
        c.argument('key_identifier', help='The Key Vault Url of the workspace encryption key. should be in the format of: https://{keyvaultname}.vault.azure.net/keys/{keyname}.')
        c.argument('is_active', arg_type=get_three_state_flag(), help='Set True to change the workspace state from pending to success state.')

    # synapse workspace managed-identity
    with self.argument_context('synapse workspace managed-identity') as c:
        c.argument('workspace_name', id_part='name', help='The workspace name.')

    for scope in ['grant-sql-access', 'revoke-sql-access', ' show-sql-access']:
        with self.argument_context('synapse workspace managed-identity ' + scope) as c:
            c.argument('workspace_name', id_part='name', help='The workspace name.')

    # synapse spark job
    for scope in ['job', 'session', 'statement']:
        with self.argument_context('synapse spark ' + scope) as c:
            c.argument('workspace_name', help='The name of the workspace.')
            c.argument('spark_pool_name', help='The name of the Spark pool.')

    for scope in ['synapse spark job', 'synapse spark session']:
        with self.argument_context(scope + ' list') as c:
            c.argument('from_index', help='Optional parameter specifying which index the list should begin from.')
            c.argument('size',
                       help='The size of the returned list.By default it is 20 and that is the maximum.')

    with self.argument_context('synapse spark job submit') as c:
        c.argument('main_definition_file', help='The main file used for the job.')
        c.argument('main_class_name',
                   help='The fully-qualified identifier or the main class that is in the main definition file.')
        c.argument('command_line_arguments', options_list=['--arguments'], nargs='+',
                   help='Optional arguments to the job (Note: please use storage URIs for file arguments).')
        c.argument('archives', nargs='+', help='The array of archives.')
        c.argument('job_name', arg_type=name_type, help='The Spark job name.')
        c.argument('reference_files', nargs='+',
                   help='Additional files used for reference in the main definition file.')
        c.argument('configuration', type=get_json_object, help='The configuration of Spark job.')
        c.argument('executors', help='The number of executors.')
        c.argument('executor_size', arg_type=get_enum_type(['Small', 'Medium', 'Large']), help='The executor size')
        c.argument('tags', arg_type=tags_type)
        c.argument('language', arg_type=get_enum_type(SparkBatchLanguage, default=SparkBatchLanguage.Scala),
                   help='The Spark job language.')

    for scope in ['show', 'cancel']:
        with self.argument_context('synapse spark job ' + scope) as c:
            c.argument('job_id', options_list=['--livy-id'], arg_group='Spark job',
                       help='The id of the Spark job.')

    with self.argument_context('synapse spark session create') as c:
        c.argument('job_name', arg_type=name_type, help='The Spark session name.')
        c.argument('reference_files', nargs='+',
                   help='Additional files used for reference in the main definition file.')
        c.argument('configuration', type=get_json_object, help='The configuration of Spark session.')
        c.argument('executors', help='The number of executors.')
        c.argument('executor_size', arg_type=get_enum_type(['Small', 'Medium', 'Large']), help='The executor size')
        c.argument('tags', arg_type=tags_type)

    for scope in ['show', 'cancel', 'reset-timeout']:
        with self.argument_context('synapse spark session ' + scope) as c:
            c.argument('session_id', options_list=['--livy-id'], arg_group='Spark Session',
                       help='The id of the Spark session job.')

    with self.argument_context('synapse spark statement') as c:
        c.argument('session_id', help='The id of Spark session.')

    for scope in ['show', 'cancel']:
        with self.argument_context('synapse spark statement ' + scope) as c:
            c.argument('statement_id', options_list=['--livy-id'], arg_group="Spark statement",
                       help='The id of the statement.')

    with self.argument_context('synapse spark statement invoke') as c:
        c.argument('code', completer=FilesCompleter(),
                   help='The code of Spark statement. This is either the code contents or use `@<file path>` to load the content from a file')
        c.argument('language', arg_type=get_enum_type(SparkStatementLanguage), validator=validate_statement_language,
                   help='The language of Spark statement.')

    # synapse workspace access-control
    for scope in ['create', 'list']:
        with self.argument_context('synapse role assignment ' + scope) as c:
            c.argument('workspace_name', arg_type=workspace_name_arg_type)
            c.argument('role', arg_type=role_arg_type)
            c.argument('assignee', arg_type=assignee_arg_type)

    with self.argument_context('synapse role assignment show') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('role_assignment_id', options_list=['--id'],
                   help='Id of the role that is assigned to the principal.')

    with self.argument_context('synapse role assignment delete') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('role', arg_type=role_arg_type)
        c.argument('assignee', arg_type=assignee_arg_type)
        c.argument('ids', nargs='+',
                   help='space-separated role assignment ids. You should not provide --role or --assignee when --ids is provided.')

    with self.argument_context('synapse role definition show') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('role', arg_type=role_arg_type)

    with self.argument_context('synapse role definition list') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)

    # synapse artifacts linked-service
    for scope in ['create', 'set']:
        with self.argument_context('synapse linked-service ' + scope) as c:
            c.argument('workspace_name', arg_type=workspace_name_arg_type)
            c.argument('linked_service_name', arg_type=name_type, help='The linked service name.')
            c.argument('definition_file', arg_type=definition_file_arg_type)

    with self.argument_context('synapse linked-service list') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)

    with self.argument_context('synapse linked-service show') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('linked_service_name', arg_type=name_type, help='The linked service name.')

    with self.argument_context('synapse linked-service delete') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('linked_service_name', arg_type=name_type, help='The linked service name.')

    # synapse artifacts dataset
    for scope in ['create', 'set']:
        with self.argument_context('synapse dataset ' + scope) as c:
            c.argument('workspace_name', arg_type=workspace_name_arg_type)
            c.argument('dataset_name', arg_type=name_type, help='The dataset name.')
            c.argument('definition_file', arg_type=definition_file_arg_type)

    with self.argument_context('synapse dataset list') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)

    with self.argument_context('synapse dataset show') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('dataset_name', arg_type=name_type, help='The dataset name.')

    with self.argument_context('synapse dataset delete') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('dataset_name', arg_type=name_type, help='The dataset name.')

    # synapse artifacts pipeline
    for scope in ['create', 'set']:
        with self.argument_context('synapse pipeline ' + scope) as c:
            c.argument('workspace_name', arg_type=workspace_name_arg_type)
            c.argument('pipeline_name', arg_type=name_type, help='The pipeline name.')
            c.argument('definition_file', arg_type=definition_file_arg_type)

    with self.argument_context('synapse pipeline list') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)

    with self.argument_context('synapse pipeline show') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('pipeline_name', arg_type=name_type, help='The pipeline name.')

    with self.argument_context('synapse pipeline delete') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('pipeline_name', arg_type=name_type, help='The pipeline name.')

    with self.argument_context('synapse pipeline create-run') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('pipeline_name', arg_type=name_type, help='The pipeline name.')
        c.argument('reference_pipeline_run_id', options_list=['--reference-pipeline-run-id', '--run-id'],
                   help='The pipeline run ID for rerun. If run ID is specified, the parameters of the specified run will be used to create a new run.')
        c.argument('is_recovery', arg_type=get_three_state_flag(),
                   help='Recovery mode flag. If recovery mode is set to true, the specified referenced pipeline run and the new run will be grouped under the same groupId.')
        c.argument('start_activity_name',
                   help='In recovery mode, the rerun will start from this activity. If not specified, all activities will run.')
        c.argument('parameters', completer=FilesCompleter(), type=shell_safe_json_parse,
                   help='Parameters for pipeline run. Can be supplied from a JSON file using the `@{path}` syntax or a JSON string.')

    # synapse artifacts pipeline run
    with self.argument_context('synapse pipeline-run query-by-workspace') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('continuation_token',
                   help='The continuation token for getting the next page of results. Null for first page.')
        c.argument('last_updated_after',
                   help='The time at or after which the run event was updated in \'ISO 8601\' format.')
        c.argument('last_updated_before',
                   help='The time at or before which the run event was updated in \'ISO 8601\' format.')
        c.argument('filters', action=AddFilters, nargs='*', help='List of filters.')
        c.argument('order_by', action=AddOrderBy, nargs='*', help='List of OrderBy option.')

    with self.argument_context('synapse pipeline-run show') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('run_id', help='The pipeline run identifier.')

    with self.argument_context('synapse pipeline-run cancel') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('run_id', help='The pipeline run identifier.')
        c.argument('is_recursive', arg_type=get_three_state_flag(),
                   help='If true, cancel all the Child pipelines that are triggered by the current pipeline.')

    with self.argument_context('synapse activity-run query-by-pipeline-run') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('pipeline_name', arg_type=name_type, help='The pipeline name.')
        c.argument('run_id', help='The pipeline run identifier.')
        c.argument('continuation_token',
                   help='The continuation token for getting the next page of results. Null for first page.')
        c.argument('last_updated_after',
                   help='The time at or after which the run event was updated in \'ISO 8601\' format.')
        c.argument('last_updated_before',
                   help='The time at or before which the run event was updated in \'ISO 8601\' format.')
        c.argument('filters', action=AddFilters, nargs='*', help='List of filters.')
        c.argument('order_by', action=AddOrderBy, nargs='*', help='List of OrderBy option.')

    # synapse artifacts trigger
    for scope in ['create', 'set']:
        with self.argument_context('synapse trigger ' + scope) as c:
            c.argument('workspace_name', arg_type=workspace_name_arg_type)
            c.argument('trigger_name', arg_type=name_type, help='The trigger name.')
            c.argument('definition_file', arg_type=definition_file_arg_type)

    with self.argument_context('synapse trigger list') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)

    with self.argument_context('synapse trigger show') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('trigger_name', arg_type=name_type, help='The trigger name.')

    with self.argument_context('synapse trigger delete') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('trigger_name', arg_type=name_type, help='The trigger name.')

    with self.argument_context('synapse trigger subscribe-to-event') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('trigger_name', arg_type=name_type, help='The trigger name.')

    with self.argument_context('synapse trigger get-event-subscription-status') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('trigger_name', arg_type=name_type, help='The trigger name.')

    with self.argument_context('synapse trigger unsubscribe-from-event') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('trigger_name', arg_type=name_type, help='The trigger name.')

    with self.argument_context('synapse trigger start') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('trigger_name', arg_type=name_type, help='The trigger name.')

    with self.argument_context('synapse trigger stop') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('trigger_name', arg_type=name_type, help='The trigger name.')

    # synapse artifacts trigger run
    with self.argument_context('synapse trigger-run rerun') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('trigger_name', arg_type=name_type, help='The trigger name.')
        c.argument('run_id', help='The trigger run identifier.')

    with self.argument_context('synapse trigger-run query-by-workspace') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('continuation_token',
                   help='The continuation token for getting the next page of results. Null for first page.')
        c.argument('last_updated_after',
                   help='The time at or after which the run event was updated in \'ISO 8601\' format.')
        c.argument('last_updated_before',
                   help='The time at or before which the run event was updated in \'ISO 8601\' format.')
        c.argument('filters', action=AddFilters, nargs='*', help='List of filters.')
        c.argument('order_by', action=AddOrderBy, nargs='*', help='List of OrderBy option.')

    # synapse artifacts data flow
    for scope in ['create', 'set']:
        with self.argument_context('synapse data-flow ' + scope) as c:
            c.argument('workspace_name', arg_type=workspace_name_arg_type)
            c.argument('data_flow_name', arg_type=name_type, help='The data flow name.')
            c.argument('definition_file', arg_type=definition_file_arg_type)

    with self.argument_context('synapse data-flow list') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)

    with self.argument_context('synapse data-flow show') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('data_flow_name', arg_type=name_type, help='The data flow name.')

    with self.argument_context('synapse data-flow delete') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('data_flow_name', arg_type=name_type, help='The data flow name.')

    # synapse artifacts notebook
    for scope in ['create', 'set', 'import']:
        with self.argument_context('synapse notebook ' + scope) as c:
            c.argument('workspace_name', arg_type=workspace_name_arg_type)
            c.argument('notebook_name', arg_type=name_type, help='The notebook name.')
            c.argument('definition_file', arg_type=definition_file_arg_type)
            c.argument('spark_pool_name', help='The name of the Spark pool.')
            c.argument('executor_size', arg_type=get_enum_type(['Small', 'Medium', 'Large']),
                       help='Number of core and memory to be used for executors allocated in the specified Spark pool for the job.')
            c.argument('executor_count',
                       help='Number of executors to be allocated in the specified Spark pool for the job.')

    with self.argument_context('synapse notebook list') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)

    with self.argument_context('synapse notebook show') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('notebook_name', arg_type=name_type, help='The notebook name.')

    with self.argument_context('synapse notebook export') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('output_folder', help='The folder where the notebook should be placed.')
        c.argument('notebook_name', arg_type=name_type, help='The notebook name.')

    with self.argument_context('synapse notebook delete') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type)
        c.argument('notebook_name', arg_type=name_type, help='The notebook name.')

    # synapse integration runtime
    with self.argument_context('synapse integration-runtime') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type, id_part='name')

    for scope in ['list', 'list-auth-key', 'wait']:
        with self.argument_context('synapse integration-runtime ' + scope) as c:
            c.argument('workspace_name', arg_type=workspace_name_arg_type, id_part=None)

    for scope in ['list-auth-key', 'wait']:
        with self.argument_context('synapse integration-runtime ' + scope) as c:
            c.argument('integration_runtime_name', arg_type=name_type, help='The integration runtime name.', id_part=None)

    for scope in ['show', 'create', 'delete', 'wait', 'update', 'upgrade', 'regenerate-auth-key', 'get-monitoring-data', 'sync-credentials', 'get-connection-info', 'get-status']:
        with self.argument_context('synapse integration-runtime ' + scope) as c:
            c.argument('integration_runtime_name', arg_type=name_type, help='The integration runtime name.', id_part='child_name_1')

    with self.argument_context('synapse integration-runtime create') as c:
        c.argument('integration_runtime_type', options_list=['--type'], arg_type=get_enum_type(['Managed', 'SelfHosted']), help='The integration runtime type.')
        c.argument('description', help='The integration runtime description.')
        c.argument('if_match', help='ETag of the integration runtime entity. Should only be specified for update, for '
                   'which it should match existing entity or can be * for unconditional update.')
        # Managed
        c.argument('location', arg_group='Managed', help='The integration runtime location.')
        c.argument('compute_type', arg_group='Managed', arg_type=get_enum_type(['General', 'MemoryOptimized', 'ComputeOptimized']),
                   help='Compute type of the data flow cluster which will execute data flow job.')
        c.argument('core_count', arg_group='Managed', help='Core count of the data flow cluster which will execute data flow job.')
        c.argument('time_to_live', arg_group='Managed', help='Time to live (in minutes) setting of the data flow cluster which will execute data flow job.')

    with self.argument_context('synapse integration-runtime update') as c:
        c.argument('auto_update', arg_type=get_enum_type(['On', 'Off']), help='Enable or disable the self-hosted integration runtime auto-update.')
        c.argument('update_delay_offset', help='The time of the day for the self-hosted integration runtime auto-update.')

    with self.argument_context('synapse integration-runtime regenerate-auth-key') as c:
        c.argument('key_name', arg_type=get_enum_type(['authKey1', 'authKey2']), help='The name of the authentication key to regenerate.')

    with self.argument_context('synapse integration-runtime-node') as c:
        c.argument('workspace_name', arg_type=workspace_name_arg_type, id_part='name')
        c.argument('integration_runtime_name', arg_type=name_type, help='The integration runtime name.', id_part='child_name_1')

    for scope in ['show', 'update', 'delete', 'get-ip-address']:
        with self.argument_context('synapse integration-runtime-node ' + scope) as c:
            c.argument('node_name', help='The integration runtime node name.')

    with self.argument_context('synapse integration-runtime-node update') as c:
        c.argument('concurrent_jobs_limit', options_list=['--concurrent-jobs'], help='The number of concurrent jobs permitted to '
                   'run on the integration runtime node. Values between 1 and maxConcurrentJobs are allowed.')
コード例 #39
0
ファイル: _params.py プロジェクト: jiayexie/azure-cli
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) etc',
                                   arg_type=get_enum_type(['F1', 'FREE', 'D1', 'SHARED', 'B1', 'B2', 'B3', 'S1', 'S2', 'S3', 'P1', 'P2', 'P3', 'P1V2', 'P2V2', 'P3V2']))
    webapp_name_arg_type = CLIArgumentType(configured_default='web', options_list=['--name', '-n'], metavar='NAME',
                                           completer=get_resource_name_completion_list('Microsoft.Web/sites'), id_part='name',
                                           help="name of the web. You can configure the default using 'az configure --defaults web=<name>'")

    # use this hidden arg to give a command the right instance, that functionapp commands
    # work on function app and webapp ones work on web app
    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 web. 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')
    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 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')

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

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

    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('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.")
    # 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>")
コード例 #40
0
ファイル: _params.py プロジェクト: shrishrirang/azure-cli
def load_arguments(self, _):

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

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

    for scope in ['cosmosdb create', 'cosmosdb update']:
        with self.argument_context(scope) as c:
            c.argument('account_name', completer=None)
            c.ignore('resource_group_location')
            c.argument(
                'locations',
                nargs='+',
                validator=validate_locations,
                help=
                "space separated locations in 'regionName=failoverPriority' format. E.g eastus=0 westus=1. Failover priority values are 0 for write regions and greater than 0 for read regions. A failover priority value must be unique and less than the total number of regions. Default: single region account in the location of the specified resource group."
            )
            c.argument(
                '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.'
            )

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

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

    with self.argument_context('cosmosdb collection') as c:
        c.argument('collection_id',
                   options_list=['--collection-name', '-c'],
                   help='Collection Name')
        c.argument('throughput', type=int, help='Offer Throughput')
        c.argument('partition_key_path',
                   help='Partition Key Path, e.g., \'/properties/name\'')
        c.argument(
            'indexing_policy',
            type=shell_safe_json_parse,
            completer=FilesCompleter(),
            help=
            'Indexing Policy, you can enter it as a string or as a file, e.g., --indexing-policy @policy-file.json)'
        )
        c.argument('default_ttl', type=int, help='Default TTL')
コード例 #41
0
ファイル: _params.py プロジェクト: sptramer/azure-cli
def load_arguments(self, _):
    with self.argument_context('ad') as c:
        c.argument('_subscription')  # hide global subscription param
        c.argument('owner_object_id', help="owner's object id")
        c.argument('show_mine', action='store_true', help='list entities owned by the current user')
        c.argument('include_all', options_list='--all', action='store_true',
                   help='list all entities, expect long delay if under a big organization')

    with self.argument_context('ad app') as c:
        c.argument('app_id', help='application id')
        c.argument('application_object_id', options_list=('--object-id',))
        c.argument('display_name', help='the display name of the application')
        c.argument('homepage', help='the url where users can sign in and use your app.')
        c.argument('identifier', options_list=['--id'], help='identifier uri, application id, or object id')
        c.argument('identifier_uris', nargs='+', help='space-separated unique URIs that Azure AD can use for this app.')
        c.argument('reply_urls', nargs='+', help='space-separated URIs to which Azure AD will redirect in response to an OAuth 2.0 request. The value does not need to be a physical endpoint, but must be a valid URI.')
        c.argument('start_date', help="Date or datetime at which credentials become valid(e.g. '2017-01-01T01:00:00+00:00' or '2017-01-01'). Default value is current time")
        c.argument('end_date', help="Date or datetime after which credentials expire(e.g. '2017-12-31T11:59:59+00:00' or '2017-12-31'). Default value is one year after current time")
        c.argument('available_to_other_tenants', help='the application can be used from any Azure AD tenants', arg_type=get_three_state_flag())
        c.argument('key_value', help='the value for the key credentials associated with the application')
        # TODO: Update these with **enum_choice_list(...) when SDK supports proper enums
        c.argument('key_type', help='the type of the key credentials associated with the application', arg_type=get_enum_type(['AsymmetricX509Cert', 'Password', 'Symmetric'], default='AsymmetricX509Cert'))
        c.argument('key_usage', help='the usage of the key credentials associated with the application.', arg_type=get_enum_type(['Sign', 'Verify'], default='Verify'))
        c.argument('password', help="app password, aka 'client secret'")
        c.argument('oauth2_allow_implicit_flow', arg_type=get_three_state_flag(), help='whether to allow implicit grant flow for OAuth2')
        c.argument('required_resource_accesses', type=validate_file_or_dict,
                   help="resource scopes and roles the application requires access to. Should be in manifest json format. See examples below for details")
        c.argument('native_app', arg_type=get_three_state_flag(), help="an application which can be installed on a user's device or computer")
        c.argument('credential_description', help="the description of the password")

    with self.argument_context('ad app owner list') as c:
        c.argument('identifier', options_list=['--id'], help='identifier uri, application id, or object id of the application')

    with self.argument_context('ad app permission') as c:
        c.argument('api_permissions', nargs='+', help='space seperated list of <resource-access-id>=<type>')
        c.argument('expires', help='Expiry date for the permissions in years. e.g. 1, 2 or "never"')
        c.argument('scope', help='oauth scope')
        c.argument('api', help='the target API to access')

    with self.argument_context('ad app permission list') as c:
        c.argument('identifier', options_list=['--id'], help='identifier uri, application id, or object id of the associated application')

    with self.argument_context('ad sp') as c:
        c.argument('identifier', options_list=['--id'], help='service principal name, or object id')

    with self.argument_context('ad sp create') as c:
        c.argument('identifier', options_list=['--id'], help='identifier uri, application id, or object id of the associated application')

    with self.argument_context('ad sp create-for-rbac') as c:
        c.argument('scopes', nargs='+')
        c.argument('role', completer=get_role_definition_name_completion_list)
        c.argument('skip_assignment', arg_type=get_three_state_flag(), help='do not create default assignment')
        c.argument('show_auth_for_sdk', options_list='--sdk-auth', help='output result in compatible with Azure SDK auth file', arg_type=get_three_state_flag())

    with self.argument_context('ad sp owner list') as c:
        c.argument('identifier', options_list=['--id'], help='service principal name, or object id or the service principal')

    for item in ['create-for-rbac', 'credential reset']:
        with self.argument_context('ad sp {}'.format(item)) as c:
            c.argument('name', name_arg_type)
            c.argument('cert', arg_group='Credential', validator=validate_cert)
            c.argument('password', options_list=['--password', '-p'], arg_group='Credential')
            c.argument('years', type=int, default=None, arg_group='Credential')
            c.argument('create_cert', action='store_true', arg_group='Credential')
            c.argument('keyvault', arg_group='Credential')
            c.argument('append', action='store_true', help='Append the new credential instead of overwriting.')
            c.argument('credential_description', help="the description of the password", arg_group='Credential')

    with self.argument_context('ad app credential reset') as c:
        c.argument('name', options_list=['--id'], help='identifier uri, application id, or object id')
        c.argument('cert', arg_group='Credential', validator=validate_cert, help='Certificate to use for credentials')
        c.argument('password', options_list=['--password', '-p'], arg_group='Credential')
        c.argument('years', type=int, default=None, arg_group='Credential', help='Number of years for which the credentials will be valid')
        c.argument('create_cert', action='store_true', arg_group='Credential', help='Create a self-signed certificate to use for the credential')
        c.argument('keyvault', arg_group='Credential', help='Name or ID of a KeyVault to use for creating or retrieving certificates.')
        c.argument('append', action='store_true', help='Append the new credential instead of overwriting.')

    for item in ['ad sp credential delete', 'ad sp credential list', 'ad app credential delete', 'ad app credential list']:
        with self.argument_context(item) as c:
            c.argument('key_id', help='credential key id')
            c.argument('cert', action='store_true', help='a certificate based credential')

    with self.argument_context('ad') as c:
        c.argument('display_name', help='object\'s display name or its prefix')
        c.argument('identifier_uri', help='graph application identifier, must be in uri format')
        c.argument('spn', help='service principal name')
        c.argument('upn', help='user principal name, e.g. [email protected]')
        c.argument('query_filter', options_list=['--filter'], help='OData filter')

    with self.argument_context('ad user') as c:
        c.argument('mail_nickname', help='mail alias. Defaults to user principal name')
        c.argument('force_change_password_next_login', arg_type=get_three_state_flag())

    with self.argument_context('ad user get-member-groups') as c:
        c.argument('upn_or_object_id', help='The object ID or principal name of the user for which to get information')
        c.argument('security_enabled_only', action='store_true',
                   help='If true, only membership in security-enabled groups should be checked. Otherwise, membership in all groups should be checked.')

    group_help_msg = "group's object id or display name(prefix also works if there is a unique match)"
    with self.argument_context('ad group') as c:
        for arg in VARIANT_GROUP_ID_ARGS:
            c.argument(arg, options_list=['--group', '-g'], validator=validate_group, help=group_help_msg)

    with self.argument_context('ad group create') as c:
        c.argument('mail_nickname', help='Mail nickname')

    with self.argument_context('ad group show') as c:
        c.extra('cmd')

    member_id_help_msg = 'The object ID of the contact, group, user, or service principal'
    with self.argument_context('ad group get-member-groups') as c:
        c.argument('security_enabled_only', arg_type=get_three_state_flag(), default=False, required=False)
        c.extra('cmd')

    with self.argument_context('ad group member add') as c:
        c.argument('url', options_list='--member-id', validator=validate_member_id, help=member_id_help_msg)

    for item in ['member add', 'member check', 'member list', 'member remove', 'delete']:
        with self.argument_context('ad group {}'.format(item)) as c:
            c.extra('cmd')

    with self.argument_context('ad group member') as c:
        c.argument('member_object_id', options_list='--member-id', help=member_id_help_msg)

    with self.argument_context('ad signed-in-user') as c:
        c.argument('object_type', options_list=['--type', '-t'], help='object type filter, e.g. "application", "servicePrincipal"  "group", etc')

    with self.argument_context('role') as c:
        c.argument('scope', help='scope at which the role assignment or definition 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('resource_group_name', options_list=['--resource-group', '-g'], help='use it only if the role or assignment was added at the level of a resource group')

    with self.argument_context('role assignment') as c:
        c.argument('role_assignment_name', options_list=['--name', '-n'])
        c.argument('role', help='role name or id', completer=get_role_definition_name_completion_list)
        c.argument('show_all', options_list=['--all'], action='store_true', help='show all assignments under the current subscription')
        c.argument('include_inherited', action='store_true', help='include assignments applied on parent scopes')
        c.argument('can_delegate', action='store_true', help='when set, the assignee will be able to create further role assignments to the same role')
        c.argument('assignee', help='represent a user, group, or service principal. supported format: object id, user sign-in name, or service principal name')
        c.argument('assignee_object_id', help="assignee's graph object id, such as the 'principal id' from a managed service identity. Use this instead of '--assignee' to bypass graph permission issues")
        c.argument('ids', nargs='+', help='space-separated role assignment ids')
        c.argument('include_classic_administrators', arg_type=get_three_state_flag(), help='list default role assignments for subscription classic administrators, aka co-admins')

    time_help = ('The {} of the query in the format of %Y-%m-%dT%H:%M:%SZ, e.g. 2000-12-31T12:59:59Z. Defaults to {}')
    with self.argument_context('role assignment list-changelogs') as c:
        c.argument('start_time', help=time_help.format('start time', '1 Hour prior to the current time'))
        c.argument('end_time', help=time_help.format('end time', 'the current time'))

    with self.argument_context('role definition') as c:
        c.argument('role_definition_id', options_list=['--name', '-n'], help='the role definition name')
        c.argument('custom_role_only', arg_type=get_three_state_flag(), help='custom roles only(vs. build-in ones)')
        c.argument('role_definition', help="json formatted content which defines the new role.")
        c.argument('name', arg_type=name_arg_type, completer=get_role_definition_name_completion_list, help="the role's name")
コード例 #42
0
def load_arguments(self, _):
    from azure.mgmt.compute.models import CachingTypes, UpgradeMode
    from azure.mgmt.storage.models import SkuName

    # REUSABLE ARGUMENT DEFINITIONS
    name_arg_type = CLIArgumentType(options_list=['--name', '-n'], metavar='NAME')
    multi_ids_type = CLIArgumentType(nargs='+')
    existing_vm_name = CLIArgumentType(overrides=name_arg_type,
                                       configured_default='vm',
                                       help="The name of the Virtual Machine. You can configure the default using `az configure --defaults vm=<name>`",
                                       completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachines'), id_part='name')
    existing_disk_name = CLIArgumentType(overrides=name_arg_type, help='The name of the managed disk', completer=get_resource_name_completion_list('Microsoft.Compute/disks'), id_part='name')
    existing_snapshot_name = CLIArgumentType(overrides=name_arg_type, help='The name of the snapshot', completer=get_resource_name_completion_list('Microsoft.Compute/snapshots'), id_part='name')
    vmss_name_type = CLIArgumentType(name_arg_type,
                                     configured_default='vmss',
                                     completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'),
                                     help="Scale set name. You can configure the default using `az configure --defaults vmss=<name>`",
                                     id_part='name')
    disk_sku = CLIArgumentType(help='Underlying storage SKU.', arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS']))

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

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

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

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

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

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

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

    # region Snapshots
    with self.argument_context('snapshot', resource_type=ResourceType.MGMT_COMPUTE, operation_group='snapshots') as c:
        c.argument('snapshot_name', existing_snapshot_name, id_part='name', completer=get_resource_name_completion_list('Microsoft.Compute/snapshots'))
        c.argument('name', arg_type=name_arg_type)
        if self.supported_api_version(min_api='2018-04-01', operation_group='snapshots'):
            c.argument('sku', arg_type=get_enum_type(['Premium_LRS', 'Standard_LRS', 'Standard_ZRS']))
        else:
            c.argument('sku', arg_type=disk_sku)
    # endregion

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

    with self.argument_context('image create') as c:
        # here we collpase all difference image sources to under 2 common arguments --os-disk-source --data-disk-sources
        c.argument('name', arg_type=name_arg_type, help='new image name')
        c.argument('source', help='OS disk source from the same region, including a virtual machine ID or name, OS disk blob URI, managed OS disk ID or name, or OS snapshot ID or name')
        c.argument('data_disk_sources', nargs='+', help='Space-separated list of data disk sources, including unmanaged blob URI, managed disk ID or name, or snapshot ID or name')
        c.argument('zone_resilient', min_api='2017-12-01', arg_type=get_three_state_flag(), help='Specifies whether an image is zone resilient or not. '
                   'Default is false. Zone resilient images can be created only in regions that provide Zone Redundant Storage')
        c.ignore('source_virtual_machine', 'os_blob_uri', 'os_disk', 'os_snapshot', 'data_blob_uris', 'data_disks', 'data_snapshots')
    # endregion

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('vm image') as c:
        c.argument('publisher_name', options_list=['--publisher', '-p'])
        c.argument('publisher', options_list=['--publisher', '-p'], help='image publisher')
        c.argument('offer', options_list=['--offer', '-f'], help='image offer')
        c.argument('plan', help='image billing plan')
        c.argument('sku', options_list=['--sku', '-s'], help='image sku')
        c.argument('version', help="image sku's version")
        c.argument('urn', help="URN, in format of 'publisher:offer:sku:versin'. If specified, other argument values can be omitted")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('vmss create') as c:
        VMPriorityTypes = self.get_models('VirtualMachinePriorityTypes', resource_type=ResourceType.MGMT_COMPUTE)
        c.argument('name', name_arg_type)
        c.argument('nat_backend_port', default=None, help='Backend port to open with NAT rules.  Defaults to 22 on Linux and 3389 on Windows.')
        c.argument('single_placement_group', arg_type=get_three_state_flag(), help="Enable replicate using fault domains within the same cluster. Default to 'false' for any zonals, or with 100+ instances"
                   " See https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-placement-groups for details")
        c.argument('platform_fault_domain_count', type=int, help='Fault Domain count for each placement group in the availability zone', min_api='2017-12-01')
        c.argument('vmss_name', name_arg_type, id_part=None, help='Name of the virtual machine scale set.')
        c.argument('instance_count', help='Number of VMs in the scale set.', type=int)
        c.argument('disable_overprovision', help='Overprovision option (see https://azure.microsoft.com/en-us/documentation/articles/virtual-machine-scale-sets-overview/ for details).', action='store_true')
        c.argument('upgrade_policy_mode', help=None, arg_type=get_enum_type(UpgradeMode))
        c.argument('health_probe', help='(Preview) probe name from the existing load balancer, mainly used for rolling upgrade')
        c.argument('vm_sku', help='Size of VMs in the scale set.  See https://azure.microsoft.com/en-us/pricing/details/virtual-machines/ for size info.')
        c.argument('nsg', help='Name or ID of an existing Network Security Group.', arg_group='Network')
        c.argument('priority', resource_type=ResourceType.MGMT_COMPUTE, min_api='2017-12-01', arg_type=get_enum_type(VMPriorityTypes, default=None),
                   help="(PREVIEW)Priority. Use 'Low' to run short-lived workloads in a cost-effective way")

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

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

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

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

    with self.argument_context('vmss disk') as c:
        c.argument('lun', type=int, help='0-based logical unit number (LUN). Max value depends on the Virtual Machine instance size.')
        c.argument('size_gb', options_list=['--size-gb', '-z'], help='size in GB.')
        c.argument('vmss_name', vmss_name_type, completer=get_resource_name_completion_list('Microsoft.Compute/virtualMachineScaleSets'))
        c.argument('disk', validator=validate_vmss_disk, help='existing disk name or ID to attach or detach from VM instances',
                   min_api='2017-12-01', completer=get_resource_name_completion_list('Microsoft.Compute/disks'))
        c.argument('instance_id', help='Scale set VM instance id', min_api='2017-12-01')

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

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

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

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

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

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

    for scope in ['vm identity show', 'vmss identity show']:
        with self.argument_context(scope) as c:
            c.argument('vm_name', existing_vm_name)
            c.argument('vmss_name', vmss_name_type)

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

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

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

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

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

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

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

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

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

    for scope in ['vm extension image', 'vmss extension image']:
        with self.argument_context(scope) as c:
            c.argument('image_location', options_list=['--location', '-l'], help='Image location.')
            c.argument('name', help='Image name', id_part=None)
            c.argument('publisher_name', options_list=['--publisher', '-p'], help='Image publisher name')
            c.argument('type', options_list=['--name', '-n'], help='Name of the extension')
            c.argument('latest', action='store_true', help='Show the latest version only.')
            c.argument('version', help='Extension version')
コード例 #43
0
ファイル: _params.py プロジェクト: johanste/azure-cli
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

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

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

    for scope in ['servicebus namespace create', 'servicebus namespace update']:
        with self.argument_context(scope) as c:
            c.argument('tags', arg_type=tags_type)
            c.argument('sku', arg_type=get_enum_type(SkuName))
            c.argument('capacity', type=int, choices=[1, 2, 4], 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 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], help='The maximum size of queue in megabytes, which is the size of memory allocated for the queue. Default is 1024.')
            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], help='Maximum size of topic in megabytes, which is the size of the memory allocated for the topic. Default is 1024.')
            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']))
            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')
コード例 #44
0
ファイル: _params.py プロジェクト: wiebeck/azure-cli
def load_arguments(self, _):  # pylint: disable=too-many-statements
    with self.argument_context('eventgrid') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('location', arg_type=get_location_type(self.cli_ctx))
        c.argument('tags', arg_type=tags_type)
        c.argument('included_event_types',
                   arg_group="Filtering",
                   arg_type=included_event_types_type)
        c.argument('labels', arg_type=labels_type)
        c.argument(
            'endpoint_type',
            arg_type=get_enum_type([
                'webhook', 'eventhub', 'storagequeue', 'hybridconnection',
                'servicebusqueue', 'servicebustopic', 'azurefunction'
            ],
                                   default='webhook'))
        c.argument(
            'delivery_identity_endpoint_type',
            arg_type=get_enum_type([
                'webhook', 'eventhub', 'storagequeue', 'hybridconnection',
                'servicebusqueue', 'servicebustopic', 'azurefunction'
            ],
                                   default=None),
            is_preview=True)
        c.argument(
            'source_resource_id',
            help="Fully qualified identifier of the source Azure resource.")
        c.argument(
            'endpoint',
            help=
            "Endpoint where EventGrid should deliver events matching this event subscription. For webhook endpoint type, this should be the corresponding webhook URL. For other endpoint types, this should be the Azure resource identifier of the endpoint. It is expected that the destination endpoint to be already created and available for use before executing any Event Grid command."
        )
        c.argument(
            'delivery_identity_endpoint',
            help=
            "Endpoint with identity where EventGrid should deliver events matching this event subscription. For webhook endpoint type, this should be the corresponding webhook URL. For other endpoint types, this should be the Azure resource identifier of the endpoint.",
            is_preview=True)
        c.argument('event_subscription_name',
                   help="Name of the event subscription.")
        c.argument(
            'subject_begins_with',
            arg_group="Filtering",
            help=
            "An optional string to filter events for an event subscription based on a prefix. Wildcard characters are not supported."
        )
        c.argument(
            'subject_ends_with',
            arg_group="Filtering",
            help=
            "An optional string to filter events for an event subscription based on a suffix. Wildcard characters are not supported."
        )
        c.argument('topic_type_name', help="Name of the topic type.")
        c.argument(
            'is_subject_case_sensitive',
            arg_group="Filtering",
            arg_type=get_three_state_flag(),
            options_list=['--subject-case-sensitive'],
            help=
            "Specify to indicate whether the subject fields should be compared in a case sensitive manner. True if flag present.",
        )
        c.argument('input_mapping_fields', arg_type=input_mapping_fields_type)
        c.argument('input_mapping_default_values',
                   arg_type=input_mapping_default_values_type)
        c.argument('input_schema', arg_type=input_schema_type)
        c.argument('odata_query', arg_type=odata_query_type)
        c.argument('domain_name', arg_type=domain_name_type)
        c.argument('domain_topic_name', arg_type=domain_topic_name_type)
        c.argument('system_topic_name', arg_type=system_topic_name_type)
        c.argument(
            'source',
            help=
            "The ARM Id for the topic, e.g., /subscriptions/{SubId}/resourceGroups/{RgName}/providers/Microsoft.Storage/storageAccounts/{AccountName}"
        )
        c.argument('public_network_access',
                   arg_type=public_network_access_type)
        c.argument('inbound_ip_rules', action=AddInboundIpRule, nargs='+')
        c.argument('sku', arg_type=sku_type)
        c.argument('identity', arg_type=identity_type)
        c.argument('delivery_identity', arg_type=delivery_identity_type)
        c.argument('deadletter_identity', arg_type=deadletter_identity_type)
        c.argument('partner_registration_name',
                   arg_type=partner_registration_name_type)
        c.argument('partner_namespace_name',
                   arg_type=partner_namespace_name_type)
        c.argument('event_channel_name', arg_type=event_channel_name_type)
        c.argument('partner_topic_name', arg_type=partner_topic_name_type)
        c.argument('authorized_subscription_ids',
                   arg_type=authorized_subscription_ids_type)
        c.argument('partner_name', help="Official name of the partner.")
        c.argument('display_name',
                   help="Display name for the partner topic type.")
        c.argument(
            'resource_type_name',
            help=
            "Name of the partner topic resource type. This name should be unique among all partner topic types names."
        )
        c.argument('description',
                   help="Description of the partner topic type.")
        c.argument('logo_uri', help="URI of the partner logo.")
        c.argument(
            'setup_uri',
            help=
            "URI of the partner website that can be used by Azure customers to setup Event Grid integration on an event source."
        )
        c.argument(
            'partner_registration_id',
            help=
            "The fully qualified ARM Id of the partner registration that should be associated with this partner namespace. This takes the following format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerRegistrations/{partnerRegistrationName}."
        )
        c.argument('partner_topic_source', arg_type=partner_topic_source_type)
        c.argument(
            'destination_topic_name',
            help="Name of the partner topic associated with the event channel."
        )
        c.argument(
            'destination_resource_group_name',
            help=
            "Azure Resource Group of the customer creating the event channel. The partner topic associated with the event channel will be created under this resource group."
        )
        c.argument(
            'destination_subscription_id',
            help=
            "Azure subscription Id of the customer creating the event channel. The partner topic associated with the event channel will be created under this Azure subscription."
        )
        c.argument('topic_type',
                   help="Name of the topic type.",
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/topictypes'))

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

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

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

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

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

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

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

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

    with self.argument_context('eventgrid system-topic') as c:
        c.argument('system_topic_name',
                   arg_type=system_topic_name_type,
                   options_list=['--name', '-n'],
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/systemtopics'))

    with self.argument_context('eventgrid system-topic create') as c:
        c.argument(
            'source',
            help=
            "The ARM Id for the topic, e.g., /subscriptions/{SubId}/resourceGroups/{RgName}/providers/Microsoft.Storage/storageAccounts/{AccountName}"
        )

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

    with self.argument_context('eventgrid partner registration') as c:
        c.argument('partner_registration_name',
                   arg_type=partner_registration_name_type,
                   options_list=['--name', '-n'],
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/partnerregistrations'))
        c.argument(
            'long_description',
            help=
            'Description of the custom scenarios and integration. Length of this description should not exceed 2048 characters',
            id_part=None)
        c.argument('customer_service_number',
                   arg_type=phone_number_type,
                   id_part=None)
        c.argument('customer_service_extension',
                   arg_type=phone_extension_type,
                   id_part=None)
        c.argument('customer_service_uri',
                   help='The customer service URI of the publisher.',
                   id_part=None)

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

    with self.argument_context('eventgrid partner namespace') as c:
        c.argument('partner_namespace_name',
                   arg_type=partner_namespace_name_type,
                   options_list=['--name', '-n'],
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/partnernamespaces'))

    with self.argument_context('eventgrid partner namespace key') as c:
        c.argument('partner_namespace_name',
                   arg_type=partner_namespace_name_type,
                   help='Name of the partner namespace',
                   id_part=None,
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/partnernamespaces'))

    with self.argument_context('eventgrid partner namespace show') as c:
        c.argument('partner_namespace_name',
                   arg_type=partner_namespace_name_type,
                   options_list=['--name', '-n'],
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/partnernamespaces'))

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

    with self.argument_context(
            'eventgrid partner namespace event-channel') as c:
        c.argument('partner_namespace_name',
                   arg_type=partner_namespace_name_type,
                   id_part='name')
        c.argument('event_channel_name',
                   arg_type=event_channel_name_type,
                   options_list=['--name', '-n'],
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/partnernamespaes/eventchannels'))
        c.argument('partner_topic_source',
                   arg_type=partner_topic_source_type,
                   options_list=['--source'])
        c.argument(
            'activation_expiration_date',
            help=
            "Date or datetime in UTC ISO 8601 format (e.g., '2022-02-17T01:59:59+00:00' or '2022-02-17') after which the event channel and corresponding partner topic would expire and get auto deleted. If this time is not specified, the expiration date is set to seven days by default."
        )
        c.argument(
            'partner_topic_description',
            help=
            "Friendly description of the corresponding partner topic. This will be helpful to remove any ambiguity of the origin of creation of the partner topic for the customer."
        )
        c.argument('publisher_filter', action=EventChannelAddFilter, nargs='+')

    with self.argument_context(
            'eventgrid partner namespace event-channel show') as c:
        c.argument('partner_namespace_name',
                   arg_type=partner_namespace_name_type,
                   id_part='name')

    with self.argument_context(
            'eventgrid partner namespace event-channel list') as c:
        c.argument('partner_namespace_name',
                   arg_type=partner_namespace_name_type,
                   id_part=None)
        c.argument('odata_query', arg_type=odata_query_type, id_part=None)

    with self.argument_context('eventgrid partner topic') as c:
        c.argument('partner_topic_name',
                   arg_type=partner_topic_name_type,
                   options_list=['--name', '-n'],
                   id_part='name',
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/partnertopics'))

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

    with self.argument_context('eventgrid event-subscription') as c:
        c.argument('event_subscription_name',
                   arg_type=name_type,
                   help='Name of the event subscription.')
        c.argument(
            'event_delivery_schema',
            arg_type=get_enum_type([
                'eventgridschema', 'custominputschema', 'cloudeventschemav1_0'
            ]),
            help=
            'The schema in which events should be delivered for this event subscription. By default, events will be delivered in the same schema in which they are published (based on the corresponding topic\'s input schema).'
        )
        c.argument(
            'max_delivery_attempts',
            type=int,
            help=
            "Maximum number of delivery attempts. Must be a number between 1 and 30."
        )
        c.argument(
            'max_events_per_batch',
            type=int,
            help=
            "Maximum number of events in a batch. Must be a number between 1 and 5000."
        )
        c.argument(
            'preferred_batch_size_in_kilobytes',
            type=int,
            help=
            "Preferred batch size in kilobytes. Must be a number between 1 and 1024."
        )
        c.argument(
            'event_ttl',
            type=int,
            help=
            "Event time to live (in minutes). Must be a number between 1 and 1440."
        )
        c.argument(
            'deadletter_endpoint',
            help=
            "The Azure resource ID of an Azure Storage blob container destination where EventGrid should deadletter undeliverable events for this event subscription."
        )
        c.argument(
            'deadletter_identity_endpoint',
            help=
            "The Azure resource ID of an Azure Storage blob container destination with identity where EventGrid should deadletter undeliverable events for this event subscription."
        )
        c.argument('advanced_filter',
                   arg_group="Filtering",
                   action=EventSubscriptionAddFilter,
                   nargs='+')
        c.argument(
            'expiration_date',
            help=
            "Date or datetime (in UTC, e.g. '2018-11-30T11:59:59+00:00' or '2018-11-30') after which the event subscription would expire. By default, there is no expiration for the event subscription."
        )
        c.argument(
            'azure_active_directory_tenant_id',
            help=
            "The Azure Active Directory Tenant Id to get the access token that will be included as the bearer token in delivery requests. Applicable only for webhook as a destination"
        )
        c.argument(
            'azure_active_directory_application_id_or_uri',
            help=
            "The Azure Active Directory Application Id or Uri to get the access token that will be included as the bearer token in delivery requests. Applicable only for webhook as a destination"
        )
        c.argument('delivery_identity', arg_type=delivery_identity_type)
        c.argument('deadletter_identity', arg_type=deadletter_identity_type)
        c.argument(
            'delivery_identity_endpoint',
            help=
            "Endpoint with identity where EventGrid should deliver events matching this event subscription. For webhook endpoint type, this should be the corresponding webhook URL. For other endpoint types, this should be the Azure resource identifier of the endpoint.",
            is_preview=True)
        c.argument(
            'delivery_identity_endpoint_type',
            arg_type=get_enum_type([
                'webhook', 'eventhub', 'storagequeue', 'hybridconnection',
                'servicebusqueue', 'servicebustopic', 'azurefunction'
            ],
                                   default=None),
            is_preview=True)
        c.argument(
            'enable_advanced_filtering_on_arrays',
            is_preview=True,
            arg_type=get_three_state_flag(),
            options_list=[
                '--enable-advanced-filtering-on-arrays', '--enable-af-arr'
            ],
            arg_group="Filtering",
            help=
            "Allows advanced filters to be evaluated against an array of values instead of expecting a singular value."
        )
        c.argument('storage_queue_msg_ttl',
                   help="Storage queue message time to live in seconds.",
                   type=int,
                   options_list=['--storage-queue-msg-ttl', '--qttl'],
                   is_preview=True)
        c.argument(
            'delivery_attribute_mapping',
            action=AddDeliveryAttributeMapping,
            nargs='+',
            is_preview=True,
            help=
            'Add delivery attribute mapping to send additional information via HTTP headers when delivering events. This attribute is valid for all destination types except StorageQueue. Multiple attributes can be specified by using more than one `--delivery-attribute-mapping` argument',
            options_list=['--delivery-attribute-mapping'])

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

    with self.argument_context('eventgrid event-subscription show') as c:
        c.argument(
            'include_full_endpoint_url',
            arg_type=get_three_state_flag(),
            options_list=['--include-full-endpoint-url'],
            help=
            "Specify to indicate whether the full endpoint URL should be returned. True if flag present."
        )
        c.argument(
            'include_static_delivery_attribute_secret',
            arg_type=get_three_state_flag(),
            options_list=[
                '--include-static-delivery-attribute-secret',
                '--include-attrib-secret'
            ],
            help=
            "Indicate whether any static delivery attribute secrets should be returned. True if flag present.",
            is_preview=True)

    with self.argument_context(
            'eventgrid system-topic event-subscription') as c:
        c.argument('system_topic_name',
                   arg_type=system_topic_name_type,
                   id_part=None,
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/systemtopics'))
        c.argument('event_subscription_name',
                   arg_type=name_type,
                   options_list=['--name', '-n'],
                   help='Name of the event subscription.')
        c.argument(
            'endpoint_type',
            arg_type=get_enum_type([
                'webhook', 'eventhub', 'storagequeue', 'hybridconnection',
                'servicebusqueue', 'servicebustopic', 'azurefunction'
            ],
                                   default='webhook'))
        c.argument(
            'event_delivery_schema',
            arg_type=get_enum_type([
                'eventgridschema', 'custominputschema', 'cloudeventschemav1_0'
            ]),
            help=
            'The schema in which events should be delivered for this event subscription. By default, events will be delivered in the same schema in which they are published (based on the corresponding topic\'s input schema).'
        )
        c.argument(
            'max_delivery_attempts',
            help=
            "Maximum number of delivery attempts. Must be a number between 1 and 30."
        )
        c.argument(
            'max_events_per_batch',
            help=
            "Maximum number of events in a batch. Must be a number between 1 and 5000."
        )
        c.argument(
            'preferred_batch_size_in_kilobytes',
            help=
            "Preferred batch size in kilobytes. Must be a number between 1 and 1024."
        )
        c.argument(
            'event_ttl',
            help=
            "Event time to live (in minutes). Must be a number between 1 and 1440."
        )
        c.argument(
            'deadletter_endpoint',
            help=
            "The Azure resource ID of an Azure Storage blob container destination where EventGrid should deadletter undeliverable events for this event subscription."
        )
        c.argument('advanced_filter',
                   arg_group="Filtering",
                   action=EventSubscriptionAddFilter,
                   nargs='+')
        c.argument(
            'expiration_date',
            help=
            "Date or datetime (in UTC, e.g. '2018-11-30T11:59:59+00:00' or '2018-11-30') after which the event subscription would expire. By default, there is no expiration for the event subscription."
        )
        c.argument(
            'azure_active_directory_tenant_id',
            help=
            "The Azure Active Directory Tenant Id to get the access token that will be included as the bearer token in delivery requests. Applicable only for webhook as a destination"
        )
        c.argument(
            'azure_active_directory_application_id_or_uri',
            help=
            "The Azure Active Directory Application Id or Uri to get the access token that will be included as the bearer token in delivery requests. Applicable only for webhook as a destination"
        )
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument(
            'enable_advanced_filtering_on_arrays',
            is_preview=True,
            arg_type=get_three_state_flag(),
            options_list=[
                '--enable-advanced-filtering-on-arrays', '--enable-af-arr'
            ],
            arg_group="Filtering",
            help=
            "Allows advanced filters to be evaluated against an array of values instead of expecting a singular value."
        )
        c.argument('storage_queue_msg_ttl',
                   help="Storage queue message time to live in seconds.",
                   type=int,
                   options_list=['--storage-queue-msg-ttl', '--qttl'],
                   is_preview=True)
        c.argument(
            'delivery_attribute_mapping',
            action=AddDeliveryAttributeMapping,
            nargs='+',
            is_preview=True,
            help=
            'Add delivery attribute mapping to send additional information via HTTP headers when delivering events. This attribute is valid for all destination types except StorageQueue. Multiple attributes can be specified by using more than one `--delivery-attribute-mapping` argument',
            options_list=['--delivery-attribute-mapping'])

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

    with self.argument_context(
            'eventgrid system-topic event-subscription show') as c:
        c.argument('system_topic_name',
                   arg_type=system_topic_name_type,
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/systemtopics'))
        c.argument(
            'include_full_endpoint_url',
            arg_type=get_three_state_flag(),
            options_list=['--include-full-endpoint-url'],
            help=
            "Specify to indicate whether the full endpoint URL should be returned. True if flag present."
        )
        c.argument(
            'include_static_delivery_attribute_secret',
            arg_type=get_three_state_flag(),
            options_list=[
                '--include-static-delivery-attribute-secret',
                '--include-attrib-secret'
            ],
            help=
            "Indicate whether any static delivery attribute secrets should be returned. True if flag present.",
            is_preview=True)

    with self.argument_context(
            'eventgrid partner topic event-subscription') as c:
        c.argument('partner_topic_name',
                   arg_type=partner_topic_name_type,
                   id_part=None,
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/partnertopics'))
        c.argument('event_subscription_name',
                   arg_type=name_type,
                   options_list=['--name', '-n'],
                   help='Name of the event subscription.')
        c.argument(
            'endpoint_type',
            arg_type=get_enum_type([
                'webhook', 'eventhub', 'storagequeue', 'hybridconnection',
                'servicebusqueue', 'servicebustopic', 'azurefunction'
            ],
                                   default='webhook'))
        c.argument(
            'event_delivery_schema',
            arg_type=get_enum_type([
                'eventgridschema', 'custominputschema', 'cloudeventschemav1_0'
            ]),
            help=
            'The schema in which events should be delivered for this event subscription. By default, events will be delivered in the same schema in which they are published (based on the corresponding topic\'s input schema).'
        )
        c.argument(
            'max_delivery_attempts',
            help=
            "Maximum number of delivery attempts. Must be a number between 1 and 30."
        )
        c.argument(
            'max_events_per_batch',
            help=
            "Maximum number of events in a batch. Must be a number between 1 and 5000."
        )
        c.argument(
            'preferred_batch_size_in_kilobytes',
            help=
            "Preferred batch size in kilobytes. Must be a number between 1 and 1024."
        )
        c.argument(
            'event_ttl',
            help=
            "Event time to live (in minutes). Must be a number between 1 and 1440."
        )
        c.argument(
            'deadletter_endpoint',
            help=
            "The Azure resource ID of an Azure Storage blob container destination where EventGrid should deadletter undeliverable events for this event subscription."
        )
        c.argument('advanced_filter',
                   arg_group="Filtering",
                   action=EventSubscriptionAddFilter,
                   nargs='+')
        c.argument(
            'expiration_date',
            help=
            "Date or datetime (in UTC, e.g. '2018-11-30T11:59:59+00:00' or '2018-11-30') after which the event subscription would expire. By default, there is no expiration for the event subscription."
        )
        c.argument(
            'azure_active_directory_tenant_id',
            help=
            "The Azure Active Directory Tenant Id to get the access token that will be included as the bearer token in delivery requests. Applicable only for webhook as a destination"
        )
        c.argument(
            'azure_active_directory_application_id_or_uri',
            help=
            "The Azure Active Directory Application Id or Uri to get the access token that will be included as the bearer token in delivery requests. Applicable only for webhook as a destination"
        )
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument(
            'enable_advanced_filtering_on_arrays',
            is_preview=True,
            arg_type=get_three_state_flag(),
            options_list=[
                '--enable-advanced-filtering-on-arrays', '--enable-af-arr'
            ],
            arg_group="Filtering",
            help=
            "Allows advanced filters to be evaluated against an array of values instead of expecting a singular value."
        )
        c.argument('storage_queue_msg_ttl',
                   help="Storage queue message time to live in seconds.",
                   type=int,
                   options_list=['--storage-queue-msg-ttl', '--qttl'],
                   is_preview=True)
        c.argument(
            'delivery_attribute_mapping',
            action=AddDeliveryAttributeMapping,
            nargs='+',
            is_preview=True,
            help=
            'Add delivery attribute mapping to send additional information via HTTP headers when delivering events. This attribute is valid for all destination types except StorageQueue. Multiple attributes can be specified by using more than one `--delivery-attribute-mapping` argument',
            options_list=['--delivery-attribute-mapping'])

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

    with self.argument_context(
            'eventgrid partner topic event-subscription show') as c:
        c.argument('partner_topic_name',
                   arg_type=partner_topic_name_type,
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/partnertopics'))
        c.argument(
            'include_full_endpoint_url',
            arg_type=get_three_state_flag(),
            options_list=['--include-full-endpoint-url'],
            help=
            "Specify to indicate whether the full endpoint URL should be returned. True if flag present."
        )
        c.argument(
            'include_static_delivery_attribute_secret',
            arg_type=get_three_state_flag(),
            options_list=[
                '--include-static-delivery-attribute-secret',
                '--include-attrib-secret'
            ],
            help=
            "Indicate whether any static delivery attribute secrets should be returned. True if flag present.",
            is_preview=True)

    with self.argument_context('eventgrid topic-type') as c:
        c.argument('topic_type_name',
                   arg_type=name_type,
                   help="Name of the topic type.",
                   completer=get_resource_name_completion_list(
                       'Microsoft.EventGrid/topictypes'))
コード例 #45
0
ファイル: _params.py プロジェクト: yugangw-msft/azure-cli
def load_arguments(self, _):    # pylint: disable=too-many-statements

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('mysql server replica list') as c:
        c.argument('server_name', options_list=['--server-name', '-s'], help='Name of the master server.')
コード例 #46
0
ファイル: _params.py プロジェクト: sptramer/azure-cli
def load_arguments_eh(self, _):
    from knack.arguments import CLIArgumentType
    from azure.mgmt.eventhub.models import KeyType, AccessRights, SkuName
    from azure.cli.command_modules.eventhubs._completers import get_consumergroup_command_completion_list, get_eventhubs_command_completion_list
    from azure.cli.command_modules.eventhubs._validator import validate_storageaccount, validate_partner_namespace

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

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

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

    with self.argument_context('eventhubs namespace') as c:
        c.argument('namespace_name', arg_type=name_type, id_part='name', completer=get_resource_name_completion_list('Microsoft.ServiceBus/namespaces'), help='Name of Namespace')
        c.argument('is_kafka_enabled', options_list=['--enable-kafka'], arg_type=get_three_state_flag(),
                   help='A boolean value that indicates whether Kafka is enabled for eventhub namespace.')

    with self.argument_context('eventhubs namespace create') as c:
        c.argument('tags', arg_type=tags_type)
        c.argument('sku', options_list=['--sku'], arg_type=get_enum_type(SkuName))
        c.argument('location', arg_type=get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)
        c.argument('capacity', type=int, help='Capacity for Sku')
        c.argument('is_auto_inflate_enabled', options_list=['--enable-auto-inflate'], arg_type=get_three_state_flag(), help='A boolean value that indicates whether AutoInflate is enabled for eventhub namespace.')
        c.argument('maximum_throughput_units', type=int, help='Upper limit of throughput units when AutoInflate is enabled, vaule should be within 0 to 20 throughput units. ( 0 if AutoInflateEnabled = true)')

    with self.argument_context('eventhubs namespace update') as c:
        c.argument('tags', arg_type=tags_type)
        c.argument('sku', options_list=['--sku'], arg_type=get_enum_type(SkuName))
        c.argument('capacity', type=int, help='Capacity for Sku')
        c.argument('is_auto_inflate_enabled', options_list=['--enable-auto-inflate'], arg_type=get_three_state_flag(), help='A boolean value that indicates whether AutoInflate is enabled for eventhub namespace.')
        c.argument('maximum_throughput_units', type=int, help='Upper limit of throughput units when AutoInflate is enabled, vaule should be within 0 to 20 throughput units. ( 0 if AutoInflateEnabled = true)')

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

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

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

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

    with self.argument_context('eventhubs georecovery-alias authorization-rule keys list') as c:
        c.argument('alias', options_list=['--alias', '-a'], id_part=None, help='Name of Geo-Disaster Recovery Configuration Alias')
        c.argument('namespace_name', options_list=['--namespace-name'], id_part=None, help='Name of Namespace')
        c.argument('authorization_rule_name', arg_type=name_type, help='Name of Namespace AuthorizationRule')
コード例 #47
0
ファイル: _params.py プロジェクト: derekbekoe/azure-cli
def load_arguments(self, _):  # pylint: disable=too-many-statements
    # Arguments for IoT DPS
    with self.argument_context('iot dps') as c:
        c.argument('dps_name', dps_name_type, options_list=['--name', '-n'], id_part='name')

    with self.argument_context('iot dps create') as c:
        c.argument('location', get_location_type(self.cli_ctx),
                   help='Location of your IoT Provisioning Service. Default is the location of target resource group.')
        c.argument('sku', arg_type=get_enum_type(IotDpsSku),
                   help='Pricing tier for the IoT provisioning service.')
        c.argument('unit', help='Units in your IoT Provisioning Service.', type=int)

    for subgroup in ['access-policy', 'linked-hub', 'certificate']:
        with self.argument_context('iot dps {}'.format(subgroup)) as c:
            c.argument('dps_name', options_list=['--dps-name'], id_part=None)

    with self.argument_context('iot dps access-policy') as c:
        c.argument('access_policy_name', options_list=['--access-policy-name', '--name', '-n'],
                   help='A friendly name for DPS access policy.')

    with self.argument_context('iot dps access-policy create') as c:
        c.argument('rights', options_list=['--rights', '-r'], nargs='+',
                   arg_type=get_enum_type(AccessRightsDescription),
                   help='Access rights for the IoT provisioning service. Use space-separated list for multiple rights.')
        c.argument('primary_key', help='Primary SAS key value.')
        c.argument('secondary_key', help='Secondary SAS key value.')

    with self.argument_context('iot dps access-policy update') as c:
        c.argument('rights', options_list=['--rights', '-r'], nargs='+',
                   arg_type=get_enum_type(AccessRightsDescription),
                   help='Access rights for the IoT provisioning service. Use space-separated list for multiple rights.')
        c.argument('primary_key', help='Primary SAS key value.')
        c.argument('secondary_key', help='Secondary SAS key value.')

    with self.argument_context('iot dps linked-hub') as c:
        c.argument('linked_hub', options_list=['--linked-hub'], help='Host name of linked IoT Hub.')

    with self.argument_context('iot dps linked-hub create') as c:
        c.argument('connection_string', help='Connection string of the IoT hub.')
        c.argument('location', get_location_type(self.cli_ctx),
                   help='Location of the IoT hub.')
        c.argument('apply_allocation_policy',
                   help='A boolean indicating whether to apply allocation policy to the IoT hub.',
                   arg_type=get_three_state_flag())
        c.argument('allocation_weight', help='Allocation weight of the IoT hub.')

    with self.argument_context('iot dps linked-hub update') as c:
        c.argument('apply_allocation_policy',
                   help='A boolean indicating whether to apply allocation policy to the Iot hub.',
                   arg_type=get_three_state_flag())
        c.argument('allocation_weight', help='Allocation weight of the IoT hub.')

    with self.argument_context('iot dps allocation-policy update') as c:
        c.argument('allocation_policy', options_list=['--policy', '-p'], arg_type=get_enum_type(AllocationPolicy),
                   help='Allocation policy for the IoT provisioning service.')

    with self.argument_context('iot dps certificate') as c:
        c.argument('certificate_path', options_list=['--path', '-p'], type=file_type,
                   completer=FilesCompleter([".cer", ".pem"]), help='The path to the file containing the certificate.')
        c.argument('certificate_name', options_list=['--certificate-name', '--name', '-n'],
                   help='A friendly name for the certificate.')
        c.argument('etag', options_list=['--etag', '-e'], help='Entity Tag (etag) of the object.')

    # Arguments for IoT Hub
    with self.argument_context('iot') as c:
        c.argument('device_id', options_list=['--device-id', '-d'], help='Device Id.',
                   completer=get_device_id_completion_list)

    with self.argument_context('iot hub') as c:
        c.argument('hub_name', hub_name_type, options_list=['--name', '-n'], id_part='name')
        c.argument('etag', options_list=['--etag', '-e'], help='Entity Tag (etag) of the object.')

    for subgroup in ['consumer-group', 'policy', 'job', 'certificate']:
        with self.argument_context('iot hub {}'.format(subgroup)) as c:
            c.argument('hub_name', options_list=['--hub-name'])

    with self.argument_context('iot device') as c:
        c.argument('hub_name', hub_name_type)

    with self.argument_context('iot hub certificate') as c:
        c.argument('certificate_path', options_list=['--path', '-p'], type=file_type,
                   completer=FilesCompleter([".cer", ".pem"]), help='The path to the file containing the certificate.')
        c.argument('certificate_name', options_list=['--name', '-n'], help='A friendly name for the certificate.')

    with self.argument_context('iot hub consumer-group') as c:
        c.argument('consumer_group_name', options_list=['--name', '-n'], id_part='child_name_2',
                   help='Event hub consumer group name.')
        c.argument('event_hub_name', id_part='child_name_1', help='Event hub endpoint name.')

    with self.argument_context('iot hub policy') as c:
        c.argument('policy_name', options_list=['--name', '-n'], id_part='child_name_1',
                   help='Shared access policy name.')
        permission_values = ', '.join([x.value for x in SimpleAccessRights])
        c.argument('permissions', nargs='*', validator=validate_policy_permissions, type=str.lower,
                   help='Permissions of shared access policy. Use space-separated list for multiple permissions. '
                        'Possible values: {}'.format(permission_values))

    with self.argument_context('iot hub job') as c:
        c.argument('job_id', id_part='child_name_1', help='Job Id.')

    with self.argument_context('iot hub create') as c:
        c.argument('hub_name', completer=None)
        c.argument('location', get_location_type(self.cli_ctx),
                   help='Location of your IoT Hub. Default is the location of target resource group.')
        c.argument('sku', arg_type=get_enum_type(IotHubSku),
                   help='Pricing tier for Azure IoT Hub. Default value is F1, which is free. '
                        'Note that only one free IoT hub instance is allowed in each '
                        'subscription. Exception will be thrown if free instances exceed one.')
        c.argument('unit', help='Units in your IoT Hub.', type=int)
        c.argument('partition_count', help='The number of partitions for device-to-cloud messages.', type=int)

    with self.argument_context('iot hub show-connection-string') as c:
        c.argument('policy_name', help='Shared access policy to use.')
        c.argument('key_type', arg_type=get_enum_type(KeyType), options_list=['--key'], help='The key to use.')

    with self.argument_context('iot device create') as c:
        c.argument('device_id', completer=None)

    with self.argument_context('iot device create', arg_group='X.509 Certificate') as c:
        c.argument('x509', action='store_true', help='Use X.509 certificate for device authentication.')
        c.argument('primary_thumbprint', help='Primary X.509 certificate thumbprint to authenticate device.')
        c.argument('secondary_thumbprint', help='Secondary X.509 certificate thumbprint to authenticate device.')
        c.argument('valid_days', type=int, help='Number of days the generated self-signed X.509 certificate should be '
                                                'valid for. Default validity is 365 days.')
        c.argument('output_dir', help='Output directory for generated self-signed X.509 certificate. '
                                      'Default is current working directory.')

    with self.argument_context('iot device list') as c:
        c.argument('top', help='Maximum number of device identities to return.', type=int)

    with self.argument_context('iot device delete') as c:
        c.argument('etag', help='ETag of the target device. It is used for the purpose of optimistic '
                                'concurrency. Delete operation will be performed only if the specified '
                                'ETag matches the value maintained by the server, indicating that the '
                                'device identity has not been modified since it was retrieved. Default '
                                'value is set to wildcard character (*) to force an unconditional '
                                'delete.')

    with self.argument_context('iot device show-connection-string') as c:
        c.argument('top', type=int, help='Maximum number of connection strings to return.')
        c.argument('key_type', arg_type=get_enum_type(KeyType), options_list=['--key'], help='The key to use.')

    with self.argument_context('iot device message') as c:
        c.argument('lock_token', help='Message lock token.')

    with self.argument_context('iot device message send', arg_group='Messaging') as c:
        c.argument('data', help='Device-to-cloud message body.')
        c.argument('message_id', help='Device-to-cloud message Id.')
        c.argument('correlation_id', help='Device-to-cloud message correlation Id.')
        c.argument('user_id', help='Device-to-cloud message user Id.')

    with self.argument_context('iot device message receive') as c:
        c.argument('lock_timeout', type=int,
                   help='In case a message returned to this call, this specifies the amount of '
                        'time in seconds, the message will be invisible to other receive calls.')

    with self.argument_context('iot device export') as c:
        c.argument('blob_container_uri',
                   help='Blob Shared Access Signature URI with write access to a blob container.'
                        'This is used to output the status of the job and the results.')
        c.argument('include_keys', action='store_true',
                   help='If set, keys are exported normally. Otherwise, keys are set to null in '
                        'export output.')

    with self.argument_context('iot device import') as c:
        c.argument('input_blob_container_uri',
                   help='Blob Shared Access Signature URI with read access to a blob container.'
                        'This blob contains the operations to be performed on the identity '
                        'registry ')
        c.argument('output_blob_container_uri',
                   help='Blob Shared Access Signature URI with write access to a blob container.'
                        'This is used to output the status of the job and the results.')
コード例 #48
0
def load_arguments(self, _):

    from azext_front_door.vendored_sdks.models import (
        PolicyMode, FrontDoorProtocol, FrontDoorHealthProbeMethod,
        FrontDoorCertificateSource, FrontDoorQuery, ActionType, RuleType,
        TransformType, FrontDoorRedirectType, FrontDoorRedirectProtocol,
        MinimumTLSVersion)

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

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

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

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

    with self.argument_context('network front-door', arg_group='HTTPS') as c:
        c.argument('certificate_source',
                   arg_type=get_enum_type(FrontDoorCertificateSource),
                   help='Certificate source to enable HTTPS.')
        c.argument(
            'secret_name',
            help=
            'The name of the Key Vault secret representing the full certificate PFX'
        )
        c.argument(
            'secret_version',
            help=
            'The version of the Key Vault secret representing the full certificate PFX'
        )
        c.argument(
            'vault_id',
            help=
            'The resource id of the Key Vault containing the SSL certificate')
        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',
                   help='Protocol to use for forwarding traffic.')
        c.argument(
            'route_type',
            arg_type=get_enum_type(RouteType),
            help=
            'Route type to define how Front Door should handle requests for this route i.e. forward them to a backend or redirect the users to a different URL.'
        )

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

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

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

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

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

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

    with self.argument_context('network front-door routing-rule',
                               arg_group=None) as c:
        c.argument(
            'accepted_protocols',
            nargs='+',
            help='Space-separated list of protocols to accept. Default: Http')
        c.argument(
            'patterns_to_match',
            options_list='--patterns',
            nargs='+',
            help='Space-separated list of patterns to match. Default: \'/*\'.')
        c.argument('forwarding_protocol',
                   help='Protocol to use for forwarding traffic.')
        c.argument('backend_pool',
                   help='Name or ID of a backend pool.',
                   validator=validate_backend_pool)
        c.argument(
            'frontend_endpoints',
            help='Space-separated list of frontend endpoint names or IDs.',
            nargs='+',
            validator=validate_frontend_endpoints)
    with self.argument_context('network front-door routing-rule',
                               arg_group='Forward Routing Rule') as c:
        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('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.')
    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)
コード例 #49
0
def load_arguments(self, _):

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('network express-route update') as c:
        c.argument('sku_family', sku_family_type, default=None)
        c.argument('sku_tier', sku_tier_type, default=None)
コード例 #50
0
ファイル: _params.py プロジェクト: superclassiceth/azure-cli
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('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"')
コード例 #51
0
ファイル: _params.py プロジェクト: yugangw-msft/azure-cli
def load_arguments(self, _):

    for scope in ['sql vm', 'sql vm group']:
        with self.argument_context(scope) as c:
            c.argument('tags', tags_type)

    ###############################################
    #    sql virtual machine groups params        #
    ###############################################

    with self.argument_context('sql vm group') as c:
        c.argument('sql_virtual_machine_group_name',
                   options_list=['--name', '-n'],
                   id_part='name',
                   help='Name of the SQL virtual machine group.')
        c.argument('sql_image_offer',
                   options_list=['--image-offer', '-i'],
                   help='SQL image offer. Examples may include SQL2016-WS2016, SQL2017-WS2016.')
        c.argument('sql_image_sku',
                   options_list=['--image-sku', '-s'],
                   help='SQL image sku.',
                   arg_type=get_enum_type(SqlVmGroupImageSku))
        c.argument('location',
                   help='Location. If not provided, group will be created in the same reosurce group location.'
                   'You can configure the default location using `az configure --defaults location=<location>`.',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)

    with self.argument_context('sql vm group', arg_group='WSFC Domain Profile') as c:
        c.argument('domain_fqdn',
                   options_list=['--domain-fqdn', '-f'],
                   help='Fully qualified name of the domain.')
        c.argument('cluster_operator_account',
                   options_list=['--operator-acc', '-p'],
                   help='Account name used for operating cluster i.e. will be part of administrators group on all the participating virtual machines in the cluster.')
        c.argument('sql_service_account',
                   options_list=['--service-acc', '-e'],
                   help='Account name under which SQL service will run on all participating SQL virtual machines in the cluster.')
        c.argument('storage_account_url',
                   options_list=['--storage-account', '-u'],
                   help='Storage account url of the witness storage account.')
        c.argument('storage_account_key',
                   options_list=['--sa-key', '-k'],
                   help='Primary key of the witness storage account.')
        c.argument('cluster_bootstrap_account',
                   options_list=['--bootstrap-acc'],
                   help='Account name used for creating cluster (at minimum needs permissions to \'Create Computer Objects\' in domain).')
        c.argument('file_share_witness_path',
                   options_list=['--fsw-path'],
                   help='Optional path for fileshare witness.')
        c.argument('ou_path',
                   help='Organizational Unit path in which the nodes and cluster will be present. Example: OU=WSCluster,DC=testdomain,DC=com')

    ###############################################
    #    availability group listener params       #
    ###############################################

    with self.argument_context('sql vm group ag-listener') as c:
        c.argument('availability_group_listener_name',
                   options_list=['--name', '-n'],
                   id_part='name',
                   help='Name of the availability group listener.')
        c.argument('sql_virtual_machine_group_name',
                   options_list=['--group-name', '-r'],
                   help='Name of the SQL virtual machine group.',
                   id_part=None)
        c.argument('port',
                   options_list=['--port', '-p'],
                   help='Listener port.',
                   type=int)
        c.argument('availability_group_name',
                   options_list=['--ag-name', '-a'],
                   help='Name of the availability group. Please refer to '
                   'https://docs.microsoft.com/en-us/sql/database-engine/availability-groups/windows/use-the-availability-group-wizard-sql-server-management-studio?view=sql-server-2017 '
                   'to create and availability group')

    with self.argument_context('sql vm group ag-listener', arg_group='Load Balancer Configuration') as c:
        c.argument('ip_address',
                   options_list=['--ip-address', '-i'],
                   help='Private IP address bound to the availability group listener.')
        c.argument('subnet_resource_id',
                   options_list=['--subnet', '-u'],
                   validator=validate_subnet,
                   help='The name or resource id of the subnet to include in the private IP.')
        c.argument('vnet_name',
                   options_list=['--vnet-name'],
                   help='Name of the virtual network. Provide only if name of the subnet has been provided.')
        c.argument('public_ip_address_resource_id',
                   options_list=['--public-ip', '-c'],
                   validator=validate_public_ip_address,
                   help='Name or resource ID of the public IP.')
        c.argument('load_balancer_resource_id',
                   options_list=['--load-balancer', '-b'],
                   validator=validate_load_balancer,
                   help='Name or resource ID of the load balancer.')
        c.argument('probe_port',
                   options_list=['--probe-port', '-e'],
                   help='Probe port.',
                   type=int)
        c.argument('sql_virtual_machine_instances',
                   options_list=['--sqlvms', '-q'],
                   nargs='+',
                   validator=validate_sqlvm_list,
                   help='Space-separated list of SQL virtual machine instance name or resource IDs that are enrolled into the availability group.')

    ###############################################
    #      sql virtual machine params             #
    ###############################################

    with self.argument_context('sql vm') as c:
        c.argument('sql_virtual_machine_name',
                   options_list=['--name', '-n'],
                   id_part='name',
                   help='Name of the SQL virtual machine.')
        c.argument('location',
                   help='Location. If not provided, virtual machine should be in the same region of resource group.'
                   'You can configure the default location using `az configure --defaults location=<location>`.',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('expand',
                   help='Get the SQLIaaSExtension configuration settings.',
                   arg_type=get_enum_type(['*']))

    with self.argument_context('sql vm', arg_group='SQL Server License') as c:
        c.argument('sql_server_license_type',
                   help='SQL Server license type.',
                   options_list=['--license-type'],
                   arg_type=get_enum_type(SqlServerLicenseType))

    with self.argument_context('sql vm add-to-group') as c:
        c.argument('sql_virtual_machine_group_resource_id',
                   options_list=['--sqlvm-group', '-r'],
                   validator=validate_sqlvm_group,
                   help='Name or resource ID of the SQL virtual machine group. If only name provided, SQL virtual machine group should be in the same '
                   'resource group of the SQL virtual machine.')
        c.argument('sql_virtual_machine_name',
                   id_part='name',
                   help="Name of the SQL virtual machine.")

    with self.argument_context('sql vm remove-from-group') as c:
        c.argument('sql_virtual_machine_name',
                   id_part='name',
                   help="Name of the SQL virtual machine.")

    with self.argument_context('sql vm add-to-group', arg_group='WSFC Domain Credentials') as c:
        c.argument('cluster_bootstrap_account_password',
                   options_list=['-b', '--bootstrap-acc-pwd',
                                 c.deprecate(target='--boostrap-acc-pwd', redirect='--bootstrap-acc-pwd')],
                   help='Password for the cluster bootstrap account if provided in the SQL virtual machine group.')
        c.argument('cluster_operator_account_password',
                   options_list=['--operator-acc-pwd', '-p'],
                   help='Password for the cluster operator account provided in the SQL virtual machine group.')
        c.argument('sql_service_account_password',
                   options_list=['--service-acc-pwd', '-s'],
                   help='Password for the SQL service account provided in the SQL virtual machine group.')

    with self.argument_context('sql vm', arg_group='Auto Patching Settings') as c:
        c.argument('enable_auto_patching',
                   help='Enable or disable autopatching on SQL virtual machine. If any autopatching settings provided, parameter automatically sets to true.',
                   arg_type=get_three_state_flag())
        c.argument('day_of_week',
                   help='Day of week to apply the patch on.',
                   arg_type=get_enum_type(DayOfWeek))
        c.argument('maintenance_window_starting_hour',
                   type=int,
                   options_list=['--maintenance-window-start-hour'],
                   help='Hour of the day when patching is initiated. Local VM time 0-23 hours.')
        c.argument('maintenance_window_duration',
                   type=int,
                   help='Duration of patching. 30-180 minutes.')

    with self.argument_context('sql vm', arg_group='Auto Backup Settings') as c:
        c.argument('enable_auto_backup',
                   help='Enable or disable autobackup on SQL virtual machine. If any backup settings provided, parameter automatically sets to true.',
                   arg_type=get_three_state_flag())
        c.argument('enable_encryption',
                   help=' Enable encryption for backup on SQL virtual machine.',
                   arg_type=get_three_state_flag())
        c.argument('retention_period',
                   type=int,
                   help='Retention period of backup. 1-30 days.')
        c.argument('storage_account_url',
                   options_list=['--storage-account'],
                   help='Storage account url where backup will be taken to.')
        c.argument('storage_access_key',
                   options_list=['--sa-key'],
                   help='Storage account key where backup will be taken to.')
        c.argument('backup_password',
                   options_list=['--backup-pwd'],
                   help='Password for encryption on backup.')
        c.argument('backup_system_dbs',
                   help='Include system databases on backup.',
                   arg_type=get_three_state_flag())
        c.argument('backup_schedule_type',
                   help='Backup schedule type.',
                   arg_type=get_enum_type(BackupScheduleType))
        c.argument('full_backup_frequency',
                   help='Frequency of full backups. In both cases, full backups begin during the next scheduled time window.',
                   arg_type=get_enum_type(FullBackupFrequencyType))
        c.argument('full_backup_start_time',
                   type=int,
                   options_list=['--full-backup-start-hour'],
                   help='Start time of a given day during which full backups can take place. 0-23 hours.')
        c.argument('full_backup_window_hours',
                   type=int,
                   options_list=['--full-backup-duration'],
                   help='Duration of the time window of a given day during which full backups can take place. 1-23 hours.')
        c.argument('log_backup_frequency',
                   type=int,
                   help='Frequency of log backups. 5-60 minutes.')

    with self.argument_context('sql vm', arg_group='Key Vault Credential Settings') as c:
        c.argument('enable_key_vault_credential',
                   help='Enable or disable key vault credential setting. If any key vault settings provided, parameter automatically sets to true.',
                   arg_type=get_three_state_flag())
        c.argument('credential_name',
                   help='Credential name')
        c.argument('azure_key_vault_url',
                   options_list=['--key-vault'],
                   help='Azure Key Vault url.')
        c.argument('service_principal_name',
                   options_list=['--sp-name'],
                   help='Service principal name to access key vault.')
        c.argument('service_principal_secret',
                   options_list=['--sp-secret'],
                   help='Service principal name secret to access key vault.')

    with self.argument_context('sql vm', arg_group='SQL Connectivity Update Settings') as c:
        c.argument('connectivity_type',
                   help='SQL Server connectivity option.',
                   arg_type=get_enum_type(ConnectivityType))
        c.argument('port',
                   help='SQL Server port.',
                   type=int)
        c.argument('sql_auth_update_username',
                   help='SQL Server sysadmin login to create.')
        c.argument('sql_auth_update_password',
                   options_list=['--sql-auth-update-pwd'],
                   help='SQL Server sysadmin login password.')

    with self.argument_context('sql vm', arg_group='SQL Workload Type Update Settings') as c:
        c.argument('sql_workload_type',
                   help='SQL Server workload type.',
                   arg_type=get_enum_type(SqlWorkloadType))

    with self.argument_context('sql vm', arg_group='SQL Storage Update Settings') as c:
        c.argument('disk_count',
                   help='Virtual machine disk count.',
                   type=int)
        c.argument('disk_configuration_type',
                   help='Disk configuration to apply to SQL Server.',
                   arg_type=get_enum_type(DiskConfigurationType))

    with self.argument_context('sql vm', arg_group='Additional Features') as c:
        c.argument('enable_r_services',
                   help='Enable or disable R services (SQL 2016 onwards).',
                   arg_type=get_three_state_flag())
コード例 #52
0
def load_arguments(self, _):
    from azure.mgmt.monitor.models import ConditionOperator, TimeAggregationOperator, EventData
    from .grammar.metric_alert.MetricAlertConditionValidator import dim_op_conversion, agg_conversion, op_conversion, sens_conversion
    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. '
            'The resources specified in this parameter must be of the same type and exist in the same location.'
        )
        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.')
        c.argument(
            'target_resource_type',
            options_list=['--target-resource-type', '--type'],
            help='The resource type of the target resource(s) in scopes. '
            'This must be provided when scopes is resource group or subscription.'
        )
        c.argument(
            'target_resource_region',
            options_list=['--target-resource-region', '--region'],
            help='The region of the target resource(s) in scopes. '
            'This must be provided when scopes is resource group or subscription.'
        )

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

    with self.argument_context('monitor metrics alert dimension create',
                               arg_group=None) as c:
        c.argument('dimension_name',
                   options_list=['--name', '-n'],
                   help='Name of the dimension.')
        c.argument('operator',
                   options_list=['--operator', '--op'],
                   arg_type=get_enum_type(
                       dim_op_conversion.values(),
                       default=dim_op_conversion['includes']),
                   help="Dimension operator.")
        c.argument('value_list',
                   options_list=['--value', '-v'],
                   nargs='+',
                   help='The values to apply on the operation.')

    with self.argument_context('monitor metrics alert condition create',
                               arg_group=None) as c:
        c.argument('condition_type',
                   options_list=['--type', '-t'],
                   arg_type=get_enum_type(['static', 'dynamic']),
                   help='Type of condition threshold.')
        c.argument('metric_name',
                   options_list=['--metric'],
                   help='Name of metric.')
        c.argument('metric_namespace',
                   options_list=['--namespace'],
                   help='Namespace of metric.')
        c.argument(
            'dimension_list',
            options_list=['--dimension'],
            nargs='+',
            help=
            'Dimension created by \'az monitor metrics alert dimension create\'.'
        )
        c.argument('aggregation',
                   arg_type=get_enum_type(agg_conversion.values()),
                   help='Time aggregation.')
        c.argument(
            'operator',
            options_list=['--operator', '--op'],
            arg_type=get_enum_type(op_conversion.values()),
            help=
            "Operator for static threshold can be 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan' or 'LessThanOrEqual'. "
            "Operator for dynamic threshold can be 'GreaterThan', 'LessThan', 'GreaterOrLessThan'."
        )
        c.argument('threshold', type=float, help='Static threshold value.')
        c.argument('alert_sensitivity',
                   options_list=['--sensitivity'],
                   arg_type=get_enum_type(sens_conversion.values(),
                                          default='Medium'),
                   help="Alert sensitivity for dynamic threshold.")
        c.argument(
            'number_of_evaluation_periods',
            options_list=['--num-periods'],
            type=int,
            help='The number of evaluation periods for dynamic threshold. '
            'Range: 1-6.')
        c.argument(
            'min_failing_periods_to_alert',
            options_list=['--num-violations'],
            type=int,
            help='The number of violations to trigger an dynamic alert. '
            'Range: 1-6. It should be less than or equal to --num-periods.')
        c.argument(
            'ignore_data_before',
            options_list=['--since'],
            arg_type=get_datetime_type(
                help=
                'The date from which to start learning the metric historical data and calculate the dynamic thresholds.'
            ))

    # 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)
        c.argument(
            'export_to_resource_specific',
            arg_type=get_three_state_flag(),
            help=
            'Indicate that the export to LA must be done to a resource specific table, '
            'a.k.a. dedicated or fixed schema table, '
            'as opposed to the default dynamic schema table called AzureDiagnostics. '
            'This argument is effective only when the argument --workspace is also given.'
        )

    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)

    with self.argument_context(
            'monitor diagnostic-settings subscription') as c:
        import argparse
        c.argument('subscription_id',
                   validator=process_subscription_id,
                   help=argparse.SUPPRESS,
                   required=False)
        c.argument(
            'logs',
            type=get_json_object,
            help=
            "JSON encoded list of logs settings. Use '@{file}' to load from a file."
        )
        c.argument('name',
                   help='The name of the diagnostic setting.',
                   options_list=['--name', '-n'])
        c.argument(
            'event_hub_name',
            help=
            'The name of the event hub. If none is specified, the default event hub will be selected.'
        )
        c.argument(
            'event_hub_auth_rule',
            help='The resource Id for the event hub authorization rule.')
        c.argument('workspace',
                   help='The resource id of the log analytics workspace.')
        c.argument(
            'storage_account',
            help=
            'The resource id of the storage account to which you would like to send the Activity Log.'
        )
        c.argument(
            'service_bus_rule',
            help=
            "The service bus rule ID of the service bus namespace in which you would like to have Event Hubs created for streaming the Activity Log. The rule ID is of the format '{service bus resource ID}/authorizationrules/{key name}'."
        )
    # 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.argument('sku',
                   help="The supported value: PerGB2018, CapacityReservation.")
        c.argument(
            'capacity_reservation_level',
            options_list=['--capacity-reservation-level', '--level'],
            help=
            'The capacity reservation level for this workspace, when CapacityReservation sku is selected. The maximum value is 1000 and must be in multiples of 100. If you want to increase the limit, please contact [email protected].'
        )
        c.argument(
            'daily_quota_gb',
            options_list=['--quota'],
            help=
            'The workspace daily quota for ingestion in gigabytes. The minimum value is 0.023 and default is -1 which means unlimited.'
        )
        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))
        c.argument('force',
                   options_list=['--force', '-f'],
                   arg_type=get_three_state_flag())

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

    with self.argument_context(
            'monitor log-analytics workspace saved-search') as c:
        c.argument(
            'saved_search_id',
            options_list=['--name', '-n'],
            help=
            "Name of the saved search and it's unique in a given workspace.")
        c.argument('workspace_name', options_list='--workspace-name')
        c.argument(
            'category',
            help=
            'The category of the saved search. This helps the user to find a saved search faster.'
        )
        c.argument('display_name', help='Display name of the saved search.')
        c.argument('saved_query',
                   options_list=['--saved-query', '-q'],
                   help='The query expression for the saved search.')
        c.argument(
            'function_alias',
            options_list=['--func-alias', '--fa'],
            help=
            'Function Aliases are short names given to Saved Searches so they can be easily referenced in query. They are required for Computer Groups.'
        )
        c.argument(
            'function_parameters',
            options_list=['--func-param', '--fp'],
            help=
            "The optional function parameters if query serves as a function. "
            "Value should be in the following format: 'param-name1:type1 = default_value1, param-name2:type2 = default_value2'. "
            "For more examples and proper syntax please refer to "
            "https://docs.microsoft.com/en-us/azure/kusto/query/functions/user-defined-functions."
        )
        c.argument('tags', tags_type)
    # endregion

    # region Log Analytics Workspace table
    with self.argument_context('monitor log-analytics workspace table') as c:
        c.argument('table_name', name_arg_type, help='Name of the table.')
        c.argument('workspace_name', options_list='--workspace-name')
        c.argument('retention_in_days',
                   options_list='--retention-time',
                   type=int,
                   required=True)
    # endregion

    # region Log Analytics Workspace Data Export
    with self.argument_context(
            'monitor log-analytics workspace data-export') as c:
        c.argument('data_export_name',
                   options_list=['--name', '-n'],
                   help="Name of the data export rule")
        c.argument('workspace_name', options_list='--workspace-name')
        c.argument(
            'table_names',
            nargs='+',
            options_list=['--tables', '-t'],
            help=
            'An array of tables to export. if --export-all-tables is true, this argument should not be provided.'
        )
        c.argument(
            'destination',
            validator=process_workspace_data_export_destination,
            help=
            'The destination resource ID. It should be a storage account, an event hub namespace or an event hub. '
            'If event hub namespace is provided, event hub would be created for each table automatically.'
        )
        c.ignore('data_export_type')
        c.ignore('event_hub_name')
        c.argument('enable',
                   arg_type=get_three_state_flag(),
                   help='Enable this data export rule.')
    # 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))
コード例 #53
0
ファイル: _params.py プロジェクト: sptramer/azure-cli
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)

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

    _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.')
        c.argument('subscription', arg_type=subscription_type)
        c.argument('management_group', arg_type=management_group_name_type)

    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.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 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('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('subscription', arg_type=subscription_type)
        c.argument('management_group', arg_type=management_group_name_type)

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

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

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

    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)

    with self.argument_context('account management-group') as c:
        c.argument('group_name', options_list=['--name', '-n'])
        c.ignore('_subscription')  # hide global subscription parameter

    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'])
コード例 #54
0
def load_arguments(self, _):  # pylint: disable=too-many-locals, too-many-statements, too-many-lines
    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

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

    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')
    t_blob_tier = self.get_sdk(
        '_generated.models._azure_blob_storage_enums#AccessTierOptional',
        resource_type=CUSTOM_DATA_STORAGE_BLOB)
    t_rehydrate_priority = self.get_sdk(
        '_generated.models._azure_blob_storage_enums#RehydratePriority',
        resource_type=CUSTOM_DATA_STORAGE_BLOB)

    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_storage_name_completion_list(t_base_blob_service,
                                                   'list_containers'))
    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'))
    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'))
    progress_type = CLIArgumentType(
        help='Include this flag to disable progress reporting for the command.',
        action='store_true',
        validator=add_progress_callback)
    sas_help = 'The permissions the SAS grants. Allowed values: {}. Do not use if a stored access policy is ' \
               'referenced with --policy-name that specifies this value. Can be combined.'

    lease_type = CLIArgumentType(
        options_list='--lease-id',
        help='Required if the blob has an active lease.')

    snapshot_type = CLIArgumentType(
        help=
        'The snapshot parameter is an opaque DateTime value that, when present, specifies the blob snapshot '
        'to retrieve.')

    tags_type = CLIArgumentType(
        nargs='*',
        validator=validate_tags,
        min_api='2019-12-12',
        is_preview=True,
        help=
        'space-separated tags: key[=value] [key[=value] ...]. Tags are case-sensitive. The tag set may '
        'contain at most 10 tags.  Tag keys must be between 1 and 128 characters, and tag values must be '
        'between 0 and 256 characters. Valid tag key and value characters include: lowercase and uppercase '
        'letters, digits (0-9), space (` `), plus (+), minus (-), period (.), solidus (/), colon (:), equals '
        '(=), underscore (_).')

    marker_type = CLIArgumentType(
        help=
        'A string value that identifies the portion of the list of containers to be '
        'returned with the next listing operation. The operation returns the NextMarker value within '
        'the response body if the listing operation did not return all containers remaining to be listed '
        'with the current page. If specified, this generator will begin returning results from the point '
        'where the previous generator stopped.')

    num_results_type = CLIArgumentType(
        default=5000,
        validator=validate_storage_data_plane_list,
        options_list='--num-results',
        help=
        'Specify the maximum number to return. If the request does not specify '
        'num_results, or specifies a value greater than 5000, the server will return up to 5000 items. Note that '
        'if the listing operation crosses a partition boundary, then the service will return a continuation token '
        'for retrieving the remaining of the results. Provide "*" to return all.'
    )

    version_id_type = CLIArgumentType(
        help=
        'An optional blob version ID. This parameter is only for versioning enabled account. ',
        min_api='2019-12-12',
        is_preview=True)  # Fix preview display

    tier_type = CLIArgumentType(
        arg_type=get_enum_type(t_blob_tier),
        min_api='2019-02-02',
        help=
        'The tier value to set the blob to. For page blob, the tier correlates to the size of the blob '
        'and number of allowed IOPS. Possible values are P10, P15, P20, P30, P4, P40, P50, P6, P60, P70, P80 '
        'and this is only applicable to page blobs on premium storage accounts; For block blob, possible '
        'values are Archive, Cool and Hot. This is only applicable to block blobs on standard storage accounts.'
    )

    rehydrate_priority_type = CLIArgumentType(
        arg_type=get_enum_type(t_rehydrate_priority),
        options_list=('--rehydrate-priority', '-r'),
        min_api='2019-02-02',
        help='Indicate the priority with which to rehydrate an archived blob.')

    tags_condition_type = CLIArgumentType(
        options_list='--tags-condition',
        min_api='2019-12-12',
        help=
        'Specify a SQL where clause on blob tags to operate only on blobs with a matching value.'
    )
    timeout_type = CLIArgumentType(
        help='Request timeout in seconds. Applies to each call to the service.',
        type=int)

    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 account blob-service-properties show',
                               resource_type=CUSTOM_MGMT_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 blob-service-properties update',
            resource_type=CUSTOM_MGMT_STORAGE) as c:
        c.argument('account_name', acct_name_type, id_part=None)
        c.argument('resource_group_name',
                   required=False,
                   validator=process_resource_group)
        c.argument('enable_change_feed',
                   arg_type=get_three_state_flag(),
                   min_api='2019-04-01')
        c.argument(
            'enable_container_delete_retention',
            arg_type=get_three_state_flag(),
            options_list=[
                '--enable-container-delete-retention', '--container-retention'
            ],
            arg_group='Container Delete Retention Policy',
            min_api='2019-06-01',
            help=
            'Enable container delete retention policy for container soft delete when set to true. '
            'Disable container delete retention policy when set to false.')
        c.argument(
            'container_delete_retention_days',
            options_list=[
                '--container-delete-retention-days', '--container-days'
            ],
            type=int,
            arg_group='Container Delete Retention Policy',
            min_api='2019-06-01',
            validator=validate_container_delete_retention_days,
            help=
            'Indicate the number of days that the deleted container should be retained. The minimum '
            'specified value can be 1 and the maximum value can be 365.')
        c.argument('enable_delete_retention',
                   arg_type=get_three_state_flag(),
                   arg_group='Delete Retention Policy',
                   min_api='2018-07-01')
        c.argument('delete_retention_days',
                   type=int,
                   arg_group='Delete Retention Policy',
                   validator=validate_delete_retention_days,
                   min_api='2018-07-01')
        c.argument('enable_restore_policy',
                   arg_type=get_three_state_flag(),
                   arg_group='Restore Policy',
                   min_api='2019-06-01',
                   help="Enable blob restore policy when it set to true.")
        c.argument(
            'restore_days',
            type=int,
            arg_group='Restore Policy',
            min_api='2019-06-01',
            help=
            "The number of days for the blob can be restored. It should be greater "
            "than zero and less than Delete Retention Days.")
        c.argument('enable_versioning',
                   arg_type=get_three_state_flag(),
                   help='Versioning is enabled if set to true.',
                   min_api='2019-06-01')
        c.argument(
            'enable_last_access_tracking',
            arg_type=get_three_state_flag(),
            min_api='2019-06-01',
            options_list=['--enable-last-access-tracking', '-t'],
            help=
            'When set to true last access time based tracking policy is enabled.'
        )

    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/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 account management-policy update') as c:
        c.argument(
            'account_name',
            help=
            'The name of the storage account within the specified resource group.'
        )

    with self.argument_context('storage blob') as c:
        c.argument('blob_name',
                   options_list=('--name', '-n'),
                   arg_type=blob_name_type)

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

        c.register_blob_arguments()
        c.register_precondition_options()
        c.register_precondition_options(prefix='source_')
        c.register_source_uri_arguments(validator=validate_source_url)

        c.ignore('incremental_copy')
        c.argument('if_match', options_list=['--destination-if-match'])
        c.argument('if_modified_since',
                   options_list=['--destination-if-modified-since'])
        c.argument('if_none_match',
                   options_list=['--destination-if-none-match'])
        c.argument('if_unmodified_since',
                   options_list=['--destination-if-unmodified-since'])
        c.argument('if_tags_match_condition',
                   options_list=['--destination-tags-condition'])

        c.argument(
            'blob_name',
            options_list=['--destination-blob', '-b'],
            required=True,
            help=
            'Name of the destination blob. If the exists, it will be overwritten.'
        )
        c.argument('container_name',
                   options_list=['--destination-container', '-c'],
                   required=True,
                   help='The container name.')
        c.extra(
            'destination_lease',
            options_list='--destination-lease-id',
            help=
            'The lease ID specified for this header must match the lease ID of the estination blob. '
            'If the request does not include the lease ID or it is not valid, the operation fails with status '
            'code 412 (Precondition Failed).')
        c.extra(
            'source_lease',
            options_list='--source-lease-id',
            arg_group='Copy Source',
            help=
            'Specify this to perform the Copy Blob operation only if the lease ID given matches the '
            'active lease ID of the source blob.')
        c.extra('rehydrate_priority', rehydrate_priority_type)
        c.extra(
            'requires_sync',
            arg_type=get_three_state_flag(),
            help=
            'Enforce that the service will not return a response until the copy is complete.'
        )
        c.extra('tier', tier_type)
        c.extra('tags', tags_type)

    with self.argument_context('storage blob delete') as c:
        c.register_blob_arguments()
        c.register_precondition_options()

        c.extra('lease', lease_type)
        c.extra('snapshot', snapshot_type)
        c.extra('version_id', version_id_type)

    with self.argument_context('storage blob download') as c:
        from ._validators import add_progress_callback_v2
        c.register_blob_arguments()
        c.register_precondition_options()
        c.argument('file_path',
                   options_list=('--file', '-f'),
                   type=file_type,
                   completer=FilesCompleter(),
                   help='Path of file to write out to.')
        c.extra(
            'start_range',
            type=int,
            help=
            'Start of byte range to use for downloading a section of the blob. If no end_range is given, '
            'all bytes after the start_range will be downloaded. The start_range and end_range params are '
            'inclusive. Ex: start_range=0, end_range=511 will download first 512 bytes of blob.'
        )
        c.extra(
            'end_range',
            type=int,
            help=
            'End of byte range to use for downloading a section of the blob. If end_range is given, '
            'start_range must be provided. The start_range and end_range params are inclusive. Ex: start_range=0, '
            'end_range=511 will download first 512 bytes of blob.')
        c.extra('no_progress',
                progress_type,
                validator=add_progress_callback_v2)
        c.extra('snapshot', snapshot_type)
        c.extra('lease', lease_type)
        c.extra('version_id', version_id_type)
        c.extra(
            'max_concurrency',
            options_list='--max-connections',
            type=int,
            default=2,
            help='The number of parallel connections with which to download.')
        c.argument(
            'open_mode',
            help=
            'Mode to use when opening the file. Note that specifying append only open_mode '
            'prevents parallel download. So, max_connections must be set to 1 if this open_mode is used.'
        )
        c.argument(
            'socket_timeout',
            deprecate_info=c.deprecate(hide=True),
            help=
            'The socket timeout(secs), used by the service to regulate data flow.'
        )
        c.extra(
            'validate_content',
            action='store_true',
            min_api='2016-05-31',
            help=
            'If true, calculates an MD5 hash for each chunk of the blob. 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 blob. Also note that if enabled, the '
            'memory-efficient algorithm will not be used because computing the MD5 hash requires buffering '
            'entire blocks, and doing so defeats the purpose of the memory-efficient algorithm.'
        )

    with self.argument_context('storage blob exists') as c:
        c.register_blob_arguments()

    with self.argument_context('storage blob filter') as c:
        c.argument('filter_expression', options_list=['--tag-filter'])

    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(
            '_models#BlobSasPermissions',
            resource_type=CUSTOM_DATA_STORAGE_BLOB)
        c.register_sas_arguments()
        c.argument(
            'cache_control',
            help=
            'Response header value for Cache-Control when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'content_disposition',
            help=
            'Response header value for Content-Disposition when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'content_encoding',
            help=
            'Response header value for Content-Encoding when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'content_language',
            help=
            'Response header value for Content-Language when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'content_type',
            help=
            'Response header value for Content-Type when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'full_uri',
            action='store_true',
            help=
            'Indicate that this command return the full blob URI and the shared access signature token.'
        )
        c.argument(
            'as_user',
            min_api='2018-11-09',
            action='store_true',
            validator=as_user_validator,
            help=
            "Indicates that this command return the SAS signed with the user delegation key. "
            "The expiry parameter and '--auth-mode login' are required if this argument is specified. "
        )
        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(
            'ip',
            help=
            'Specify an IP address or a range of IP addresses from which to accept requests. '
            'If the IP address from which the request originates does not match the IP address or address range '
            'specified on the SAS token, the request is not authenticated. For example, specifying ip=168.1.5.65'
            ' or ip=168.1.5.60-168.1.5.70 on the SAS restricts the request to those IP addresses.'
        )
        c.argument('permission',
                   options_list='--permissions',
                   help=sas_help.format(
                       get_permission_help_string(t_blob_permissions)),
                   validator=get_permission_validator(t_blob_permissions))
        c.argument('snapshot', snapshot_type)
        c.ignore('sas_token')
        c.argument('version_id', version_id_type)

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

    with self.argument_context('storage blob lease acquire') as c:
        c.register_precondition_options()
        c.register_blob_arguments()
        c.extra(
            'lease_id',
            options_list='--proposed-lease-id',
            help='Proposed lease ID, in a GUID string format. '
            'The Blob service returns 400 (Invalid request) if the proposed lease ID is not in the correct format.'
        )
        c.argument(
            'lease_duration',
            help=
            'Specify the duration of the lease, in seconds, or negative one (-1) for '
            'a lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease '
            'duration cannot be changed using renew or change. Default is -1 (infinite lease)',
            type=int)
        c.extra('if_tags_match_condition', tags_condition_type)

    with self.argument_context('storage blob lease break') as c:
        c.register_precondition_options()
        c.register_blob_arguments()
        c.argument(
            'lease_break_period',
            type=int,
            help=
            "This is the proposed duration of seconds that the lease should continue before it is broken, "
            "between 0 and 60 seconds. This break period is only used if it is shorter than the time remaining "
            "on the lease. If longer, the time remaining on the lease is used. A new lease will not be "
            "available before the break period has expired, but the lease may be held for longer than the break "
            "period. If this header does not appear with a break operation, a fixed-duration lease breaks after "
            "the remaining lease period elapses, and an infinite lease breaks immediately."
        )
        c.extra('if_tags_match_condition', tags_condition_type)

    with self.argument_context('storage blob lease change') as c:
        c.register_precondition_options()
        c.register_blob_arguments()
        c.extra(
            'proposed_lease_id',
            help=
            'Proposed lease ID, in a GUID string format. The Blob service returns 400 '
            '(Invalid request) if the proposed lease ID is not in the correct format.',
            required=True)
        c.extra('lease_id',
                help='Required if the blob has an active lease.',
                required=True)
        c.extra('if_tags_match_condition', tags_condition_type)

    for item in ['release', 'renew']:
        with self.argument_context('storage blob lease {}'.format(item)) as c:
            c.register_precondition_options()
            c.register_blob_arguments()
            c.extra('lease_id',
                    help='Required if the blob has an active lease.',
                    required=True)
            c.extra('if_tags_match_condition', tags_condition_type)

    with self.argument_context('storage blob list') as c:
        from .track2_util import get_include_help_string
        t_blob_include = self.get_sdk(
            '_generated.models._azure_blob_storage_enums#ListBlobsIncludeItem',
            resource_type=CUSTOM_DATA_STORAGE_BLOB)
        c.register_container_arguments()
        c.argument(
            'delimiter',
            help=
            'When the request includes this parameter, the operation returns a BlobPrefix element in the '
            'result list that acts as a placeholder for all blobs whose names begin with the same substring '
            'up to the appearance of the delimiter character. The delimiter may be a single character or a '
            'string.')
        c.argument(
            'include',
            help=
            "Specify one or more additional datasets to include in the response. "
            "Options include: {}. Can be combined.".format(
                get_include_help_string(t_blob_include)),
            validator=validate_included_datasets_v2)
        c.argument('marker', arg_type=marker_type)
        c.argument('num_results', arg_type=num_results_type)
        c.argument(
            'prefix',
            help=
            'Filter the results to return only blobs whose name begins with the specified prefix.'
        )
        c.argument('show_next_marker',
                   action='store_true',
                   is_preview=True,
                   help='Show nextMarker in result when specified.')

    for item in ['show', 'update']:
        with self.argument_context('storage blob metadata {}'.format(item), resource_type=CUSTOM_DATA_STORAGE_BLOB) \
                as c:
            c.register_blob_arguments()
            c.register_precondition_options()
            c.extra('lease', lease_type)
            c.extra('snapshot', snapshot_type)
            c.extra('if_tags_match_condition', tags_condition_type)

    with self.argument_context('storage blob set-tier',
                               resource_type=CUSTOM_DATA_STORAGE_BLOB) as c:
        c.register_blob_arguments()

        c.argument('blob_type',
                   options_list=('--type', '-t'),
                   arg_type=get_enum_type(('block', 'page')))
        c.extra('tier',
                tier_type,
                validator=blob_tier_validator,
                required=True)
        c.argument('rehydrate_priority',
                   rehydrate_priority_type,
                   is_preview=True)
        c.extra('version_id', version_id_type)
        c.extra('if_tags_match_condition', tags_condition_type)

    with self.argument_context('storage blob show') as c:
        c.register_blob_arguments()
        c.register_precondition_options()
        c.extra('snapshot', snapshot_type)
        c.extra('lease', lease_type)
        c.argument('version_id', version_id_type)

    with self.argument_context('storage blob snapshot') as c:
        c.register_blob_arguments()
        c.register_precondition_options()
        c.extra('lease', lease_type)
        c.extra('if_tags_match_condition', tags_condition_type)

    with self.argument_context('storage blob undelete',
                               resource_type=CUSTOM_DATA_STORAGE_BLOB) as c:
        c.register_blob_arguments()

    with self.argument_context('storage blob tag list') as c:
        c.register_blob_arguments()
        c.extra('version_id', version_id_type)
        c.extra('snapshot', snapshot_type)
        c.extra('if_tags_match_condition', tags_condition_type)

    with self.argument_context('storage blob tag set') as c:
        c.register_blob_arguments()
        c.extra('version_id', version_id_type)
        c.argument('tags', tags_type, required=True)
        c.extra('if_tags_match_condition', tags_condition_type)

    with self.argument_context('storage blob upload') as c:
        from ._validators import validate_encryption_scope_client_params, \
            add_progress_callback_v2
        from .sdkutil import get_blob_types

        t_blob_content_settings = self.get_sdk(
            '_models#ContentSettings', resource_type=CUSTOM_DATA_STORAGE_BLOB)

        c.register_blob_arguments()
        c.register_precondition_options()
        c.register_content_settings_argument(t_blob_content_settings,
                                             update=False)

        c.argument('file_path',
                   options_list=('--file', '-f'),
                   type=file_type,
                   completer=FilesCompleter(),
                   help='Path of the file to upload as the blob content.')
        c.argument(
            'overwrite',
            arg_type=get_three_state_flag(),
            help=
            'Whether the blob to be uploaded should overwrite the current data. If True, upload_blob will '
            'overwrite the existing data. If set to False, the operation will fail with ResourceExistsError. '
            'The exception to the above is with Append blob types: if set to False and the data already exists, '
            'an error will not be raised and the data will be appended to the existing blob. If set '
            'overwrite=True, then the existing append blob will be deleted, and a new one created. '
            'Defaults to False.',
            is_preview=True)
        c.argument(
            'max_connections',
            type=int,
            help=
            'Maximum number of parallel connections to use when the blob size exceeds 64MB.'
        )
        c.extra('maxsize_condition',
                type=int,
                help='The max length in bytes permitted for the append blob.')
        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,
                validator=add_progress_callback_v2)
        c.argument(
            'socket_timeout',
            deprecate_info=c.deprecate(hide=True),
            help=
            'The socket timeout(secs), used by the service to regulate data flow.'
        )
        c.extra('tier', tier_type, validator=blob_tier_validator)
        c.argument(
            'encryption_scope',
            validator=validate_encryption_scope_client_params,
            help=
            'A predefined encryption scope used to encrypt the data on the service.'
        )
        c.argument('lease_id',
                   help='Required if the blob has an active lease.')
        c.extra('tags', arg_type=tags_type)

    with self.argument_context('storage container') as c:
        c.argument('container_name',
                   container_name_type,
                   options_list=('--name', '-n'))

    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(
            '_models#ContainerSasPermissions',
            resource_type=CUSTOM_DATA_STORAGE_BLOB)
        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))
        c.argument(
            'cache_control',
            help=
            'Response header value for Cache-Control when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'content_disposition',
            help=
            'Response header value for Content-Disposition when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'content_encoding',
            help=
            'Response header value for Content-Encoding when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'content_language',
            help=
            'Response header value for Content-Language when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'content_type',
            help=
            'Response header value for Content-Type when resource is accessed'
            'using this shared access signature.')
        c.argument(
            'as_user',
            min_api='2018-11-09',
            action='store_true',
            validator=as_user_validator,
            help=
            "Indicates that this command return the SAS signed with the user delegation key. "
            "The expiry parameter and '--auth-mode login' are required if this argument is specified. "
        )
        c.ignore('sas_token')
        c.argument(
            'full_uri',
            action='store_true',
            is_preview=True,
            help=
            'Indicate that this command return the full blob URI and the shared access signature token.'
        )

    with self.argument_context('storage container list') as c:
        c.extra('timeout', timeout_type)
        c.argument('marker', arg_type=marker_type)
        c.argument('num_results', arg_type=num_results_type)
        c.argument(
            'prefix',
            help=
            'Filter the results to return only blobs whose name begins with the specified prefix.'
        )
        c.argument(
            'include_metadata',
            arg_type=get_three_state_flag(),
            help=
            'Specify that container metadata to be returned in the response.')
        c.argument('show_next_marker',
                   action='store_true',
                   is_preview=True,
                   help='Show nextMarker in result when specified.')
        c.argument(
            'include_deleted',
            arg_type=get_three_state_flag(),
            min_api='2020-02-10',
            help=
            'Specify that deleted containers to be returned in the response. This is for container restore '
            'enabled account. The default value is `False`')

    with self.argument_context('storage container restore') as c:
        c.argument(
            'deleted_container_name',
            options_list=['--name', '-n'],
            help='Specify the name of the deleted container to restore.')
        c.argument(
            'deleted_container_version',
            options_list=['--deleted-version'],
            help='Specify the version of the deleted container to restore.')
        c.argument(
            'new_name',
            help='The new name for the deleted container to be restored to.')
        c.extra('timeout', timeout_type)
コード例 #55
0
ファイル: _params.py プロジェクト: jiayexie/azure-cli
def load_arguments(self, _):    # pylint: disable=too-many-statements

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    for scope in ['mysql server configuration', 'postgres server configuration']:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('configuration_name', id_part='child_name_1', options_list=['--name', '-n'])
コード例 #56
0
def load_arguments(self, _):
    """
    Load CLI Args for Knack parser
    """
    with self.argument_context('iot') as context:
        context.argument(
            'login',
            options_list=['--login', '-l'],
            validator=mode2_iot_login_handler,
            help=
            'This command supports an entity connection string with rights to perform action. '
            'Use to avoid session login via "az login". '
            'If both an entity connection string and name are provided the connection string takes priority.'
        )
        context.argument('resource_group_name',
                         arg_type=resource_group_name_type)
        context.argument('hub_name',
                         options_list=['--hub-name', '-n'],
                         arg_type=hub_name_type)
        context.argument('device_id',
                         options_list=['--device-id', '-d'],
                         help='Target Device.')
        context.argument('module_id',
                         options_list=['--module-id', '-m'],
                         help='Target Module.')
        context.argument('key_type',
                         options_list=['--key-type', '--kt'],
                         arg_type=get_enum_type(KeyType),
                         help='Shared access policy key type for auth.')
        context.argument('policy_name',
                         options_list=['--policy-name', '--pn'],
                         help='Shared access policy to use for auth.')
        context.argument('duration',
                         options_list=['--duration', '--du'],
                         type=int,
                         help='Valid token duration in seconds.')
        context.argument('etag',
                         options_list=['--etag', '-e'],
                         help='Entity tag value.')
        context.argument(
            'top',
            type=int,
            options_list=['--top'],
            help='Maximum number of elements to return. Use -1 for unlimited.')
        context.argument('method_name',
                         options_list=['--method-name', '--mn'],
                         help='Target method for invocation.')
        context.argument(
            'method_payload',
            options_list=['--method-payload', '--mp'],
            help=
            'Json payload to be passed to method. Must be file path or raw json.'
        )
        context.argument(
            'timeout',
            options_list=['--timeout', '--to'],
            type=int,
            help='Maximum number of seconds to wait for method result.')
        context.argument(
            'auth_method',
            options_list=['--auth-method', '--am'],
            arg_type=get_enum_type(DeviceAuthType),
            help='The authorization type an entity is to be created with.')
        context.argument(
            'metric_type',
            options_list=['--metric-type', '--mt'],
            arg_type=get_enum_type(MetricType),
            help=
            'Indicates which metric collection should be used to lookup a metric.'
        )
        context.argument('metric_id',
                         options_list=['--metric-id', '-m'],
                         help='Target metric for evaluation.')
        context.argument(
            'yes',
            options_list=['--yes', '-y'],
            arg_type=get_three_state_flag(),
            help=
            'Skip user prompts. Indicates acceptance of dependency installation (if required). '
            'Used primarily for automation scenarios. Default: false')
        context.argument(
            'repair',
            options_list=['--repair', '-r'],
            arg_type=get_three_state_flag(),
            help=
            'Reinstall uamqp dependency compatible with extension version. Default: false'
        )

    with self.argument_context('iot hub') as context:
        context.argument(
            'target_json',
            options_list=['--json', '-j'],
            help=
            'Json to replace existing twin with. Provide file path or raw json.'
        )
        context.argument(
            'policy_name',
            options_list=['--policy-name', '--pn'],
            help=
            'Shared access policy with operation permissions for target IoT Hub entity.'
        )
        context.argument(
            'primary_thumbprint',
            arg_group='X.509',
            options_list=['--primary-thumbprint', '--ptp'],
            help=
            'Explicit self-signed certificate thumbprint to use for primary key.'
        )
        context.argument('secondary_thumbprint',
                         arg_group='X.509',
                         options_list=['--secondary-thumbprint', '--stp'],
                         help='Explicit self-signed certificate thumbprint to '
                         'use for secondary key.')
        context.argument(
            'valid_days',
            arg_group='X.509',
            options_list=['--valid-days', '--vd'],
            type=int,
            help='Generate self-signed cert and use its thumbprint. Valid '
            'for specified number of days. Default: 365.')
        context.argument(
            'output_dir',
            arg_group='X.509',
            options_list=['--output-dir', '--od'],
            help='Generate self-signed cert and use its thumbprint. '
            'Output to specified target directory')

    with self.argument_context('iot hub monitor-events') as context:
        context.argument(
            'timeout',
            options_list=['--timeout', '--to', '-t'],
            type=int,
            help=
            'Maximum seconds to maintain connection without receiving message. Use 0 for infinity. '
        )
        context.argument(
            'consumer_group',
            options_list=['--consumer-group', '--cg', '-c'],
            help=
            'Specify the consumer group to use when connecting to event hub endpoint.'
        )
        context.argument(
            'enqueued_time',
            options_list=['--enqueued-time', '--et', '-e'],
            type=int,
            help=
            'Indicates the time that should be used as a starting point to read messages from the partitions. '
            'Units are milliseconds since unix epoch. '
            'If no time is indicated "now" is used.')
        context.argument('properties',
                         options_list=['--properties', '--props', '-p'],
                         arg_type=event_msg_prop_type)

    with self.argument_context('iot hub monitor-feedback') as context:
        context.argument(
            'wait_on_id',
            options_list=['--wait-on-msg', '-w'],
            help=
            'Feedback monitor will block until a message with specific id (uuid) is received.'
        )

    with self.argument_context('iot hub device-identity') as context:
        context.argument('edge_enabled',
                         options_list=['--edge-enabled', '--ee'],
                         arg_type=get_three_state_flag(),
                         help='Flag indicating edge enablement.')
        context.argument('status',
                         options_list=['--status', '--sta'],
                         arg_type=get_enum_type(EntityStatusType),
                         help='Set device status upon creation.')
        context.argument('status_reason',
                         options_list=['--status-reason', '--star'],
                         help='Description for device status.')

    with self.argument_context('iot hub device-identity export') as context:
        context.argument(
            'blob_container_uri',
            options_list=['--blob-container-uri', '--bcu'],
            help='Blob Shared Access Signature URI with write access to '
            'a blob container. This is used to output the status of the '
            'job and the results.')
        context.argument(
            'include_keys',
            options_list=['--include-keys', '--ik'],
            arg_type=get_three_state_flag(),
            help='If set, keys are exported normally. Otherwise, keys are '
            'set to null in export output.')

    with self.argument_context('iot hub device-identity import') as context:
        context.argument(
            'input_blob_container_uri',
            options_list=['--input-blob-container-uri', '--ibcu'],
            help='Blob Shared Access Signature URI with read access to a blob '
            'container. This blob contains the operations to be performed on '
            'the identity registry ')
        context.argument(
            'output_blob_container_uri',
            options_list=['--output-blob-container-uri', '--obcu'],
            help='Blob Shared Access Signature URI with write access '
            'to a blob container. This is used to output the status of '
            'the job and the results.')

    with self.argument_context('iot hub query') as context:
        context.argument('query_command',
                         options_list=['--query-command', '-q'],
                         help='User query to be executed.')
        context.argument(
            'top',
            options_list=['--top'],
            type=int,
            help=
            'Maximum number of elements to return. By default query has no cap.'
        )

    with self.argument_context('iot device') as context:
        context.argument('data',
                         options_list=['--data', '--da'],
                         help='Message body.')
        context.argument(
            'properties',
            options_list=['--properties', '--props'],
            help='Message property bag in key-value pairs with the '
            'following format: a=b;c=d')
        context.argument('msg_count',
                         options_list=['--msg-count', '--mc'],
                         type=int,
                         help='Number of device messages to send to IoT Hub.')
        context.argument(
            'msg_interval',
            options_list=['--msg-interval', '--mi'],
            type=int,
            help='Delay in seconds between device-to-cloud messages.')
        context.argument(
            'receive_settle',
            options_list=['--receive-settle', '--rs'],
            arg_type=get_enum_type(SettleType),
            help='Indicates how to settle received cloud-to-device messages. '
            'Supported with HTTP only.')
        context.argument('protocol_type',
                         options_list=['--protocol', '--proto'],
                         arg_type=get_enum_type(ProtocolType),
                         help='Indicates device-to-cloud message protocol')

    with self.argument_context('iot device c2d-message') as context:
        context.argument(
            'ack',
            options_list=['--ack'],
            arg_type=get_enum_type(AckType),
            help=
            'Request the delivery of per-message feedback regarding the final state of that message. '
            'The description of ack values is as follows. '
            'Positive: If the c2d message reaches the Completed state, IoT Hub generates a feedback message. '
            'Negative: If the c2d message reaches the Dead lettered state, IoT Hub generates a feedback message. '
            'Full: IoT Hub generates a feedback message in either case. '
            'By default, no ack is requested.')
        context.argument('correlation_id',
                         options_list=['--correlation-id', '--cid'],
                         help='Correlation Id associated with message.')
        context.argument(
            'lock_timeout',
            options_list=['--lock-timeout', '--lt'],
            type=int,
            help=
            'Specifies the amount of time a message will be invisible to other receive calls.'
        )

    with self.argument_context('iot device c2d-message send') as context:
        context.argument(
            'wait_on_feedback',
            options_list=['--wait', '-w'],
            arg_type=get_three_state_flag(),
            help=
            'If set the c2d send operation will block until device feedback has been received.'
        )

    with self.argument_context('iot device upload-file') as context:
        context.argument('file_path',
                         options_list=['--file-path', '--fp'],
                         help='Path to file for upload.')
        context.argument('content_type',
                         options_list=['--content-type', '--ct'],
                         help='MIME Type of file.')

    # Remove after deprecation
    with self.argument_context('iot hub apply-configuration') as context:
        context.argument(
            'content',
            options_list=['--content', '-k'],
            help='Configuration content. Provide file path or raw json.')

    with self.argument_context('iot hub configuration') as context:
        context.argument('config_id',
                         options_list=['--config-id', '-c'],
                         help='Target device configuration.')
        context.argument(
            'target_condition',
            options_list=['--target-condition', '--tc', '-t'],
            help='Target condition in which a device configuration applies to.'
        )
        context.argument(
            'priority',
            options_list=['--priority', '--pri'],
            help=
            'Weight of the device configuration in case of competing rules (highest wins).'
        )
        context.argument(
            'content',
            options_list=['--content', '-k'],
            help='Device configuration content. Provide file path or raw json.'
        )
        context.argument(
            'metrics',
            options_list=['--metrics', '-m'],
            help=
            'Device configuration metric definitions. Provide file path or raw json.'
        )
        context.argument(
            'labels',
            options_list=['--labels', '--lab'],
            help="Map of labels to be applied to target configuration. "
            "Format example: {\"key0\":\"value0\", \"key1\":\"value1\"}")
        context.argument('top',
                         options_list=['--top'],
                         type=int,
                         help='Maximum number of configurations to return.')

    with self.argument_context('iot edge') as context:
        context.argument(
            'config_id',
            options_list=['--deployment-id', '-d', '--config-id', '-c'],
            help=
            'Target deployment. --config-id/-c is deprecated for deployments. Use --deployment-id/-d instead.'
        )
        context.argument(
            'target_condition',
            options_list=['--target-condition', '--tc', '-t'],
            help='Target condition in which an Edge deployment applies to.')
        context.argument(
            'priority',
            options_list=['--priority', '--pri'],
            help=
            'Weight of deployment in case of competing rules (highest wins).')
        context.argument(
            'content',
            options_list=['--content', '-k'],
            help='IoT Edge deployment content. Provide file path or raw json.')
        context.argument(
            'metrics',
            options_list=['--metrics', '-m'],
            help=
            'IoT Edge deployment metric definitions. Provide file path or raw json.'
        )
        context.argument(
            'labels',
            options_list=['--labels', '--lab'],
            help="Map of labels to be applied to target deployment. "
            "Use the following format: '{\"key0\":\"value0\", \"key1\":\"value1\"}'"
        )
        context.argument('top',
                         options_list=['--top'],
                         type=int,
                         help='Maximum number of deployments to return.')

    with self.argument_context('iot dps') as context:
        context.argument(
            'dps_name',
            help='Name of the Azure IoT Hub device provisioning service')
        context.argument('initial_twin_properties',
                         options_list=['--initial-twin-properties', '--props'],
                         help='Initial twin properties')
        context.argument('initial_twin_tags',
                         options_list=['--initial-twin-tags', '--tags'],
                         help='Initial twin tags')
        context.argument('iot_hub_host_name',
                         options_list=['--iot-hub-host-name', '--hn'],
                         help='Host name of target IoT Hub')
        context.argument('provisioning_status',
                         options_list=['--provisioning-status', '--ps'],
                         arg_type=get_enum_type(EntityStatusType),
                         help='Enable or disable enrollment entry')
        context.argument(
            'certificate_path',
            options_list=['--certificate-path', '--cp'],
            help='The path to the file containing the primary certificate.')
        context.argument(
            'secondary_certificate_path',
            options_list=['--secondary-certificate-path', '--scp'],
            help='The path to the file containing the secondary certificate')
        context.argument('remove_certificate',
                         options_list=['--remove-certificate', '--rc'],
                         help='Remove current primary certificate',
                         arg_type=get_three_state_flag())
        context.argument(
            'remove_secondary_certificate',
            options_list=['--remove-secondary-certificate', '--rsc'],
            help='Remove current secondary certificate',
            arg_type=get_three_state_flag())
        context.argument(
            'reprovision_policy',
            options_list=['--reprovision-policy', '--rp'],
            arg_type=get_enum_type(ReprovisionType),
            help=
            'Device data to be handled on re-provision to different Iot Hub.')
        context.argument(
            'allocation_policy',
            options_list=['--allocation-policy', '--ap'],
            arg_type=get_enum_type(AllocationType),
            help='Type of allocation for device assigned to the Hub.')
        context.argument(
            'iot_hubs',
            options_list=['--iot-hubs', '--ih'],
            help=
            'Host name of target IoT Hub. Use space-separated list for multiple IoT Hubs.'
        )

    with self.argument_context('iot dps enrollment') as context:
        context.argument('enrollment_id',
                         help='ID of device enrollment record')
        context.argument('device_id', help='IoT Hub Device ID')
        context.argument(
            'primary_key',
            options_list=['--primary-key', '--pk'],
            help=
            'The primary symmetric shared access key stored in base64 format. '
        )
        context.argument(
            'secondary_key',
            options_list=['--secondary-key', '--sk'],
            help=
            'The secondary symmetric shared access key stored in base64 format. '
        )

    with self.argument_context('iot dps enrollment create') as context:
        context.argument('attestation_type',
                         options_list=['--attestation-type', '--at'],
                         arg_type=get_enum_type(AttestationType),
                         help='Attestation Mechanism')
        context.argument(
            'certificate_path',
            options_list=['--certificate-path', '--cp'],
            help='The path to the file containing the primary certificate. '
            'When choosing x509 as attestation type, '
            'one of the certificate path is required.')
        context.argument(
            'secondary_certificate_path',
            options_list=['--secondary-certificate-path', '--scp'],
            help='The path to the file containing the secondary certificate. '
            'When choosing x509 as attestation type, '
            'one of the certificate path is required.')
        context.argument(
            'endorsement_key',
            options_list=['--endorsement-key', '--ek'],
            help='TPM endorsement key for a TPM device. '
            'When choosing tpm as attestation type, endorsement key is required.'
        )

    with self.argument_context('iot dps enrollment update') as context:
        context.argument('endorsement_key',
                         options_list=['--endorsement-key', '--ek'],
                         help='TPM endorsement key for a TPM device.')

    with self.argument_context('iot dps enrollment-group') as context:
        context.argument('enrollment_id', help='ID of enrollment group')
        context.argument(
            'primary_key',
            options_list=['--primary-key', '--pk'],
            help=
            'The primary symmetric shared access key stored in base64 format. '
        )
        context.argument(
            'secondary_key',
            options_list=['--secondary-key', '--sk'],
            help=
            'The secondary symmetric shared access key stored in base64 format. '
        )
        context.argument(
            'certificate_path',
            options_list=['--certificate-path', '--cp'],
            help='The path to the file containing the primary certificate. '
            'If attestation with an intermediate certificate is desired then a certificate path must be provided.'
        )
        context.argument(
            'secondary_certificate_path',
            options_list=['--secondary-certificate-path', '--scp'],
            help='The path to the file containing the secondary certificate. '
            'If attestation with an intermediate certificate is desired then a certificate path must be provided.'
        )
        context.argument(
            'root_ca_name',
            options_list=['--root-ca-name', '--ca-name', '--cn'],
            help='The name of the primary root CA certificate. '
            'If attestation with a root CA certificate is desired then a root ca name must be provided.'
        )
        context.argument(
            'secondary_root_ca_name',
            options_list=[
                '--secondary-root-ca-name', '--secondary-ca-name', '--scn'
            ],
            help='The name of the secondary root CA certificate. '
            'If attestation with a root CA certificate is desired then a root ca name must be provided.'
        )

    with self.argument_context('iot dps registration') as context:
        context.argument('registration_id', help='ID of device registration')

    with self.argument_context('iot dps registration list') as context:
        context.argument('enrollment_id', help='ID of enrollment group')
コード例 #57
0
ファイル: _params.py プロジェクト: derekbekoe/azure-cli
def load_arguments(self, _):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        restore_point_arg_group = 'Restore Point'

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

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

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

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

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

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

        search_arg_group = 'Search'

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

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

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

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

        c.ignore('type')

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

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

        auth_group = 'Authentication'

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        policy_arg_group = 'Policy'

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

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

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

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

        policy_arg_group = 'Policy'
        notification_arg_group = 'Notification'

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

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

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

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

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

        # TODO: use server default

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

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

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

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

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

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

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

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

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

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

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

        c.argument('elastic_pool_name',
                   options_list=['--name', '-n'],
                   help='The name of the elastic pool.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

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

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

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

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

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

        search_arg_group = 'Search'

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

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

    #####
    #           sql elastic-pool op
    #####
    with self.argument_context('sql elastic-pool op') as c:
        c.argument('elastic_pool_name',
                   options_list=['--elastic-pool'],
                   help='Name of the Azure SQL Elastic Pool.')

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

    ###############################################
    #                sql server                   #
    ###############################################
    with self.argument_context('sql server') as c:
        c.argument('server_name', options_list=['--name', '-n'],
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')
        c.argument('administrator_login', options_list=['--admin-user', '-u'])
        c.argument('administrator_login_password', options_list=['--admin-password', '-p'])

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

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

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

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

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

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

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

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

    #####
    #           sql server dns-alias
    #####
    with self.argument_context('sql server dns-alias') as c:
        c.argument('server_name', arg_type=server_param_type)
        c.argument('dns_alias_name', options_list=('--name', '-n'))
        c.argument('original_server_name', options_list=('--original-server'),
                   help='The name of the server to which alias is currently pointing')
        c.argument('original_resource_group_name', options_list=('--original-resource-group'))
        c.argument('original_subscription_id', options_list=('--original-subscription-id'))

    #####
    #           sql server firewall-rule
    #####
    with self.argument_context('sql server firewall-rule') as c:
        # Help text needs to be specified because 'sql server firewall-rule update' is a custom
        # command.
        c.argument('server_name',
                   arg_type=server_param_type,
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')

        c.argument('firewall_rule_name',
                   options_list=['--name', '-n'],
                   help='The name of the firewall rule.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

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

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

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

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

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

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

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

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

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

    with self.argument_context('sql server vnet-rule create') as c:
        c.extra('vnet_name', options_list=['--vnet-name'], help='The virtual network name')
コード例 #58
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'))
    large_file_share_type = CLIArgumentType(
        action='store_true', min_api='2019-04-01',
        help='Enable the capability to support large file shares with more than 5 TiB capacity for storage account.'
             'Once the property is enabled, the feature cannot be disabled. Currently only supported for LRS and '
             'ZRS replication types, hence account conversions to geo-redundant accounts would not be possible. '
             'For more information, please refer to https://go.microsoft.com/fwlink/?linkid=2086047.')
    adds_type = CLIArgumentType(arg_type=get_three_state_flag(), min_api='2019-04-01',
                                arg_group='Azure Files Identity Based Authentication',
                                help='Enable Azure Files Active Directory Domain Service Authentication for '
                                     'storage account. When --enable-files-adds is set to true, Azure Active '
                                     'Directory Properties arguments must be provided.')
    aadds_type = CLIArgumentType(arg_type=get_three_state_flag(), min_api='2018-11-01',
                                 arg_group='Azure Files Identity Based Authentication',
                                 help='Enable Azure Active Directory Domain Services authentication for Azure Files')
    domain_name_type = CLIArgumentType(min_api='2019-04-01', arg_group="Azure Active Directory Properties",
                                       help="Specify the primary domain that the AD DNS server is authoritative for. "
                                            "Required when --enable-files-adds is set to True")
    net_bios_domain_name_type = CLIArgumentType(min_api='2019-04-01', arg_group="Azure Active Directory Properties",
                                                help="Specify the NetBIOS domain name. "
                                                     "Required when --enable-files-adds is set to True")
    forest_name_type = CLIArgumentType(min_api='2019-04-01', arg_group="Azure Active Directory Properties",
                                       help="Specify the Active Directory forest to get. "
                                            "Required when --enable-files-adds is set to True")
    domain_guid_type = CLIArgumentType(min_api='2019-04-01', arg_group="Azure Active Directory Properties",
                                       help="Specify the domain GUID. Required when --enable-files-adds is set to True")
    domain_sid_type = CLIArgumentType(min_api='2019-04-01', arg_group="Azure Active Directory Properties",
                                      help="Specify the security identifier (SID). Required when --enable-files-adds "
                                           "is set to True")
    azure_storage_sid_type = CLIArgumentType(min_api='2019-04-01', arg_group="Azure Active Directory Properties",
                                             help="Specify the security identifier (SID) for Azure Storage. "
                                                  "Required when --enable-files-adds is set to True")
    sam_account_name_type = CLIArgumentType(min_api='2021-08-01', arg_group="Azure Active Directory Properties",
                                            help="Specify the Active Directory SAMAccountName for Azure Storage.",
                                            is_preview=True)
    t_account_type = self.get_models('ActiveDirectoryPropertiesAccountType', resource_type=CUSTOM_MGMT_STORAGE)
    account_type_type = CLIArgumentType(min_api='2021-08-01', arg_group="Azure Active Directory Properties",
                                        arg_type=get_enum_type(t_account_type), is_preview=True,
                                        help="Specify the Active Directory account type for Azure Storage.")
    t_routing_choice = self.get_models('RoutingChoice', resource_type=CUSTOM_MGMT_STORAGE)
    routing_choice_type = CLIArgumentType(
        arg_group='Routing Preference', arg_type=get_enum_type(t_routing_choice),
        help='Routing Choice defines the kind of network routing opted by the user.',
        min_api='2019-06-01')
    publish_microsoft_endpoints_type = CLIArgumentType(
        arg_group='Routing Preference', arg_type=get_three_state_flag(), min_api='2019-06-01',
        help='A boolean flag which indicates whether microsoft routing storage endpoints are to be published.')
    publish_internet_endpoints_type = CLIArgumentType(
        arg_group='Routing Preference', arg_type=get_three_state_flag(), min_api='2019-06-01',
        help='A boolean flag which indicates whether internet routing storage endpoints are to be published.')
    allow_shared_key_access_type = CLIArgumentType(
        arg_type=get_three_state_flag(), options_list=['--allow-shared-key-access', '-k'], min_api='2019-04-01',
        help='Indicate whether the storage account permits requests to be authorized with the account access key via '
             'Shared Key. If false, then all requests, including shared access signatures, must be authorized with '
             'Azure Active Directory (Azure AD). The default value is null, which is equivalent to true.')
    sas_expiration_period_type = CLIArgumentType(
        options_list=['--sas-expiration-period', '--sas-exp'], min_api='2021-02-01',
        help='Expiration period of the SAS Policy assigned to the storage account, DD.HH:MM:SS.'
    )
    key_expiration_period_in_days_type = CLIArgumentType(
        options_list=['--key-expiration-period-in-days', '--key-exp-days'], min_api='2021-02-01', type=int,
        help='Expiration period in days of the Key Policy assigned to the storage account'
    )
    allow_cross_tenant_replication_type = CLIArgumentType(
        arg_type=get_three_state_flag(), options_list=['--allow-cross-tenant-replication', '-r'], min_api='2021-04-01',
        help='Allow or disallow cross AAD tenant object replication. The default interpretation is true for this '
        'property.')
    t_share_permission = self.get_models('DefaultSharePermission', resource_type=CUSTOM_MGMT_STORAGE)
    default_share_permission_type = CLIArgumentType(
        options_list=['--default-share-permission', '-d'],
        arg_type=get_enum_type(t_share_permission),
        min_api='2020-08-01-preview',
        arg_group='Azure Files Identity Based Authentication',
        help='Default share permission for users using Kerberos authentication if RBAC role is not assigned.')
    action_type = CLIArgumentType(
        help='The action of virtual network rule. Possible value is Allow.'
    )
    immutability_period_since_creation_in_days_type = CLIArgumentType(
        options_list=['--immutability-period-in-days', '--immutability-period'], min_api='2021-06-01',
        help='The immutability period for the blobs in the container since the policy creation, in days.'
    )
    account_immutability_policy_state_enum = self.get_sdk(
        'models._storage_management_client_enums#AccountImmutabilityPolicyState',
        resource_type=CUSTOM_MGMT_STORAGE)
    immutability_policy_state_type = CLIArgumentType(
        arg_type=get_enum_type(account_immutability_policy_state_enum),
        options_list='--immutability-state', min_api='2021-06-01',
        help='Defines the mode of the policy. Disabled state disables the policy, '
        'Unlocked state allows increase and decrease of immutability retention time '
        'and also allows toggling allow-protected-append-write property, '
        'Locked state only allows the increase of the immutability retention time. '
        'A policy can only be created in a Disabled or Unlocked state and can be toggled between the '
        'two states. Only a policy in an Unlocked state can transition to a Locked state which cannot '
        'be reverted.')
    public_network_access_enum = self.get_sdk('models._storage_management_client_enums#PublicNetworkAccess',
                                              resource_type=CUSTOM_MGMT_STORAGE)
    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)
    timeout_type = CLIArgumentType(
        help='Request timeout in seconds. Applies to each call to the service.', type=int
    )

    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 create', resource_type=CUSTOM_MGMT_STORAGE) as c:
        t_account_type, t_sku_name, t_kind, t_tls_version = \
            self.get_models('AccountType', 'SkuName', 'Kind', 'MinimumTlsVersion',
                            resource_type=CUSTOM_MGMT_STORAGE)
        t_identity_type = self.get_models('IdentityType', 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,
                   local_context_attribute=LocalContextAttribute(
                       name='storage_account_name', actions=[LocalContextAction.SET], scopes=[ALL]))
        c.argument('kind', help='Indicate the type of storage account.',
                   arg_type=get_enum_type(t_kind),
                   default='StorageV2' if self.cli_ctx.cloud.profile == 'latest' else 'Storage')
        c.argument('https_only', arg_type=get_three_state_flag(), min_api='2019-04-01',
                   help='Allow https traffic only to storage service if set to true. The default value is true.')
        c.argument('https_only', arg_type=get_three_state_flag(), max_api='2018-11-01',
                   help='Allow https traffic only to storage service if set to true. The default value is false.')
        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'))
        c.argument('enable_sftp', arg_type=get_three_state_flag(), min_api='2021-08-01',
                   is_preview=True, help='Enable Secure File Transfer Protocol.')
        c.argument('enable_local_user', arg_type=get_three_state_flag(), min_api='2021-08-01',
                   is_preview=True, help='Enable local user features.')
        c.argument('enable_files_aadds', aadds_type)
        c.argument('enable_files_adds', adds_type)
        c.argument('enable_large_file_share', arg_type=large_file_share_type)
        c.argument('domain_name', domain_name_type)
        c.argument('net_bios_domain_name', net_bios_domain_name_type)
        c.argument('forest_name', forest_name_type)
        c.argument('domain_guid', domain_guid_type)
        c.argument('domain_sid', domain_sid_type)
        c.argument('azure_storage_sid', azure_storage_sid_type)
        c.argument('sam_account_name', sam_account_name_type)
        c.argument('account_type', account_type_type)
        c.argument('enable_hierarchical_namespace', arg_type=get_three_state_flag(),
                   options_list=['--enable-hierarchical-namespace', '--hns',
                                 c.deprecate(target='--hierarchical-namespace', redirect='--hns', hide=True)],
                   help=" Allow the blob service to exhibit filesystem semantics. This property can be enabled only "
                   "when storage account kind is StorageV2.",
                   min_api='2018-02-01')
        c.argument('encryption_key_type_for_table', arg_type=get_enum_type(['Account', 'Service']),
                   help='Set the encryption key type for Table service. "Account": Table will be encrypted '
                        'with account-scoped encryption key. "Service": Table will always be encrypted with '
                        'service-scoped keys. Currently the default encryption key type is "Service".',
                   min_api='2019-06-01', options_list=['--encryption-key-type-for-table', '-t'])
        c.argument('encryption_key_type_for_queue', arg_type=get_enum_type(['Account', 'Service']),
                   help='Set the encryption key type for Queue service. "Account": Queue will be encrypted '
                        'with account-scoped encryption key. "Service": Queue will always be encrypted with '
                        'service-scoped keys. Currently the default encryption key type is "Service".',
                   min_api='2019-06-01', options_list=['--encryption-key-type-for-queue', '-q'])
        c.argument('routing_choice', routing_choice_type)
        c.argument('publish_microsoft_endpoints', publish_microsoft_endpoints_type)
        c.argument('publish_internet_endpoints', publish_internet_endpoints_type)
        c.argument('require_infrastructure_encryption', options_list=['--require-infrastructure-encryption', '-i'],
                   arg_type=get_three_state_flag(),
                   help='A boolean indicating whether or not the service applies a secondary layer of encryption with '
                   'platform managed keys for data at rest.')
        c.argument('allow_blob_public_access', arg_type=get_three_state_flag(), min_api='2019-04-01',
                   help='Allow or disallow public access to all blobs or containers in the storage account. '
                   'The default value for this property is null, which is equivalent to true. When true, containers '
                   'in the account may be configured for public access. Note that setting this property to true does '
                   'not enable anonymous access to any data in the account. The additional step of configuring the '
                   'public access setting for a container is required to enable anonymous access.')
        c.argument('min_tls_version', arg_type=get_enum_type(t_tls_version),
                   help='The minimum TLS version to be permitted on requests to storage. '
                        'The default interpretation is TLS 1.0 for this property')
        c.argument('allow_shared_key_access', allow_shared_key_access_type)
        c.argument('edge_zone', edge_zone_type, min_api='2020-08-01-preview')
        c.argument('identity_type', arg_type=get_enum_type(t_identity_type), arg_group='Identity',
                   help='The identity type.')
        c.argument('user_identity_id', arg_group='Identity',
                   help='The key is the ARM resource identifier of the identity. Only 1 User Assigned identity is '
                   'permitted here.')
        c.argument('key_expiration_period_in_days', key_expiration_period_in_days_type, is_preview=True)
        c.argument('sas_expiration_period', sas_expiration_period_type, is_preview=True)
        c.argument('allow_cross_tenant_replication', allow_cross_tenant_replication_type)
        c.argument('default_share_permission', default_share_permission_type)
        c.argument('enable_nfs_v3', arg_type=get_three_state_flag(), is_preview=True, min_api='2021-01-01',
                   help='NFS 3.0 protocol support enabled if sets to true.')
        c.argument('enable_alw', arg_type=get_three_state_flag(), min_api='2021-06-01',
                   help='The account level immutability property. The property is immutable and can only be set to true'
                        ' at the account creation time. When set to true, it enables object level immutability for all '
                        'the containers in the account by default.',
                   arg_group='Account Level Immutability',
                   validator=validate_immutability_arguments)
        c.argument('immutability_period_since_creation_in_days',
                   arg_type=immutability_period_since_creation_in_days_type,
                   arg_group='Account Level Immutability',
                   validator=validate_immutability_arguments)
        c.argument('immutability_policy_state', arg_type=immutability_policy_state_type,
                   arg_group='Account Level Immutability',
                   validator=validate_immutability_arguments)
        c.argument('allow_protected_append_writes', arg_type=get_three_state_flag(),
                   options_list=['--allow-protected-append-writes', '--allow-append', '-w'],
                   min_api='2021-06-01',
                   help='This property can only be changed for disabled and unlocked time-based retention policies. '
                        'When enabled, new blocks can be written to an append blob while maintaining immutability '
                        'protection and compliance. Only new blocks can be added and any existing blocks cannot be '
                        'modified or deleted.',
                   arg_group='Account Level Immutability',
                   validator=validate_immutability_arguments)
        c.argument('public_network_access', arg_type=get_enum_type(public_network_access_enum), min_api='2021-06-01',
                   help='Enable or disable public network access to the storage account. '
                        'Possible values include: `Enabled` or `Disabled`.')

    with self.argument_context('storage account update', resource_type=CUSTOM_MGMT_STORAGE) as c:
        t_tls_version = self.get_models('MinimumTlsVersion', resource_type=CUSTOM_MGMT_STORAGE)
        t_identity_type = self.get_models('IdentityType', resource_type=CUSTOM_MGMT_STORAGE)
        c.register_common_storage_account_options()
        c.argument('sku', arg_type=get_enum_type(t_sku_name),
                   help='Note that the SKU name cannot be updated to Standard_ZRS, Premium_LRS or Premium_ZRS, '
                   'nor can accounts of those SKU names be updated to any other value')
        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)
        c.argument('enable_sftp', arg_type=get_three_state_flag(), min_api='2021-08-01',
                   is_preview=True, help='Enable Secure File Transfer Protocol.')
        c.argument('enable_local_user', arg_type=get_three_state_flag(), min_api='2021-08-01',
                   is_preview=True, help='Enable local user features.')
        c.argument('enable_files_aadds', aadds_type)
        c.argument('enable_files_adds', adds_type)
        c.argument('enable_large_file_share', arg_type=large_file_share_type)
        c.argument('domain_name', domain_name_type)
        c.argument('net_bios_domain_name', net_bios_domain_name_type)
        c.argument('forest_name', forest_name_type)
        c.argument('domain_guid', domain_guid_type)
        c.argument('domain_sid', domain_sid_type)
        c.argument('azure_storage_sid', azure_storage_sid_type)
        c.argument('sam_account_name', sam_account_name_type)
        c.argument('account_type', account_type_type)
        c.argument('routing_choice', routing_choice_type)
        c.argument('publish_microsoft_endpoints', publish_microsoft_endpoints_type)
        c.argument('publish_internet_endpoints', publish_internet_endpoints_type)
        c.argument('allow_blob_public_access', arg_type=get_three_state_flag(), min_api='2019-04-01',
                   help='Allow or disallow public access to all blobs or containers in the storage account. '
                   'The default value for this property is null, which is equivalent to true. When true, containers '
                   'in the account may be configured for public access. Note that setting this property to true does '
                   'not enable anonymous access to any data in the account. The additional step of configuring the '
                   'public access setting for a container is required to enable anonymous access.')
        c.argument('min_tls_version', arg_type=get_enum_type(t_tls_version),
                   help='The minimum TLS version to be permitted on requests to storage. '
                        'The default interpretation is TLS 1.0 for this property')
        c.argument('allow_shared_key_access', allow_shared_key_access_type)
        c.argument('identity_type', arg_type=get_enum_type(t_identity_type), arg_group='Identity',
                   help='The identity type.')
        c.argument('user_identity_id', arg_group='Identity',
                   help='The key is the ARM resource identifier of the identity. Only 1 User Assigned identity is '
                   'permitted here.')
        c.argument('key_expiration_period_in_days', key_expiration_period_in_days_type, is_preview=True)
        c.argument('sas_expiration_period', sas_expiration_period_type, is_preview=True)
        c.argument('allow_cross_tenant_replication', allow_cross_tenant_replication_type)
        c.argument('default_share_permission', default_share_permission_type)
        c.argument('immutability_period_since_creation_in_days',
                   arg_type=immutability_period_since_creation_in_days_type,
                   arg_group='Account Level Immutability')
        c.argument('immutability_policy_state', arg_type=immutability_policy_state_type,
                   arg_group='Account Level Immutability')
        c.argument('allow_protected_append_writes', arg_type=get_three_state_flag(),
                   options_list=['--allow-protected-append-writes', '--allow-append', '-w'],
                   min_api='2021-06-01',
                   help='This property can only be changed for disabled and unlocked time-based retention policies. '
                        'When enabled, new blocks can be written to an append blob while maintaining immutability '
                        'protection and compliance. Only new blocks can be added and any existing blocks cannot be '
                        'modified or deleted.',
                   arg_group='Account Level Immutability')
        c.argument('public_network_access', arg_type=get_enum_type(public_network_access_enum), min_api='2021-06-01',
                   help='Enable or disable public network access to the storage account. '
                        'Possible values include: `Enabled` or `Disabled`.')

    for scope in ['storage account create', 'storage account update']:
        with self.argument_context(scope, arg_group='Customer managed key', min_api='2017-06-01',
                                   resource_type=CUSTOM_MGMT_STORAGE) as c:
            t_key_source = self.get_models('KeySource', resource_type=CUSTOM_MGMT_STORAGE)
            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 to use, which will opt out of implicit key rotation. '
                       'Please use "" to opt in key auto-rotation again.')
            c.argument('encryption_key_source',
                       arg_type=get_enum_type(t_key_source),
                       help='The default encryption key source',
                       validator=validate_encryption_source)
            c.argument('key_vault_user_identity_id', options_list=['--key-vault-user-identity-id', '-u'],
                       min_api='2021-01-01',
                       help='Resource identifier of the UserAssigned identity to be associated with server-side '
                            'encryption on the storage account.')

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

    for item in ['update', 'network-rule']:
        with self.argument_context('storage account {}'.format(item)) as c:
            c.argument('account_name', acct_name_type, options_list=['--name', '-n'])
            c.argument('resource_group_name', required=False, validator=process_resource_group)

    with self.argument_context('storage account network-rule') as c:
        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 account local-user') as c:
        c.argument('account_name', acct_name_type, options_list='--account-name', id_part=None)
        c.argument('username', options_list=['--username', '--name', '-n'],
                   help='The name of local user. The username must contain lowercase letters and numbers '
                        'only. It must be unique only within the storage account.')

    for item in ['create', 'update']:
        with self.argument_context(f'storage account local-user {item}') as c:
            c.argument('permission_scope', nargs='+', action=PermissionScopeAddAction,
                       help='The permission scope argument list which includes the permissions, service, and resource_name.'
                            'The permissions can be a combination of the below possible values: '
                            'Read(r), Write (w), Delete (d), List (l), and Create (c). '
                            'The service has possible values: blob, file. '
                            'The resource-name is the container name or the file share name. '
                            'Example: --permission-scope permissions=r service=blob resource-name=container1'
                            'Can specify multiple permission scopes: '
                            '--permission-scope permissions=rw service=blob resource-name=container1'
                            '--permission-scope permissions=rwd service=file resource-name=share2')
            c.argument('home_directory', help='The home directory.')
            c.argument('ssh_authorized_key', nargs='+', action=SshPublicKeyAddAction,
                       help='SSH authorized keys for SFTP. Includes an optional description and key. '
                            'The key is the base64 encoded SSH public key , with format: '
                            '<keyType> <keyData> e.g. ssh-rsa AAAABBBB.'
                            'Example: --ssh_authorized_key description=description key="ssh-ras AAAABBBB"'
                            'or --ssh_authorized_key key="ssh-ras AAAABBBB"')
            c.argument('has_shared_key', arg_type=get_three_state_flag(),
                       help='Indicates whether shared key exists. Set it to false to remove existing shared key.')
            c.argument('has_ssh_key', arg_type=get_three_state_flag(),
                       help='Indicates whether ssh key exists. Set it to false to remove existing SSH key.')
            c.argument('has_ssh_password', arg_type=get_three_state_flag(),
                       help='Indicates whether ssh password exists. Set it to false to remove existing SSH password.')

    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='Enable 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='Enable 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='Represent 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)

    with self.argument_context('storage fs service-properties update', resource_type=CUSTOM_DATA_STORAGE_FILEDATALAKE,
                               min_api='2020-06-12') as c:
        c.argument('delete_retention', arg_type=get_three_state_flag(), arg_group='Soft Delete',
                   help='Enable soft-delete.')
        c.argument('delete_retention_period', type=int, arg_group='Soft Delete',
                   options_list=['--delete-retention-period', '--period'],
                   help='Number of days that soft-deleted fs will be retained. Must be in range [1,365].')
        c.argument('enable_static_website', options_list=['--static-website'], arg_group='Static Website',
                   arg_type=get_three_state_flag(),
                   help='Enable static-website.')
        c.argument('index_document', help='Represent 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='Represent 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.')

    for item in ['list-deleted-path', 'undelete-path']:
        with self.argument_context('storage fs {}'.format(item)) as c:
            c.extra('file_system_name', options_list=['--file-system', '-f'],
                    help="File system name.", required=True)
            c.extra('timeout', timeout_type)

    with self.argument_context('storage fs list-deleted-path') as c:
        c.argument('path_prefix', help='Filter the results to return only paths under the specified path.')
        c.argument('num_results', type=int, help='Specify the maximum number to return.')
        c.argument('marker', help='A string value that identifies the portion of the list of containers to be '
                   'returned with the next listing operation. The operation returns the NextMarker value within '
                   'the response body if the listing operation did not return all containers remaining to be listed '
                   'with the current page. If specified, this generator will begin returning results from the point '
                   'where the previous generator stopped.')
コード例 #59
0
ファイル: _params.py プロジェクト: johanste/azure-cli
def load_arguments(self, _):

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

    with self.argument_context('sql db') as c:
        c.argument('server_name',
                   arg_type=server_param_type)

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

        c.argument('max_size_bytes',
                   arg_type=max_size_bytes_param_type)

        creation_arg_group = 'Creation'

        c.argument('collation',
                   arg_group=creation_arg_group)

        c.argument('catalog_collation',
                   arg_group=creation_arg_group,
                   arg_type=get_enum_type(CatalogCollationType))

        c.argument('sample_name',
                   arg_group=creation_arg_group)

        c.argument('license_type',
                   arg_type=get_enum_type(DatabaseLicenseType))

        # Needs testing
        c.ignore('read_scale')
        # c.argument('read_scale',
        #            arg_type=get_three_state_flag(DatabaseReadScale.enabled.value,
        #                                         DatabaseReadScale.disabled.value,
        #                                         return_label=True))

        c.argument('zone_redundant',
                   arg_type=zone_redundant_param_type)

        c.argument('tier',
                   arg_type=tier_param_type,
                   help='The edition component of the sku. Allowed values include: Basic, Standard, '
                   'Premium, GeneralPurpose, BusinessCritical.')

        c.argument('capacity',
                   arg_type=capacity_param_type,
                   arg_group=sku_component_arg_group,
                   help='The capacity component of the sku in integer number of DTUs or vcores.')

        c.argument('family',
                   arg_type=family_param_type,
                   help='The compute generation component of the sku (for vcore skus only). '
                   'Allowed values include: Gen4, Gen5.')

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

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

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

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

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

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

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

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

        restore_point_arg_group = 'Restore Point'

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

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

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

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

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

        c.argument('available', arg_type=available_param_type)

        search_arg_group = 'Search'

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

        c.argument('service_objective',
                   arg_group=search_arg_group,
                   help='Service objective to search for. If unspecified, all service objectives are shown.')

        c.argument('dtu',
                   arg_group=search_arg_group,
                   help='Number of DTUs to search for. If unspecified, all DTU sizes are shown.')

        c.argument('vcores',
                   arg_group=search_arg_group,
                   help='Number of vcores to search for. If unspecified, all vcore sizes are shown.')

    with self.argument_context('sql db update') as c:
        c.argument('service_objective',
                   arg_group=sku_arg_group,
                   help='The name of the new service objective. If this is a standalone db service'
                   ' objective and the db is currently in an elastic pool, then the db is removed from'
                   ' the pool.')

        c.argument('elastic_pool_id',
                   arg_type=elastic_pool_id_param_type,
                   help='The name or resource id of the elastic pool to move the database into.')

        c.argument('max_size_bytes', help='The new maximum size of the database expressed in bytes.')

    with self.argument_context('sql db export') as c:
        # Create args that will be used to build up the ExportRequest object
        create_args_for_complex_type(
            c, 'parameters', ExportRequest, [
                'administrator_login',
                'administrator_login_password',
                'authentication_type',
                'storage_key',
                'storage_key_type',
                'storage_uri',
            ])

        c.argument('administrator_login',
                   options_list=['--admin-user', '-u'])

        c.argument('administrator_login_password',
                   options_list=['--admin-password', '-p'])

        c.argument('authentication_type',
                   options_list=['--auth-type', '-a'],
                   arg_type=get_enum_type(AuthenticationType))

        c.argument('storage_key_type',
                   arg_type=get_enum_type(StorageKeyType))

    with self.argument_context('sql db import') as c:
        # Create args that will be used to build up the ImportExtensionRequest object
        create_args_for_complex_type(c, 'parameters', ImportExtensionRequest, [
            'administrator_login',
            'administrator_login_password',
            'authentication_type',
            'storage_key',
            'storage_key_type',
            'storage_uri'
        ])

        c.argument('administrator_login',
                   options_list=['--admin-user', '-u'])

        c.argument('administrator_login_password',
                   options_list=['--admin-password', '-p'])

        c.argument('authentication_type',
                   options_list=['--auth-type', '-a'],
                   arg_type=get_enum_type(AuthenticationType))

        c.argument('storage_key_type',
                   arg_type=get_enum_type(StorageKeyType))

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

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

        auth_group = 'Authentication'

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

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

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

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

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

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

    with self.argument_context('sql db replica set-primary') as c:
        c.argument('database_name',
                   help='Name of the database to fail over.')

        c.argument('server_name',
                   help='Name of the server containing the secondary replica that will become'
                   ' the new primary. ' + server_configure_help)

        c.argument('resource_group_name',
                   help='Name of the resource group containing the secondary replica that'
                   ' will become the new primary.')

        c.argument('allow_data_loss',
                   help='If specified, the failover operation will allow data loss.')

    with self.argument_context('sql db replica delete-link') as c:
        c.argument('partner_server_name',
                   options_list=['--partner-server'],
                   help='Name of the server that the other replica is in.')

        c.argument('partner_resource_group_name',
                   options_list=['--partner-resource-group'],
                   help='Name of the resource group that the other replica is in. If unspecified,'
                   ' defaults to the first database\'s resource group.')

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

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

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

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

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

        policy_arg_group = 'Policy'

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

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

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

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

        policy_arg_group = 'Policy'
        notification_arg_group = 'Notification'

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

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

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

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

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

        # TODO: use server default

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

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

    ###############################################
    #                sql dw                       #
    ###############################################
    with self.argument_context('sql dw') as c:
        c.argument('server_name',
                   arg_type=server_param_type)

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

        c.argument('max_size_bytes',
                   arg_type=max_size_bytes_param_type)

        c.argument('service_objective',
                   help='The service objective of the data warehouse. For example: ' +
                   dw_service_objective_examples)

        c.argument('collation',
                   help='The collation of the data warehouse.')

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

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

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

    ###############################################
    #                sql elastic-pool             #
    ###############################################
    with self.argument_context('sql elastic-pool') as c:
        c.argument('server_name',
                   arg_type=server_param_type)

        c.argument('elastic_pool_name',
                   options_list=['--name', '-n'],
                   help='The name of the elastic pool.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

        # --db-dtu-max and --db-dtu-min were the original param names, which is consistent with the
        # 2014-04-01 REST API.
        # --db-max-dtu and --db-min-dtu are aliases which are consistent with the `sql elastic-pool
        # list-editions --show-details db-max-dtu db-min-dtu` parameter values. These are more
        # consistent with other az sql commands, but the original can't be removed due to
        # compatibility.
        c.argument('max_capacity',
                   options_list=['--db-dtu-max', '--db-max-dtu', '--db-max-capacity'],
                   help='The maximum capacity (in DTUs or vcores) any one database can consume.')

        c.argument('min_capacity',
                   options_list=['--db-dtu-min', '--db-min-dtu', '--db-min-capacity'],
                   help='The minumum capacity (in DTUs or vcores) each database is guaranteed.')

        # --storage was the original param name, which is consistent with the underlying REST API.
        # --max-size is an alias which is consistent with the `sql elastic-pool list-editions
        # --show-details max-size` parameter value and also matches `sql db --max-size` parameter name.
        c.argument('max_size_bytes',
                   arg_type=max_size_bytes_param_type,
                   options_list=['--max-size', '--storage'])

        c.argument('license_type',
                   arg_type=get_enum_type(ElasticPoolLicenseType))

        c.argument('zone_redundant',
                   arg_type=zone_redundant_param_type)

        c.argument('tier',
                   arg_type=tier_param_type,
                   help='The edition component of the sku. Allowed values include: Basic, Standard, '
                   'Premium, GeneralPurpose, BusinessCritical.')

        c.argument('capacity',
                   arg_type=capacity_or_dtu_param_type,
                   help='The capacity component of the sku in integer number of DTUs or vcores.')

        c.argument('family',
                   arg_type=family_param_type,
                   help='The compute generation component of the sku (for vcore skus only). '
                   'Allowed values include: Gen4, Gen5.')

    with self.argument_context('sql elastic-pool create') as c:
        # Create args that will be used to build up the ElasticPool object
        create_args_for_complex_type(
            c, 'parameters', ElasticPool, [
                'license_type',
                'max_size_bytes',
                'name',
                'per_database_settings',
                'tags',
                'zone_redundant',
            ])

        # Create args that will be used to build up the ElasticPoolPerDatabaseSettings object
        create_args_for_complex_type(
            c, 'per_database_settings', ElasticPoolPerDatabaseSettings, [
                'max_capacity',
                'min_capacity',
            ])

        # Create args that will be used to build up the ElasticPool Sku object
        create_args_for_complex_type(
            c, 'sku', Sku, [
                'capacity',
                'family',
                'name',
                'tier',
            ])

        c.ignore('name')  # Hide sku name

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

        c.argument('available',
                   arg_type=available_param_type)

        search_arg_group = 'Search'

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

        c.argument('dtu',
                   arg_group=search_arg_group,
                   help='Number of DTUs to search for. If unspecified, all DTU sizes are shown.')

        c.argument('vcores',
                   arg_group=search_arg_group,
                   help='Number of vcores to search for. If unspecified, all vcore sizes are shown.')

    with self.argument_context('sql elastic-pool update') as c:
        c.argument('database_dtu_max',
                   help='The maximum DTU any one database can consume.')

        c.argument('database_dtu_min',
                   help='The minimum DTU all databases are guaranteed.')

        c.argument('storage_mb',
                   help='Storage limit for the elastic pool in MB.')

    #####
    #           sql elastic-pool op
    #####
    with self.argument_context('sql elastic-pool op') as c:
        c.argument('elastic_pool_name',
                   options_list=['--elastic-pool'],
                   help='Name of the Azure SQL Elastic Pool.')

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

    ###############################################
    #             sql failover-group              #
    ###############################################

    with self.argument_context('sql failover-group') as c:
        c.argument('failover_group_name', options_list=['--name', '-n'], help="The name of the Failover Group")
        c.argument('server_name', arg_type=server_param_type)
        c.argument('partner_server', help="The name of the partner server of a Failover Group")
        c.argument('partner_resource_group', help="The name of the resource group of the partner server")
        c.argument('failover_policy', help="The failover policy of the Failover Group",
                   arg_type=get_enum_type(FailoverPolicyType))
        c.argument('grace_period',
                   help='Interval in hours before automatic failover is initiated '
                        'if an outage occurs on the primary server. '
                        'This indicates that Azure SQL Database will not initiate '
                        'automatic failover before the grace period expires. '
                        'Please note that failover operation with AllowDataLoss option '
                        'might cause data loss due to the nature of asynchronous synchronization.')
        c.argument('add_db', nargs='+',
                   help='List of databases to add to Failover Group')
        c.argument('remove_db', nargs='+',
                   help='List of databases to remove from Failover Group')
        c.argument('allow-data-loss',
                   help='Complete the failover even if doing so may result in data loss. '
                        'This will allow the failover to proceed even if a primary database is unavailable.')

    ###############################################
    #                sql server                   #
    ###############################################
    with self.argument_context('sql server') as c:
        c.argument('server_name',
                   arg_type=server_param_type,
                   options_list=['--name', '-n'])

        c.argument('administrator_login',
                   options_list=['--admin-user', '-u'])

        c.argument('administrator_login_password',
                   options_list=['--admin-password', '-p'])

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

    with self.argument_context('sql server create') as c:
        # Create args that will be used to build up the Server object
        create_args_for_complex_type(
            c, 'parameters', Server, [
                'administrator_login',
                'administrator_login_password',
                'location'
            ])

        c.argument('administrator_login',
                   required=True)

        c.argument('administrator_login_password',
                   required=True)

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

    with self.argument_context('sql server update') as c:
        c.argument('administrator_login_password',
                   help='The administrator login password.')

    #####
    #           sql server ad-admin
    ######
    with self.argument_context('sql server ad-admin') as c:
        # The options list should be ['--server', '-s'], but in the originally released version it was
        # ['--server-name'] which we must keep for backward compatibility - but we should deprecate it.
        c.argument('server_name',
                   options_list=['--server-name', '--server', '-s'])

        c.argument('login',
                   options_list=['--display-name', '-u'],
                   help='Display name of the Azure AD administrator user or group.')

        c.argument('sid',
                   options_list=['--object-id', '-i'],
                   help='The unique ID of the Azure AD administrator ')

        c.ignore('tenant_id')

    with self.argument_context('sql server ad-admin create') as c:
        # Create args that will be used to build up the ServerAzureADAdministrator object
        create_args_for_complex_type(
            c, 'properties', ServerAzureADAdministrator, [
                'login',
                'sid',
            ])

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

        c.argument('connection_type',
                   options_list=['--connection-type', '-t'],
                   arg_type=get_enum_type(ServerConnectionType))

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

        c.argument('dns_alias_name',
                   options_list=('--name', '-n'))

        c.argument('original_server_name',
                   options_list=('--original-server'),
                   help='The name of the server to which alias is currently pointing')

        c.argument('original_resource_group_name',
                   options_list=('--original-resource-group'))

        c.argument('original_subscription_id',
                   options_list=('--original-subscription-id'))

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

        c.argument('firewall_rule_name',
                   options_list=['--name', '-n'],
                   help='The name of the firewall rule.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

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

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

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

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

        c.argument('kid',
                   options_list=['--kid', '-k'],
                   required=True,
                   help='The Azure Key Vault key identifier of the server key. An example key identifier is '
                   '"https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901"')

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

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

        c.argument('server_key_type',
                   options_list=['--server-key-type', '-t'],
                   help='The type of the server key',
                   arg_type=get_enum_type(ServerKeyType))

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

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

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

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

    with self.argument_context('sql server vnet-rule create') as c:
        c.extra('vnet_name',
                options_list=['--vnet-name'],
                help='The virtual network name')

    ###############################################
    #                sql managed instance         #
    ###############################################
    with self.argument_context('sql mi') as c:
        c.argument('managed_instance_name',
                   help='The managed instance name',
                   options_list=['--name', '-n'],
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')

        c.argument('tier',
                   arg_type=tier_param_type,
                   help='The edition component of the sku. Allowed value is GeneralPurpose.')

        c.argument('family',
                   arg_type=family_param_type,
                   help='The compute generation component of the sku. '
                   'Allowed values include: Gen4, Gen5.')

        c.argument('storage_size_in_gb',
                   options_list=['--storage'],
                   arg_type=storage_param_type,
                   help='The storage size of the managed instance. '
                   'Storage size must be specified in increments of 32 GB')

        c.argument('license_type',
                   arg_type=get_enum_type(DatabaseLicenseType),
                   help='The license type to apply for this managed instance.')

        c.argument('vcores',
                   options_list=['--capacity', '-c'],
                   help='The capacity of the managed instance in vcores.')

    with self.argument_context('sql mi create') as c:
        # Create args that will be used to build up the ManagedInstance object
        create_args_for_complex_type(
            c, 'parameters', ManagedInstance, [
                'administrator_login',
                'administrator_login_password',
                'license_type',
                'virtual_network_subnet_id',
                'vcores',
                'storage_size_in_gb'
            ])

        # Create args that will be used to build up the Managed Instance's Sku object
        create_args_for_complex_type(
            c, 'sku', Sku, [
                'family',
                'name',
                'tier',
            ])

        c.ignore('name')  # Hide sku name

        c.argument('administrator_login',
                   options_list=['--admin-user', '-u'],
                   required=True)

        c.argument('administrator_login_password',
                   options_list=['--admin-password', '-p'],
                   required=True)

        c.extra('vnet_name',
                options_list=['--vnet-name'],
                help='The virtual network name',
                validator=validate_subnet)

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

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

    with self.argument_context('sql mi update') as c:
        # Create args that will be used to build up the ManagedInstance object
        create_args_for_complex_type(
            c, 'parameters', ManagedInstance, [
                'administrator_login_password',
            ])

        c.argument('administrator_login_password',
                   options_list=['--admin-password', '-p'])

        c.argument('assign_identity',
                   options_list=['--assign-identity', '-i'],
                   help='Generate and assign an Azure Active Directory Identity for this managed instance '
                   'for use with key management services like Azure KeyVault. '
                   'If identity is already assigned - do nothing.')

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

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

    with self.argument_context('sql midb create') as c:
        create_args_for_complex_type(
            c, 'parameters', ManagedDatabase, [
                'collation',
            ])

        c.argument('collation',
                   required=False,
                   help='The collation of the Azure SQL Managed Database collation to use, '
                   'e.g.: SQL_Latin1_General_CP1_CI_AS or Latin1_General_100_CS_AS_SC')

    with self.argument_context('sql midb restore') as c:
        create_args_for_complex_type(
            c, 'parameters', ManagedDatabase, [
                'target_managed_database_name',
                'target_managed_instance_name',
                'restore_point_in_time'
            ])

        c.argument('target_managed_database_name',
                   options_list=['--dest-name'],
                   required=True,
                   help='Name of the managed database that will be created as the restore destination.')

        c.argument('target_managed_instance_name',
                   options_list=['--dest-mi'],
                   help='Name of the managed instance to restore managed database to. '
                   'This can be same managed instance, or another managed instance on same subscription. '
                   'When not specified it defaults to source managed instance.')

        c.argument('target_resource_group_name',
                   options_list=['--dest-resource-group'],
                   help='Name of the resource group of the managed instance to restore managed database to. '
                   'When not specified it defaults to source resource group.')

        restore_point_arg_group = 'Restore Point'

        c.argument('restore_point_in_time',
                   options_list=['--time', '-t'],
                   arg_group=restore_point_arg_group,
                   required=True,
                   help='The point in time of the source database that will be restored to create the'
                   ' new database. Must be greater than or equal to the source database\'s'
                   ' earliestRestoreDate value. Time should be in following format: "YYYY-MM-DDTHH:MM:SS"')

    with self.argument_context('sql midb list') as c:
        c.argument('managed_instance_name', id_part=None)
コード例 #60
0
ファイル: _params.py プロジェクト: venkataratnam19/azure-cli
def load_arguments(self, _):
    (JsonWebKeyOperation, KeyAttributes, JsonWebKeyType, JsonWebKeyCurveName,
     SasTokenType, SasDefinitionAttributes, SecretAttributes,
     CertificateAttributes, StorageAccountAttributes) = self.get_models(
         'JsonWebKeyOperation',
         'KeyAttributes',
         'JsonWebKeyType',
         'JsonWebKeyCurveName',
         'SasTokenType',
         'SasDefinitionAttributes',
         'SecretAttributes',
         'CertificateAttributes',
         'StorageAccountAttributes',
         resource_type=ResourceType.DATA_KEYVAULT)

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

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

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

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

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

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

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

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

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

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

        for cmd in ['backup', 'delete', 'download', 'set-attributes', 'show']:
            with self.argument_context('keyvault {} {}'.format(item, cmd),
                                       arg_group='Id') as c:
                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)
    # endregion

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

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

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

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

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

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

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

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

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

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

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

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