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.')
def load_arguments(self, _):

    ExpressRoutePeeringType = self.get_models('ExpressRoutePeeringType')

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

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

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

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

    with self.argument_context('network cross-connection peering list') as c:
        c.argument('cross_connection_name', id_part=None)
Esempio n. 3
0
def load_arguments(self, _):
    with self.argument_context('container') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('name', options_list=['--name', '-n'], help="The name of the container group", id_part='name')
        c.argument('location', arg_type=get_location_type(self.cli_ctx))

    with self.argument_context('container create') as c:
        c.argument('location', arg_type=get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)
        c.argument('image', help='The container image name')
        c.argument('cpu', type=int, help='The required number of CPU cores of the containers')
        c.argument('memory', type=float, help='The required memory of the containers in GB')
        c.argument('os_type', arg_type=get_enum_type(OperatingSystemTypes), help='The OS type of the containers')
        c.argument('ip_address', arg_type=get_enum_type(IP_ADDRESS_TYPES), help='The IP address type of the container group')
        c.argument('ports', type=int, nargs='+', default=[80], help='The ports to open')
        c.argument('protocol', arg_type=get_enum_type(ContainerNetworkProtocol), help='The network protocol to use')
        c.argument('dns_name_label', help='The dns name label for container group with public IP')
        c.argument('restart_policy', arg_type=get_enum_type(ContainerGroupRestartPolicy), help='Restart policy for all containers within the container group')
        c.argument('command_line', help='The command line to run when the container is started, e.g. \'/bin/bash -c myscript.sh\'')
        c.argument('environment_variables', nargs='+', options_list=['--environment-variables', '-e'], type=_environment_variables_type, help='A list of environment variable for the container. Space-separated values in \'key=value\' format.')
        c.argument('secrets', secrets_type)
        c.argument('secrets_mount_path', validator=validate_volume_mount_path, help="The path within the container where the secrets volume should be mounted. Must not contain colon ':'.")
        c.argument('file', options_list=['--file', '-f'], help="The path to the input file.")

    with self.argument_context('container create', arg_group='Image Registry') as c:
        c.argument('registry_login_server', help='The container image registry login server')
        c.argument('registry_username', help='The username to log in container image registry server')
        c.argument('registry_password', help='The password to log in container image registry server')

    with self.argument_context('container create', arg_group='Azure File Volume') as c:
        c.argument('azure_file_volume_share_name', help='The name of the Azure File share to be mounted as a volume')
        c.argument('azure_file_volume_account_name', help='The name of the storage account that contains the Azure File share')
        c.argument('azure_file_volume_account_key', help='The storage account access key used to access the Azure File share')
        c.argument('azure_file_volume_mount_path', validator=validate_volume_mount_path, help="The path within the container where the azure file volume should be mounted. Must not contain colon ':'.")

    with self.argument_context('container create', arg_group='Log Analytics') as c:
        c.argument('log_analytics_workspace', help='The Log Analytics workspace name or id. If a name is specified, use the current subscription or use --subscription flag to set the desired subscription.')
        c.argument('log_analytics_workspace_key', help='The Log Analytics workspace key.')

    with self.argument_context('container create', arg_group='Git Repo Volume') as c:
        c.argument('gitrepo_url', help='The URL of a git repository to be mounted as a volume')
        c.argument('gitrepo_dir', validator=validate_gitrepo_directory, help="The target directory path in the git repository. Must not contain '..'.")
        c.argument('gitrepo_revision', help='The commit hash for the specified revision')
        c.argument('gitrepo_mount_path', validator=validate_volume_mount_path, help="The path within the container where the git repo volume should be mounted. Must not contain colon ':'.")

    with self.argument_context('container logs') as c:
        c.argument('container_name', help='The container name to tail the logs. If omitted, the first container in the container group will be chosen')
        c.argument('follow', help='Indicate to stream the tailing logs', action='store_true')

    with self.argument_context('container export') as c:
        c.argument('file', options_list=['--file', '-f'], help="The file path to export the container group.")

    with self.argument_context('container exec') as c:
        c.argument('container_name', help='The container name where to execute the command. Can be ommitted for container groups with only one container.')
        c.argument('exec_command', help='The command to run from within the container')
        c.argument('terminal_row_size', help='The row size for the command output')
        c.argument('terminal_col_size', help='The col size for the command output')

    with self.argument_context('container attach') as c:
        c.argument('container_name', help='The container to attach to. If omitted, the first container in the container group will be chosen')
def load_arguments(self, _):  # pylint: disable=too-many-locals, too-many-statements
    for scope in ('mysql', 'postgres', 'sql'):
        with self.argument_context('{} up'.format(scope)) as c:
            c.argument('location', arg_type=get_location_type(self.cli_ctx))
            c.argument('server_name', options_list=['--server-name', '-s'], help='Name of the server.')
            c.argument('administrator_login', options_list=['--admin-user', '-u'], arg_group='Authentication',
                       help='The login username of the administrator.')
            c.argument('administrator_login_password', options_list=['--admin-password', '-p'],
                       arg_group='Authentication', help='The login password of the administrator.')
            c.extra('generate_password', help='Generate a password.', arg_group='Authentication')
            c.argument('database_name', options_list=['--database-name', '-d'],
                       help='The name of a database to initialize.')
            c.argument('tags', tags_type)

        if scope != 'sql':  # SQL alreaady has a core command for displaying connection strings
            with self.argument_context('{} show-connection-string'.format(scope)) as c:
                c.argument('server_name', options_list=['--server-name', '-s'], help='Name of the server.')
                c.argument('database_name', options_list=['--database-name', '-d'], help='The name of a database.')
                c.argument('administrator_login', options_list=['--admin-user', '-u'],
                           help='The login username of the administrator.')
                c.argument('administrator_login_password', options_list=['--admin-password', '-p'],
                           help='The login password of the administrator.')

        with self.argument_context('{} down'.format(scope)) as c:
            c.ignore('server_name')
            c.ignore('resource_group_name')
            c.argument('delete_group', action='store_true', help="Delete the resource group.")

    for scope in ('mysql', 'postgres'):
        with self.argument_context('{} up'.format(scope)) as c:
            c.argument('sku_name', options_list=['--sku-name'], default='GP_Gen5_2',
                       help='The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8.')
            c.argument('backup_retention', type=int, help='The number of days a backup is retained.')
            c.argument('geo_redundant_backup', arg_type=get_enum_type(GeoRedundantBackup),
                       default=GeoRedundantBackup.disabled.value, 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('ssl_enforcement', arg_type=get_enum_type(SslEnforcementEnum),
                       default=SslEnforcementEnum.disabled.value,
                       help='Enable ssl enforcement or not when connect to server.')

    with self.argument_context('mysql up') as c:
        c.argument('version', help='Server version', default='5.7')

    with self.argument_context('postgres up') as c:
        c.argument('version', help='Server version', default='10')

    with self.argument_context('sql up') as c:
        c.argument('version', help='Server version', default='12.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 publish') as c:
        c.argument('code_dir', options_list=['--code-dir'], help='The directory to upload bot code from.')
        c.argument('proj_name', options_list=['--proj-file'], help='The startup project file name (without the .csproj)'
                                                                   ' that needs to be published. Eg: EnterpriseBot.')
        c.argument('version', options_list=['-v', '--version'], help='The Microsoft Bot Builder SDK version.',
                   arg_type=get_enum_type(['v3', 'v4']))
Esempio n. 6
0
def load_arguments(self, _):
    # Argument Definition
    maps_name_type = CLIArgumentType(options_list=['--name', '-n'],
                                     completer=get_resource_name_completion_list('Microsoft.Maps/accounts'),
                                     help='The name of the maps account')

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

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

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

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

    with self.argument_context('maps account keys renew') as c:
        c.argument('key_type',
                   options_list=['--key'],
                   arg_type=get_enum_type(KeyType))
Esempio n. 7
0
def load_arguments(self, _):
    with self.argument_context('consumption usage') as c:
        c.argument('top', options_list=['--top', '-t'], type=int, help='Maximum number of items to return. Value range: 1-1000.')
        c.argument('include_additional_properties', options_list=['--include-additional-properties', '-a'], action='store_true', help='Include additional properties in the usages.')
        c.argument('include_meter_details', options_list=['--include-meter-details', '-m'], action='store_true', help='Include meter details in the usages.')
        c.argument('start_date', options_list=['--start-date', '-s'], type=datetime_type, help='Start date (YYYY-MM-DD in UTC). If specified, also requires --end-date.')
        c.argument('end_date', options_list=['--end-date', '-e'], type=datetime_type, help='End date (YYYY-MM-DD in UTC). If specified, also requires --start-date.')
        c.argument('billing_period_name', options_list=['--billing-period-name', '-p'], help='Name of the billing period to get the usage details that associate with.')

    with self.argument_context('consumption reservation') as rs:
        rs.argument('reservation_order_id', help='Reservation order id.')
        rs.argument('start_date', options_list=['--start-date', '-s'], type=datetime_type, help='Start date (YYYY-MM-DD in UTC). Only needed for daily grain and if specified, also requires --end-date.')
        rs.argument('end_date', options_list=['--end-date', '-e'], type=datetime_type, help='End date (YYYY-MM-DD in UTC). Only needed for daily grain and if specified, also requires --start-date.')
        rs.argument('reservation_id', help='Reservation id.')

    with self.argument_context('consumption reservation summary list') as rs:
        rs.argument('grain', help='Reservation summary grain. Possible values are daily or monthly.')

    with self.argument_context('consumption pricesheet show') as cps:
        cps.argument('include_meter_details', action='store_true', help='Include meter details in the price sheet.')
        cps.argument('billing_period_name', options_list=['--billing-period-name', '-p'], help='Name of the billing period to get the price sheet.')

    with self.argument_context('consumption marketplace list') as cmp:
        cmp.argument('billing_period_name', options_list=['--billing-period-name', '-p'], help='Name of the billing period to get the marketplace.')
        cmp.argument('top', options_list=['--top', '-t'], type=int, help='Maximum number of items to return. Value range: 1-1000.')
        cmp.argument('start_date', options_list=['--start-date', '-s'], type=datetime_type, help='Start date (YYYY-MM-DD in UTC). If specified, also requires --end-date.')
        cmp.argument('end_date', options_list=['--end-date', '-e'], type=datetime_type, help='End date (YYYY-MM-DD in UTC). If specified, also requires --start-date.')

    with self.argument_context('consumption budget') as cb:
        cb.argument('budget_name', help='Name of a budget.')
        cb.argument('category', arg_type=get_enum_type(['cost', 'usage']), help='Category of the budget can be cost or usage.')
        cb.argument('amount', type=decimal_type, help='Amount of a budget.')
        cb.argument('time_grain', arg_type=get_enum_type(['monthly', 'quarterly', 'annually']), help='Time grain of the budget can be monthly, quarterly, or annually.')
        cb.argument('start_date', options_list=['--start-date', '-s'], type=datetime_type, help='Start date (YYYY-MM-DD in UTC) of time period of a budget.')
        cb.argument('end_date', options_list=['--end-date', '-e'], type=datetime_type, help='End date (YYYY-MM-DD in UTC) of time period of a budget.')
        cb.argument('resource_groups', options_list='--resource-group-filter', nargs='+', help='Space-separated list of resource groups to filter on.')
        cb.argument('resources', options_list='--resource-filter', nargs='+', help='Space-separated list of resource instances to filter on.')
        cb.argument('meters', options_list='--meter-filter', nargs='+', help='Space-separated list of meters to filter on. Required if category is usage.')
Esempio n. 8
0
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')
def load_arguments(self, _):
    name_arg_type = CLIArgumentType(options_list=('--name', '-n'), metavar='NAME')

    with self.argument_context('network dns') as c:
        c.argument('record_set_name', name_arg_type, help='The name of the record set, relative to the name of the zone.')
        c.argument('relative_record_set_name', name_arg_type, help='The name of the record set, relative to the name of the zone.')
        c.argument('zone_name', options_list=('--zone-name', '-z'), help='The name of the zone.', type=dns_zone_name_type)
        c.argument('metadata', nargs='+', help='Metadata in space-separated key=value pairs. This overwrites any existing metadata.', validator=validate_metadata)

    with self.argument_context('network dns zone') as c:
        c.argument('zone_name', name_arg_type)
        c.ignore('location')

        c.argument('zone_type', help='Type of DNS zone to create.', arg_type=get_enum_type(ZoneType))
        c.argument('registration_vnets', arg_group='Private Zone', nargs='+', help='Space-separated names or IDs of virtual networks that register hostnames in this DNS zone.', validator=get_vnet_validator('registration_vnets'))
        c.argument('resolution_vnets', arg_group='Private Zone', nargs='+', help='Space-separated names or IDs of virtual networks that resolve records in this DNS zone.', validator=get_vnet_validator('resolution_vnets'))
Esempio n. 10
0
def load_arguments(self, _):

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

    with self.argument_context('iotcentral app create') as c:
        c.argument('app_name', completer=None)
        c.argument('location', get_location_type(self.cli_ctx),
                   help='Location of your IoT Central application. Default is the location of target resource group.')
        c.argument('sku', arg_type=get_enum_type(AppSku),
                   help='Pricing tier for IoT Central applications. Default value is F1, which is free.')
        c.argument(
            'subdomain', help='Subdomain for the IoT Central URL. Each application must have a unique subdomain.')
Esempio n. 11
0
def load_arguments(self, _):
    with self.argument_context('reservations reservation update') as c:
        c.argument('applied_scope_type', options_list=['--applied-scope-type', '-t'], arg_type=get_enum_type(AppliedScopeType))
        c.argument('applied_scopes', options_list=['--applied-scopes', '-s'])
        c.argument('instance_flexibility', options_list=['--instance-flexibility', '-i'], arg_type=get_enum_type(InstanceFlexibility))

    with self.argument_context('reservations reservation split') as c:
        c.argument('quantity_1', options_list=['--quantity-1', '-1'])
        c.argument('quantity_2', options_list=['--quantity-2', '-2'])

    with self.argument_context('reservations reservation merge') as c:
        c.argument('reservation_id_1', options_list=['--reservation-id-1', '-1'])
        c.argument('reservation_id_2', options_list=['--reservation-id-2', '-2'])

    with self.argument_context('reservations catalog show') as c:
        c.argument('reserved_resource_type', arg_type=get_enum_type(ReservedResourceType))
Esempio n. 12
0
    def _register_data_plane_oauth_arguments(self, command_name):
        from azure.cli.core.commands.parameters import get_enum_type

        # The CLI's argument registration methods assume command table has finished loading and contain checks
        # that reflect the state of the CLI at that point in time.
        # The following code bypasses those checks, as these arguments are registered in tandem with commands.
        if command_name not in self.command_loader.command_table:
            return
        self.command_loader.cli_ctx.invocation.data['command_string'] = command_name

        with self.command_loader.argument_context(command_name, min_api='2017-11-09') as c:
            c.extra('auth_mode', arg_type=get_enum_type(['login', 'key']),
                    help='The mode in which to run the command. "login" mode will directly use your login credentials '
                         'for the authentication. The legacy "key" mode will attempt to query for '
                         'an account key if no authentication parameters for the account are provided. '
                         'Environment variable: AZURE_STORAGE_AUTH_MODE')
Esempio n. 13
0
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'))
Esempio n. 14
0
    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')
Esempio n. 15
0
def load_arguments(self, _):

    # Kusto clusters
    sku_arg_type = CLIArgumentType(help='The name of the sku.',
                                   arg_type=get_enum_type(AzureSkuName))
    time_format_explenation = 'Duration in ISO8601 format (for example, 100 days would be P100D).'

    with self.argument_context('kusto cluster') as c:
        c.ignore('kusto_management_request_options')
        c.argument('cluster_name', arg_type=name_type, help='The name of the cluster.', id_part='name')
        c.argument('sku', arg_type=sku_arg_type)
        c.argument('capacity', type=int, help='The instance number of the VM.')

    # Kusto databases
    with self.argument_context('kusto database') as c:
        c.ignore('kusto_management_request_options')
        c.argument('cluster_name', help='The name of the cluster.', id_part='name')
        c.argument('database_name', arg_type=name_type, help='The name of the database.', id_part='child_name_1')
        c.argument('soft_delete_period', help='Amount of time that data should be kept so it is available to query. ' + time_format_explenation)
        c.argument('hot_cache_period', help='Amount of time that data should be kept in cache.' + time_format_explenation)

    # Kusto database list
    with self.argument_context('kusto database list') as c:
        c.argument('cluster_name', id_part=None)
Esempio n. 16
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)
Esempio n. 17
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 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())
Esempio n. 18
0
def load_arguments(self, _):  # pylint: disable=too-many-statements
    # PARAMETER REGISTRATION
    application_parameters = CLIArgumentType(
        options_list=['--parameters', '--application-parameters'],
        action=AddAppParamsAction,
        nargs='+',
        help=
        'Specify the application parameters as key/value pairs. These parameters must exist in the application manifest. '
        'for example: --application-parameters param1=value1 param2=value2')

    minimum_nodes = CLIArgumentType(
        options_list=['--min-nodes', '--minimum-nodes'],
        help=
        'Specify the minimum number of nodes where Service Fabric will reserve capacity for this application, '
        'this does not mean that the application is guaranteed to have replicas on all those nodes. The value of this parameter must be a non-negative integer. '
        'Default value for this is zero, which means no capacity is reserved for the application.'
    )

    maximum_nodes = CLIArgumentType(
        options_list=['--max-nodes', '--maximum-nodes'],
        help=
        'Specify the maximum number of nodes on which to place an application. '
        'The value of this parameter must be a non-negative integer. The default value is 0, which indicates the application can be placed on any number of nodes in the cluster.'
    )

    application_type_version = CLIArgumentType(
        options_list=['--version', '--application-type-version'],
        help='Specify the application type version.')

    package_url = CLIArgumentType(
        help='Specify the url of the application package sfpkg file.')

    with self.argument_context('sf') as c:
        c.argument(
            'resource_group_name',
            arg_type=resource_group_name_type,
            id_part=None,
            help=
            'Specify the resource group name. You can configure the default group using `az configure --defaults group=<name>`'
        )
        c.argument(
            'cluster_name',
            options_list=['--cluster-name', '-c'],
            help=
            'Specify the name of the cluster, if not given it will be same as resource group name'
        )
        c.argument('location',
                   validator=get_default_location_from_resource_group)
        c.argument('secret_identifier',
                   help='The existing Azure key vault secret URL')
        c.argument(
            'certificate_file',
            help=
            'The existing certificate file path for the primary cluster certificate.'
        )
        c.argument('parameter_file',
                   help='The path to the template parameter file.')
        c.argument('template_file', help='The path to the template file.')
        c.argument('vm_password', help='The password of the Vm')
        c.argument(
            'certificate_output_folder',
            options_list=['--certificate-output-folder', '--cert-out-folder'],
            help='The folder of the new certificate file to be created.')
        c.argument('certificate_password',
                   help='The password of the certificate file.')
        c.argument(
            'certificate_subject_name',
            options_list=['--certificate-subject-name', '--cert-subject-name'],
            help='The subject name of the certificate to be created.')
        c.argument(
            'vault_resource_group_name',
            options_list=['--vault-resource-group'],
            help=
            'Key vault resource group name, if not given it will be cluster resource group name'
        )
        c.argument(
            'vault_name',
            help=
            'Azure key vault name, it not given it will be the cluster resource group name'
        )
        c.argument(
            'cluster_size',
            options_list=['--cluster-size', '-s'],
            help='The number of nodes in the cluster. Default are 5 nodes')
        c.argument('vm_sku', help='VM Sku')
        c.argument(
            'vm_user_name',
            help='The user name for logging to Vm. Default will be adminuser')
        c.argument(
            'vm_os',
            arg_type=get_enum_type([
                'WindowsServer2012R2Datacenter', 'WindowsServer2016Datacenter',
                'WindowsServer2016DatacenterwithContainers',
                'UbuntuServer1604', 'WindowsServer1709',
                'WindowsServer1709withContainers',
                'WindowsServer1803withContainers',
                'WindowsServer1809withContainers',
                'WindowsServer2019Datacenter',
                'WindowsServer2019DatacenterwithContainers'
            ]),
            default='WindowsServer2016Datacenter',
            options_list=['--vm-os', '--os'],
            help='The Operating System of the VMs that make up the cluster.')
        c.argument('node_type', help='the Node type name.')

    # cluster
    with self.argument_context('sf cluster list') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   id_part=None,
                   help='The resource group name')

    with self.argument_context('sf client certificate') as c:
        c.argument('certificate_common_name',
                   help='client certificate common name.')
        c.argument(
            'admin_client_thumbprints',
            options_list=['--admin-client-thumbprints', '--admin-client-tps'],
            nargs='+',
            help=
            'Space-separated list of client certificate thumbprint that only has admin permission, '
        )
        c.argument('certificate_issuer_thumbprint',
                   options_list=[
                       '--certificate-issuer-thumbprint', '--cert-issuer-tp'
                   ],
                   help='client certificate issuer thumbprint.')

    with self.argument_context('sf cluster certificate') as c:
        c.argument('thumbprint',
                   help='The cluster certificate thumbprint to be removed')

    with self.argument_context('sf cluster client-certificate') as c:
        c.argument('is_admin', help='Client authentication type.')
        c.argument('certificate_issuer_thumbprint',
                   options_list=[
                       '--certificate-issuer-thumbprint', '--cert-issuer-tp'
                   ],
                   help='client certificate issuer thumbprint.')
        c.argument(
            'certificate_common_name',
            options_list=['--certificate-common-name', '--cert-common-name'],
            help='client certificate common name.')
        c.argument(
            'admin_client_thumbprints',
            options_list=['--admin-client-thumbprints', '--admin-client-tps'],
            nargs='+',
            help='client certificate thumbprint that only has admin permission.'
        )
        c.argument(
            'readonly_client_thumbprints',
            options_list=[
                '--readonly-client-thumbprints', '--readonly-client-tps'
            ],
            nargs='+',
            help=
            'Space-separated list of client certificate thumbprint that has read only permission.'
        )

    with self.argument_context('sf cluster client-certificate add') as c:
        c.argument('thumbprint', help='client certificate thumbprint.')

    with self.argument_context('sf cluster client-certificate remove') as c:
        c.argument(
            'thumbprints',
            nargs='+',
            help=
            'A single or Space-separated list of client certificate thumbprint(s) to be remove.'
        )

    with self.argument_context('sf cluster node') as c:
        c.argument('number_of_nodes_to_add',
                   options_list=['--number-of-nodes-to-add', '--nodes-to-add'],
                   help='number of nodes to add.')
        c.argument(
            'number_of_nodes_to_remove',
            options_list=['--number-of-nodes-to-remove', '--nodes-to-remove'],
            help='number of nodes to remove.')

    with self.argument_context('sf cluster node-type') as c:
        c.argument(
            'capacity',
            help=
            'The capacity tag applied to nodes in the node type. The cluster resource manager uses these tags to understand how much capacity a node has.'
        )
        c.argument('vm_tier', help='VM tier.')

    with self.argument_context('sf cluster') as c:
        c.argument('durability_level',
                   arg_type=get_enum_type(['Bronze', 'Silver', 'Gold']),
                   help='durability level.')

    with self.argument_context('sf cluster setting') as c:
        c.argument('parameter', help='parameter name')
        c.argument('section', help='section name')
        c.argument('value', help='Specify the value')
        c.argument('settings_section_description',
                   options_list=[
                       '--settings-section-description', '--settings-section'
                   ],
                   help='Specify the value')

    with self.argument_context('sf cluster upgrade-type set') as c:
        c.argument('version', help='cluster code version')
        c.argument('upgrade_mode',
                   arg_type=get_enum_type(['manual', 'automatic']),
                   help='cluster upgrade mode')

    with self.argument_context('sf cluster reliability') as c:
        c.argument('reliability_level',
                   arg_type=get_enum_type(
                       ['Bronze', 'Silver', 'Gold', 'Platinum']),
                   help='durability level.')
        c.argument(
            'auto_add_node',
            help='Add node count automatically when changing reliability.')

    with self.argument_context('sf cluster setting set') as c:
        c.argument(
            'settings_section_description',
            options_list=[
                '--settings-section-description', '--settings-section'
            ],
            type=get_json_object,
            help=
            'JSON encoded parameters configuration. Use @{file} to load from a file. '
            'For example: [{"section": "NamingService","parameter": "MaxOperationTimeout","value": 1000},{"section": "MaxFileOperationTimeout","parameter": "Max2","value": 1000]'
        )

    with self.argument_context('sf cluster setting remove') as c:
        c.argument(
            'settings_section_description',
            options_list=[
                '--settings-section-description', '--settings-section'
            ],
            type=get_json_object,
            help=
            'JSON encoded parameters configuration. Use @{file} to load from a file. '
            'For example: [{"section": "NamingService","parameter": "MaxOperationTimeout"}]'
        )

    with self.argument_context('sf cluster client-certificate remove') as c:
        c.argument(
            'client_certificate_common_names',
            options_list=[
                '--client-certificate-common-names', '--client-cert-cn'
            ],
            type=get_json_object,
            help=
            'JSON encoded parameters configuration. Use @{file} to load from a file. '
            'For example: [{"certificateCommonName": "test.com","certificateIssuerThumbprint": "22B4AE296B504E512DF880A77A2CAE20200FF922"}]'
        )

    with self.argument_context('sf cluster client-certificate add') as c:
        c.argument(
            'client_certificate_common_names',
            options_list=[
                '--client-certificate-common-names', '--client-cert-cn'
            ],
            type=get_json_object,
            help=
            'JSON encoded parameters configuration. Use @{file} to load from a file. '
            'For example: [{"isAdmin":true, "certificateCommonName": "test.com", '
            '"certificateIssuerThumbprint": "22B4AE296B504E512DF880A77A2CAE20200FF922"}]'
        )

    # application-type
    with self.argument_context('sf application-type') as c:
        c.argument('application_type_name',
                   options_list=['--name', '--application-type-name'],
                   help='Specify the application type name.')

    # application-type version
    with self.argument_context('sf application-type version') as c:
        c.argument('version', arg_type=application_type_version)
        c.argument('package_url', arg_type=package_url)

    # application
    with self.argument_context('sf application') as c:
        c.argument('application_name',
                   options_list=['--name', '--application-name'],
                   help='Specify the application name.')

    with self.argument_context('sf application update',
                               validator=validate_update_application) as c:
        c.argument('application_type_version',
                   arg_type=application_type_version)
        c.argument('application_parameters', arg_type=application_parameters)
        c.argument('minimum_nodes', arg_type=minimum_nodes)
        c.argument('maximum_nodes', arg_type=maximum_nodes)
        c.argument(
            'force_restart',
            arg_type=get_three_state_flag(),
            help=
            'Indicates that the service host restarts even if the upgrade is a configuration-only change.'
        )
        c.argument(
            'service_type_health_policy_map',
            options_list=[
                '--service-type-health-policy-map', '--service-type-policy'
            ],
            help=
            'Specify the map of the health policy to use for different service types as a hash table in the following format: {\"ServiceTypeName\" : \"MaxPercentUnhealthyPartitionsPerService,MaxPercentUnhealthyReplicasPerPartition,MaxPercentUnhealthyServices\"}. For example: @{ \"ServiceTypeName01\" = \"5,10,5\"; \"ServiceTypeName02\" = \"5,5,5\" }'
        )

    with self.argument_context('sf application update',
                               arg_group='Upgrade description') as c:
        c.argument(
            'upgrade_replica_set_check_timeout',
            options_list=[
                '--upgrade-replica-set-check-timeout',
                '--replica-check-timeout', '--rep-check-timeout'
            ],
            help=
            'Specify the maximum time, in seconds, that Service Fabric waits for a service to reconfigure into a safe state, if not already in a safe state, before Service Fabric proceeds with the upgrade.'
        )
        c.argument(
            'failure_action',
            arg_type=get_enum_type(['Rollback', 'Manual']),
            help=
            'Specify the action to take if the monitored upgrade fails. The acceptable values for this parameter are Rollback or Manual.'
        )
        c.argument(
            'health_check_retry_timeout',
            options_list=[
                '--hc-retry-timeout', '--health-check-retry-timeout'
            ],
            help=
            'Specify the duration, in seconds, after which Service Fabric retries the health check if the previous health check fails.'
        )
        c.argument(
            'health_check_wait_duration',
            options_list=[
                '--hc-wait-duration', '--health-check-wait-duration'
            ],
            help=
            'Specify the duration, in seconds, that Service Fabric waits before it performs the initial health check after it finishes the upgrade on the upgrade domain.'
        )
        c.argument(
            'health_check_stable_duration',
            options_list=[
                '--hc-stable-duration', '--health-check-stable-duration'
            ],
            help=
            'Specify the duration, in seconds, that Service Fabric waits in order to verify that the application is stable before moving to the next upgrade domain or completing the upgrade. This wait duration prevents undetected changes of health right after the health check is performed.'
        )
        c.argument(
            'upgrade_domain_timeout',
            options_list=['--ud-timeout', '--upgrade-domain-timeout'],
            help=
            'Specify the maximum time, in seconds, that Service Fabric takes to upgrade a single upgrade domain. After this period, the upgrade fails.'
        )
        c.argument(
            'upgrade_timeout',
            help=
            'Specify the maximum time, in seconds, that Service Fabric takes for the entire upgrade. After this period, the upgrade fails.'
        )
        c.argument(
            'consider_warning_as_error',
            options_list=['--warning-as-error', '--consider-warning-as-error'],
            arg_type=get_three_state_flag(),
            help=
            'Indicates whether to treat a warning health event as an error event during health evaluation.'
        )
        c.argument(
            'default_service_type_max_percent_unhealthy_partitions_per_service',
            options_list=[
                '--max-porcent-unhealthy-partitions', '--max-unhealthy-parts'
            ],
            help=
            'Specify the maximum percent of unhelthy partitions per service allowed by the health policy for the default service type to use for the monitored upgrade. Allowed values are form 0 to 100.'
        )
        c.argument(
            'default_service_type_max_percent_unhealthy_replicas_per_partition',
            options_list=[
                '--max-porcent-unhealthy-replicas', '--max-unhealthy-reps'
            ],
            help=
            'Specify the maximum percent of unhelthy replicas per service allowed by the health policy for the default service type to use for the monitored upgrade. Allowed values are form 0 to 100.'
        )
        c.argument(
            'default_service_type_max_percent_unhealthy_services',
            options_list=[
                '--max-porcent-unhealthy-services', '--max-unhealthy-servs'
            ],
            help=
            'Specify the maximum percent of unhelthy services allowed by the health policy for the default service type to use for the monitored upgrade. Allowed values are form 0 to 100.'
        )
        c.argument(
            'max_percent_unhealthy_deployed_applications',
            options_list=[
                '--max-porcent-unhealthy-apps', '--max-unhealthy-apps'
            ],
            help=
            'Specify the maximum percentage of the application instances deployed on the nodes in the cluster that have a health state of error before the application health state for the cluster is error. Allowed values are form 0 to 100.'
        )

    with self.argument_context('sf application create',
                               validator=validate_create_application) as c:
        c.argument('application_type_name',
                   options_list=['--type-name', '--application-type-name'],
                   help='Specify the application type name.')
        c.argument('application_type_version',
                   arg_type=application_type_version)
        c.argument('package_url', arg_type=package_url)
        c.argument('application_parameters', arg_type=application_parameters)
        c.argument('minimum_nodes', arg_type=minimum_nodes)
        c.argument('maximum_nodes', arg_type=maximum_nodes)

    # service
    with self.argument_context('sf service') as c:
        c.argument(
            'service_name',
            options_list=['--name', '--service-name'],
            help=
            'Specify the name of the service. The application name must be a prefix of the service name, for example: appName~serviceName'
        )

    with self.argument_context('sf service create',
                               validator=validate_create_service) as c:
        c.argument(
            'service_type',
            help=
            'Specify the service type name of the application, it should exist in the application manifest.'
        )
        c.argument(
            'application_name',
            options_list=['--application', '--application-name'],
            help=
            'Specify the name of the service. The application name must be a prefix of the service name, for example: appName~serviceName'
        )
        c.argument('state',
                   arg_type=get_enum_type(['stateless', 'stateful']),
                   help='Specify if the service is stateless or stateful.')
        c.argument(
            'instance_count',
            help=
            'Specify the instance count for the stateless service. If -1 is used, it means it will run on all the nodes.'
        )
        c.argument(
            'min_replica_set_size',
            options_list=['--min-replica-set-size', '--min-replica'],
            help='Specify the min replica set size for the stateful service.')
        c.argument(
            'target_replica_set_size',
            options_list=['--target-replica-set-size', '--target-replica'],
            help='Specify the target replica set size for the stateful service.'
        )
        c.argument(
            'default_move_cost',
            arg_type=get_enum_type(['Zero', 'Low', 'Medium', 'High']),
            help=
            'Specify the default cost for a move. Higher costs make it less likely that the Cluster Resource Manager will move the replica when trying to balance the cluster.'
        )
        c.argument(
            'partition_scheme',
            arg_type=get_enum_type(['singleton', 'uniformInt64', 'named']),
            help='Specify what partition scheme to use. '
            'Singleton partitions are typically used when the service does not require any additional routing. '
            'UniformInt64 means that each partition owns a range of int64 keys. '
            'Named is usually for services with data that can be bucketed, within a bounded set. Some common examples of data fields used as named partition keys would be regions, postal codes, customer groups, or other business boundaries.'
        )

    # managed cluster

    with self.argument_context('sf managed-cluster create',
                               validator=validate_create_managed_cluster) as c:
        c.argument('admin_password',
                   help='Admin password used for the virtual machines.')
        c.argument('admin_user_name',
                   help='Admin user used for the virtual machines.',
                   default='vmadmin')
        c.argument('dns_name', help='Cluster\'s dns name.')
        c.argument(
            'sku',
            help=
            'Cluster\'s Sku, the options are Basic: it will have a minimum of 3 seed nodes and only allows 1 node type and Standard: it will have a minimum of 5 seed nodes and allows multiple node types.',
            default='Basic')
        c.argument('client_connection_port',
                   options_list=['--client-connection-port', '--client-port'],
                   help='Port used for client connections to the cluster.',
                   default=19000)
        c.argument(
            'gateway_connection_port',
            options_list=['--gateway-connection-port', '--gateway-port'],
            help='Port used for http connections to the cluster.',
            default=19080)
        c.argument('client_cert_is_admin',
                   options_list=['--client-cert-is-admin', '--cert-is-admin'],
                   arg_type=get_three_state_flag(),
                   help='Client authentication type.')
        c.argument(
            'client_cert_thumbprint',
            options_list=['--client-cert-thumbprint', '--cert-thumbprint'],
            help='Client certificate thumbprint.')
        c.argument(
            'client_cert_common_name',
            options_list=['--client-cert-common-name', '--cert-common-name'],
            help='Client certificate common name.')
        c.argument('client_cert_issuer_thumbprint',
                   options_list=[
                       '--client-cert-issuer-thumbprint',
                       '--cert-issuer-thumbprint', '--cert-issuer-tp'
                   ],
                   nargs='+',
                   help='Space-separated list of issuer thumbprints.')
        c.argument('tags', arg_type=tags_type)

    with self.argument_context('sf managed-cluster update') as c:
        c.argument('client_connection_port',
                   options_list=['--client-connection-port', '--client-port'],
                   help='Port used for client connections to the cluster.')
        c.argument(
            'gateway_connection_port',
            options_list=['--gateway-connection-port', '--gateway-port'],
            help='Port used for http connections to the cluster.')
        c.argument('dns_name', help='Cluster\'s dns name')
        c.argument('tags', arg_type=tags_type)

    with self.argument_context(
            'sf managed-cluster client-certificate add') as c:
        c.argument('is_admin',
                   arg_type=get_three_state_flag(),
                   help='Client authentication type.')
        c.argument('thumbprint', help='Client certificate thumbprint.')
        c.argument('common_name', help='Client certificate common name.')
        c.argument('issuer_thumbprint',
                   nargs='+',
                   help='Space-separated list of issuer thumbprints.')

    with self.argument_context(
            'sf managed-cluster client-certificate delete') as c:
        c.argument(
            'thumbprint',
            nargs='+',
            help=
            'A single or Space-separated list of client certificate thumbprint(s) to be remove.'
        )
        c.argument(
            'common_name',
            nargs='+',
            help=
            'A single or Space-separated list of client certificate common name(s) to be remove.'
        )

    # managed node type

    capacity = CLIArgumentType(
        options_list=['--capacity'],
        action=AddNodeTypeCapacityAction,
        nargs='+',
        help=
        'Capacity tags applied to the nodes in the node type as key/value pairs, the cluster resource manager uses these tags to understand how much resource a node has. Updating this will override the current values.'
        'for example: --capacity ClientConnections=65536 param2=value2')

    placement_property = CLIArgumentType(
        options_list=['--placement-property'],
        action=AddNodeTypePlacementPropertyAction,
        nargs='+',
        help=
        'Placement tags applied to nodes in the node type as key/value pairs, which can be used to indicate where certain services (workload) should run. Updating this will override the current values.'
        'for example: --placement-property NodeColor=Green SomeProperty=5')

    with self.argument_context('sf managed-node-type') as c:
        c.argument('node_type_name',
                   options_list=['-n', '--name', '--node-type-name'],
                   help='node type name.')
        c.argument('instance_count',
                   help='essage = "The number of nodes in the node type.')
        c.argument(
            'primary',
            arg_type=get_three_state_flag(),
            help=
            'Specify if the node type is primary. On this node type will run system services. Only one node type should be marked as primary. Primary node type cannot be deleted or changed for existing clusters.'
        )
        c.argument('disk_size',
                   help='Disk size for each vm in the node type in GBs.',
                   default=100)
        c.argument(
            'application_start_port',
            options_list=['--application-start-port', '--app-start-port'],
            help='Application start port of a range of ports.')
        c.argument('application_end_port',
                   options_list=['--application-end-port', '--app-end-port'],
                   help='Application End port of a range of ports.')
        c.argument('ephemeral_start_port',
                   help='Ephemeral start port of a range of ports.')
        c.argument('ephemeral_end_port',
                   help='Ephemeral end port of a range of ports.')
        c.argument(
            'vm_size',
            help=
            'The size of virtual machines in the pool. All virtual machines in a pool are the same size.',
            default='Standard_D2')
        c.argument(
            'vm_image_publisher',
            help=
            'The publisher of the Azure Virtual Machines Marketplace image.',
            default='MicrosoftWindowsServer')
        c.argument(
            'vm_image_offer',
            help=
            'The offer type of the Azure Virtual Machines Marketplace image.',
            default='WindowsServer')
        c.argument(
            'vm_image_sku',
            help='The SKU of the Azure Virtual Machines Marketplace image.',
            default='2019-Datacenter')
        c.argument(
            'vm_image_version',
            help=
            'The version of the Azure Virtual Machines Marketplace image. ',
            default='latest')
        c.argument('capacity', arg_type=capacity)
        c.argument('placement_property', arg_type=placement_property)

    with self.argument_context('sf managed-node-type node') as c:
        c.argument('node_name',
                   nargs='+',
                   help='list of target nodes to perform the operation.')
        c.argument(
            'force',
            arg_type=get_three_state_flag(),
            help=
            'Using this flag will force the operation even if service fabric is unable to disable the nodes. Use with caution as this might cause data loss if stateful workloads are running on the node.'
        )

    with self.argument_context('sf managed-node-type vm-extension') as c:
        c.argument('extension_name', help='extension name.')
        c.argument(
            'force_update_tag',
            help=
            'If a value is provided and is different from the previous value, the extension handler will be forced to update even if the extension configuration has not changed.'
        )
        c.argument('publisher',
                   help='The name of the extension handler publisher.')
        c.argument(
            'extension_type',
            help=
            'Specifies the type of the extension; an example is \"CustomScriptExtension\".'
        )
        c.argument('type_handler_version',
                   help='Specifies the version of the script handler.')
        c.argument(
            'auto_upgrade_minor_version',
            options_list=['--auto-upgrade-minor-version', '--auto-upgrade'],
            arg_type=get_three_state_flag(),
            help=
            'Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true.'
        )
        c.argument('setting',
                   help='Json formatted public settings for the extension.')
        c.argument(
            'protected_setting',
            help=
            'The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all.'
        )
        c.argument(
            'provision_after_extension',
            options_list=['--provision-after-extension', '--provision-after'],
            help=
            'Collection of extension names after which this extension needs to be provisioned.'
        )

    with self.argument_context('sf managed-node-type vm-secret') as c:
        c.argument('source_vault_id',
                   help='Key Vault resource id containing the certificates.')
        c.argument(
            'certificate_url',
            help=
            'This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8: <br><br> {<br>  \"data\":\"<Base64-encoded-certificate>\",<br>  \"dataType\":\"pfx\",<br>  \"password\":\"<pfx-file-password>\"<br>}/'
        )
        c.argument(
            'certificate_store',
            help=
            'Specifies the certificate store on the Virtual Machine to which the certificate should be added. The specified certificate store is implicitly in the LocalMachine account.'
        )
Esempio n. 19
0
def load_arguments(self, _):
    from ._completers import storage_account_completion_list, storage_account_key_completion_list
    from knack.arguments import CLIArgumentType
    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:
        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(['standard', 'premium']), arg_group='Cluster',
                   help='The tier of the cluster: standard or premium.')
        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.')
        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.')
        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='Cluster',
                   help='The number of worker nodes in the cluster.')
        c.argument('storage_account', arg_group='Storage', completer=storage_account_completion_list,
                   help='The storage account, e.g. "<name>.blob.core.windows.net".')
        c.argument('storage_account_key', arg_group='Storage', completer=storage_account_key_completion_list,
                   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('virtual_network', arg_group='Network',
                   help='The virtual network resource ID of an existing virtual network.')
        c.argument('subnet_name', arg_group='Network',
                   help='The name of the subnet in the specified virtual network.')
        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.')

    # 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.')
Esempio n. 20
0
def load_arguments(self, _):

    with self.argument_context('sql') as c:
        c.argument('location_name', arg_type=get_location_type(self.cli_ctx))
        c.argument('usage_name', options_list=['--usage', '-u'])
        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)
Esempio n. 21
0
def load_arguments(self, _):

    acr_arg_type = CLIArgumentType(metavar='ACR_NAME_OR_RESOURCE_ID')

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('aks update') as c:
        c.argument('enable_cluster_autoscaler',
                   options_list=["--enable-cluster-autoscaler", "-e"],
                   action='store_true')
        c.argument('disable_cluster_autoscaler',
                   options_list=["--disable-cluster-autoscaler", "-d"],
                   action='store_true')
        c.argument('update_cluster_autoscaler',
                   options_list=["--update-cluster-autoscaler", "-u"],
                   action='store_true')
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('load_balancer_managed_outbound_ip_count', type=int)
        c.argument('load_balancer_outbound_ips',
                   type=str,
                   validator=validate_load_balancer_outbound_ips)
        c.argument('load_balancer_outbound_ip_prefixes',
                   type=str,
                   validator=validate_load_balancer_outbound_ip_prefixes)
        c.argument('load_balancer_outbound_ports',
                   type=int,
                   validator=validate_load_balancer_outbound_ports)
        c.argument('load_balancer_idle_timeout',
                   type=int,
                   validator=validate_load_balancer_idle_timeout)
        c.argument('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)

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

    with self.argument_context('aks enable-addons') as c:
        c.argument('addons', options_list=['--addons', '-a'])
        c.argument(
            'subnet_name',
            options_list=['--subnet-name', '-s'],
            help=
            'Name of an existing subnet to use with the virtual-node add-on.')

    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('path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   default=os.path.join(os.path.expanduser('~'), '.kube',
                                        'config'))

    for scope in ['aks', 'acs kubernetes', 'acs dcos']:
        with self.argument_context('{} install-cli'.format(scope)) as c:
            c.argument('client_version',
                       validator=validate_k8s_client_version,
                       help='Version of the client to install.')
            c.argument('install_location',
                       default=_get_default_install_location('kubectl'),
                       help='Path at which to install kubectl.')

    with self.argument_context('aks install-connector') as c:
        c.argument(
            'aci_resource_group',
            help='The resource group to create the ACI container groups')
        c.argument('chart_url',
                   default=aci_connector_chart_url,
                   help='URL to the chart')
        c.argument(
            'client_secret',
            help=
            'Client secret to use with the service principal for making calls to Azure APIs'
        )
        c.argument('connector_name',
                   default='aci-connector',
                   help='The name for the ACI Connector',
                   validator=validate_connector_name)
        c.argument('image_tag', help='The image tag of the virtual kubelet')
        c.argument('location',
                   help='The location to create the ACI container groups')
        c.argument('os_type',
                   get_enum_type(aci_connector_os_type),
                   help='The OS type of the connector')
        c.argument(
            'service_principal',
            help=
            'Service principal for making calls into Azure APIs. If not set, auto generate a new service principal of Contributor role, and save it locally for reusing'
        )

    with self.argument_context('aks remove-connector') as c:
        c.argument('connector_name',
                   default='aci-connector',
                   help='The name for the ACI Connector',
                   validator=validate_connector_name)
        c.argument(
            'graceful',
            action='store_true',
            help=
            'Mention if you want to drain/uncordon your aci-connector to move your applications'
        )
        c.argument('os_type',
                   get_enum_type(aci_connector_os_type),
                   help='The OS type of the connector')

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

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

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

    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 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(
                'zones',
                zones_type,
                options_list=['--zones', '-z'],
                help=
                'Space-separated list of availability zones where agent nodes will be placed.'
            )
            c.argument('node_vm_size',
                       options_list=['--node-vm-size', '-s'],
                       completer=get_vm_size_completion_list)
            c.argument('max_pods',
                       type=int,
                       options_list=['--max-pods', '-m'],
                       validator=validate_max_pods)
            c.argument('os_type', type=str)
            c.argument('enable_cluster_autoscaler',
                       options_list=["--enable-cluster-autoscaler", "-e"],
                       action='store_true')
            c.argument('node_taints', type=str, validator=validate_taints)

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

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

    with self.argument_context('aks upgrade-connector') as c:
        c.argument('aci_resource_group')
        c.argument('chart_url', default=aci_connector_chart_url)
        c.argument('client_secret')
        c.argument('connector_name',
                   default='aci-connector',
                   validator=validate_connector_name)
        c.argument('image_tag')
        c.argument('location')
        c.argument('os_type', get_enum_type(aci_connector_os_type))
        c.argument('service_principal')

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

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

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

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

    with self.argument_context('openshift monitor enable') as c:
        c.argument(
            'workspace_id',
            help=
            'The resource ID of an existing Log Analytics Workspace to use for storing monitoring data.'
        )
Esempio n. 22
0
def load_arguments(self, _):

    with self.argument_context('spring-cloud') as c:
        c.argument('resource_group', arg_type=resource_group_name_type)
        c.argument('name', options_list=[
            '--name', '-n'], help='Name of Azure Spring Cloud.')

    with self.argument_context('spring-cloud create') as c:
        c.argument('location', arg_type=get_location_type(
            self.cli_ctx), validator=validate_location)

    with self.argument_context('spring-cloud test-endpoint renew-key') as c:
        c.argument('type', type=str, arg_type=get_enum_type(
            TestKeyType), help='Type of test-endpoint key')

    with self.argument_context('spring-cloud app') as c:
        c.argument('service', service_name_type)
        c.argument('name', name_type, help='Name of app.')

    with self.argument_context('spring-cloud app create') as c:
        c.argument(
            'is_public', arg_type=get_three_state_flag(), help='If true, assign public domain', default=False)

    with self.argument_context('spring-cloud app update') as c:
        c.argument('is_public', arg_type=get_three_state_flag(),
                   help='If true, assign public domain')

    for scope in ['spring-cloud app update', 'spring-cloud app start', 'spring-cloud app stop', 'spring-cloud app restart', 'spring-cloud app deploy', 'spring-cloud app scale', 'spring-cloud app set-deployment', 'spring-cloud app show-deploy-log']:
        with self.argument_context(scope) as c:
            c.argument('deployment', options_list=[
                '--deployment', '-d'], help='Name of an existing deployment of the app. Default to the production deployment if not specified.', validator=validate_deployment_name)

    with self.argument_context('spring-cloud app set-deployment') as c:
        c.argument('deployment', options_list=[
            '--deployment', '-d'], help='Name of an existing deployment of the app.', validator=validate_deployment_name)

    for scope in ['spring-cloud app create', 'spring-cloud app update']:
        with self.argument_context(scope) as c:
            c.argument('enable_persistent_storage', arg_type=get_three_state_flag(),
                       help='If true, mount a 50G disk with default path.')

    for scope in ['spring-cloud app update', 'spring-cloud app deployment create', 'spring-cloud app deploy', 'spring-cloud app create']:
        with self.argument_context(scope) as c:
            c.argument('runtime_version', arg_type=get_enum_type(RuntimeVersion),
                       help='Runtime version of used language')
            c.argument('jvm_options', type=str,
                       help="A string containing jvm options, use '=' instead of ' ' for this argument to avoid bash parse error, eg: --jvm-options='-Xms1024m -Xmx2048m'")
            c.argument('env', env_type)

    for scope in ['spring-cloud app create', 'spring-cloud app deployment create']:
        with self.argument_context(scope) as c:
            c.argument('cpu', type=int, default=1,
                       help='Number of virtual cpu cores per instance.')
            c.argument('memory', type=int, default=1,
                       help='Number of GB of memory per instance.')
            c.argument('instance_count', type=int,
                       default=1, help='Number of instance.')

    for scope in ['spring-cloud app deploy', 'spring-cloud app scale']:
        with self.argument_context(scope) as c:
            c.argument('cpu', type=int,
                       help='Number of virtual cpu cores per instance.', validator=validate_nodes_count)
            c.argument('memory', type=int,
                       help='Number of GB of memory per instance.', validator=validate_nodes_count)
            c.argument('instance_count', type=int,
                       help='Number of instance.', validator=validate_nodes_count)

    for scope in ['spring-cloud app deploy', 'spring-cloud app deployment create']:
        with self.argument_context(scope) as c:
            c.argument(
                'jar_path', help='If provided, deploy jar, otherwise deploy current folder as tar.')
            c.argument(
                'target_module', help='Child module to be deployed, required for multiple jar packages built from source code')
            c.argument(
                'version', help='Deployment version, keep unchanged if not set.')

    with self.argument_context('spring-cloud app deployment create') as c:
        c.argument('skip_clone_settings', help='Create staging deployment will automatically copy settings from production deployment.',
                   action='store_true')

    with self.argument_context('spring-cloud app deployment') as c:
        c.argument('app', app_name_type, help='Name of app.',
                   validator=validate_app_name)
        c.argument('name', name_type, help='Name of deployment.')

    with self.argument_context('spring-cloud app binding') as c:
        c.argument('app', app_name_type, help='Name of app.',
                   validator=validate_app_name)
        c.argument('name', name_type, help='Name of service binding.')

    for scope in ['spring-cloud app binding cosmos add', 'spring-cloud app binding mysql add', 'spring-cloud app binding redis add']:
        with self.argument_context(scope) as c:
            c.argument('resource_id', validator=validate_resource_id,
                       help='Azure resource ID of the service to bind with.')

    for scope in ['spring-cloud app binding cosmos add', 'spring-cloud app binding cosmos update']:
        with self.argument_context(scope) as c:
            c.argument(
                'database_name', help='Name of database. Required for mongo, sql, gremlin')
            c.argument(
                'key_space', help='Cassandra key space. Required for cassandra')
            c.argument('collection_name',
                       help='Name of collection. Required for gremlin')

    with self.argument_context('spring-cloud app binding cosmos add') as c:
        c.argument('api_type', help='Type of API.', arg_type=get_enum_type(
            ApiType), validator=validate_cosmos_type)

    for scope in ['spring-cloud app binding mysql add', 'spring-cloud app binding mysql update']:
        with self.argument_context(scope) as c:
            c.argument('key', help='API key of the service.')
            c.argument('username', help='Username of the database')
            c.argument('database_name', help='Database name')

    for scope in ['spring-cloud app binding redis add', 'spring-cloud app binding redis update']:
        with self.argument_context(scope) as c:
            c.argument('key', help='Api key of the service.')
            c.argument('disable_ssl', action='store_true',
                       help='Disable SSL.')

    with self.argument_context('spring-cloud config-server set') as c:
        c.argument('config_file',
                   help='A yaml file path for the configuration of Spring Cloud config server')

    for scope in ['spring-cloud config-server git set', 'spring-cloud config-server git repo add', 'spring-cloud config-server git repo update']:
        with self.argument_context(scope) as c:
            c.argument('uri', help='Uri of the added config.')
            c.argument('label', help='Label of the added config.')
            c.argument(
                'search_paths', help='search_paths of the added config, use , as delimiter for multiple paths.')
            c.argument('username', help='Username of the added config.')
            c.argument('password', help='Password of the added config.')
            c.argument('host_key', help='Host key of the added config.')
            c.argument('host_key_algorithm',
                       help='Host key algorithm of the added config.')
            c.argument('private_key', help='Private_key of the added config.')
            c.argument('strict_host_key_checking',
                       help='Strict_host_key_checking of the added config.')

    for scope in ['spring-cloud config-server git repo add', 'spring-cloud config-server git repo update', 'spring-cloud config-server git repo remove']:
        with self.argument_context(scope) as c:
            c.argument('repo_name', help='Uri of the repo.')

    for scope in ['spring-cloud config-server git repo add', 'spring-cloud config-server git repo update']:
        with self.argument_context(scope) as c:
            c.argument(
                'pattern', help='Pattern of the repo, use , as delimiter for multiple patterns')

    with self.argument_context('spring-cloud test-endpoint list') as c:
        c.argument('app', app_name_type, help='Name of app.',
                   validator=validate_app_name)
        c.argument('deployment', options_list=[
            '--deployment', '-d'], help='Name of an existing deployment of the app. Default to the production deployment if not specified.', validator=validate_deployment_name)
Esempio n. 23
0
def load_arguments(self, _):
    with self.argument_context('healthcareapis create') as c:
        c.argument('resource_group', resource_group_name_type)
        c.argument('name',
                   id_part=None,
                   help='The name of the service instance.')
        c.argument('kind',
                   arg_type=get_enum_type(['fhir', 'fhir-Stu3', 'fhir-R4']),
                   id_part=None,
                   help='The kind of the service.')
        c.argument('location', arg_type=get_location_type(self.cli_ctx))
        c.argument('tags', tags_type)
        c.argument(
            'etag',
            id_part=None,
            help=
            'An etag associated with the resource, used for optimistic concurrency when editing it.'
        )
        c.argument(
            'access_policies_object_id',
            id_part=None,
            help=
            'An Azure AD object ID (User or Apps) that is allowed access to the FHIR service.'
        )
        c.argument('cosmos_db_offer_throughput',
                   id_part=None,
                   help='The provisioned throughput for the backing database.')
        c.argument('authentication_authority',
                   id_part=None,
                   help='The authority url for the service')
        c.argument('authentication_audience',
                   id_part=None,
                   help='The audience url for the service')
        c.argument('authentication_smart_proxy_enabled',
                   arg_type=get_three_state_flag(),
                   id_part=None,
                   help='If the SMART on FHIR proxy is enabled')
        c.argument('cors_origins',
                   id_part=None,
                   help='The origins to be allowed via CORS.')
        c.argument('cors_headers',
                   id_part=None,
                   help='The headers to be allowed via CORS.')
        c.argument('cors_methods',
                   id_part=None,
                   help='The methods to be allowed via CORS.')
        c.argument('cors_max_age',
                   id_part=None,
                   help='The max age to be allowed via CORS.')
        c.argument('cors_allow_credentials',
                   arg_type=get_three_state_flag(),
                   id_part=None,
                   help='If credentials are allowed via CORS.')

    with self.argument_context('healthcareapis update') as c:
        c.argument('resource_group', resource_group_name_type)
        c.argument('name',
                   id_part=None,
                   help='The name of the service instance.')
        c.argument('kind',
                   arg_type=get_enum_type(['fhir', 'fhir-Stu3', 'fhir-R4']),
                   id_part=None,
                   help='The kind of the service.')
        c.argument('location', arg_type=get_location_type(self.cli_ctx))
        c.argument('tags', tags_type)
        c.argument(
            'etag',
            id_part=None,
            help=
            'An etag associated with the resource, used for optimistic concurrency when editing it.'
        )
        c.argument(
            'access_policies_object_id',
            id_part=None,
            help=
            'An Azure AD object ID (User or Apps) that is allowed access to the FHIR service.'
        )
        c.argument('cosmos_db_offer_throughput',
                   id_part=None,
                   help='The provisioned throughput for the backing database.')
        c.argument('authentication_authority',
                   id_part=None,
                   help='The authority url for the service')
        c.argument('authentication_audience',
                   id_part=None,
                   help='The audience url for the service')
        c.argument('authentication_smart_proxy_enabled',
                   arg_type=get_three_state_flag(),
                   id_part=None,
                   help='If the SMART on FHIR proxy is enabled')
        c.argument('cors_origins',
                   id_part=None,
                   help='The origins to be allowed via CORS.')
        c.argument('cors_headers',
                   id_part=None,
                   help='The headers to be allowed via CORS.')
        c.argument('cors_methods',
                   id_part=None,
                   help='The methods to be allowed via CORS.')
        c.argument('cors_max_age',
                   id_part=None,
                   help='The max age to be allowed via CORS.')
        c.argument('cors_allow_credentials',
                   arg_type=get_three_state_flag(),
                   id_part=None,
                   help='If credentials are allowed via CORS.')

    with self.argument_context('healthcareapis delete') as c:
        c.argument('resource_group', resource_group_name_type)
        c.argument('name',
                   id_part=None,
                   help='The name of the service instance.')

    with self.argument_context('healthcareapis list') as c:
        c.argument('resource_group', resource_group_name_type)

    with self.argument_context('healthcareapis show') as c:
        c.argument('resource_group', resource_group_name_type)
        c.argument('name',
                   id_part=None,
                   help='The name of the service instance.')
Esempio n. 24
0
def load_arguments(self, _):
    with self.argument_context('container') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('container_group_name',
                   options_list=['--name', '-n'],
                   help="The name of the container group.")
        c.argument('name',
                   options_list=['--name', '-n'],
                   help="The name of the container group",
                   id_part='name')
        c.argument('location', arg_type=get_location_type(self.cli_ctx))

    with self.argument_context('container create') as c:
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('image',
                   validator=validate_image,
                   help='The container image name')
        c.argument(
            'cpu',
            type=int,
            help=
            'The required number of CPU cores of the containers, accurate to one decimal place'
        )
        c.argument(
            'memory',
            type=float,
            help=
            'The required memory of the containers in GB, accurate to one decimal place'
        )
        c.argument('os_type',
                   arg_type=get_enum_type(OperatingSystemTypes),
                   help='The OS type of the containers')
        c.argument('ip_address',
                   arg_type=get_enum_type(IP_ADDRESS_TYPES),
                   help='The IP address type of the container group')
        c.argument('ports',
                   type=int,
                   nargs='+',
                   default=[80],
                   help='The ports to open')
        c.argument('protocol',
                   arg_type=get_enum_type(ContainerNetworkProtocol),
                   help='The network protocol to use')
        c.argument(
            'dns_name_label',
            help='The dns name label for container group with public IP')
        c.argument(
            'restart_policy',
            arg_type=get_enum_type(ContainerGroupRestartPolicy),
            help='Restart policy for all containers within the container group'
        )
        c.argument(
            'command_line',
            help=
            'The command line to run when the container is started, e.g. \'/bin/bash -c myscript.sh\''
        )
        c.argument(
            'environment_variables',
            nargs='+',
            options_list=['--environment-variables', '-e'],
            type=_environment_variables_type,
            help=
            'A list of environment variable for the container. Space-separated values in \'key=value\' format.'
        )
        c.argument(
            'secure_environment_variables',
            nargs='+',
            type=_secure_environment_variables_type,
            help=
            'A list of secure environment variable for the container. Space-separated values in \'key=value\' format.'
        )
        c.argument('secrets', secrets_type)
        c.argument(
            'secrets_mount_path',
            validator=validate_volume_mount_path,
            help=
            "The path within the container where the secrets volume should be mounted. Must not contain colon ':'."
        )
        c.argument('file',
                   options_list=['--file', '-f'],
                   help="The path to the input file.")

    with self.argument_context('container create',
                               arg_group='Managed Service Identity') as c:
        c.argument(
            'assign_identity',
            nargs='*',
            validator=validate_msi,
            help=
            "Space-separated list of assigned identities. Assigned identities are either user assigned identities (resource IDs) and / or the system assigned identity ('[system]'). See examples for more info."
        )
        c.argument('identity_scope',
                   options_list=['--scope'],
                   help="Scope that the system assigned identity can access")
        c.argument(
            'identity_role',
            options_list=['--role'],
            help="Role name or id the system assigned identity will have")

    with self.argument_context('container create', arg_group='Network') as c:
        c.argument('network_profile', network_profile_type)
        c.argument(
            'vnet',
            help=
            'The name of the VNET when creating a new one or referencing an existing one. Can also reference an existing vnet by ID. This allows using vnets from other resource groups.'
        )
        c.argument(
            'vnet_name',
            help=
            'The name of the VNET when creating a new one or referencing an existing one.',
            deprecate_info=c.deprecate(redirect="--vnet", hide="0.3.5"))
        c.argument(
            'vnet_address_prefix',
            help=
            'The IP address prefix to use when creating a new VNET in CIDR format.'
        )
        c.argument(
            'subnet',
            options_list=['--subnet'],
            validator=validate_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.'
        )
        c.argument(
            'subnet_address_prefix',
            help=
            'The subnet IP address prefix to use when creating a new VNET in CIDR format.'
        )

    with self.argument_context('container create',
                               arg_group='Image Registry') as c:
        c.argument('registry_login_server',
                   help='The container image registry login server')
        c.argument(
            'registry_username',
            help='The username to log in container image registry server')
        c.argument(
            'registry_password',
            help='The password to log in container image registry server')

    with self.argument_context('container create',
                               arg_group='Azure File Volume') as c:
        c.argument(
            'azure_file_volume_share_name',
            help='The name of the Azure File share to be mounted as a volume')
        c.argument(
            'azure_file_volume_account_name',
            help=
            'The name of the storage account that contains the Azure File share'
        )
        c.argument(
            'azure_file_volume_account_key',
            help=
            'The storage account access key used to access the Azure File share'
        )
        c.argument(
            'azure_file_volume_mount_path',
            validator=validate_volume_mount_path,
            help=
            "The path within the container where the azure file volume should be mounted. Must not contain colon ':'."
        )

    with self.argument_context('container create',
                               arg_group='Log Analytics') as c:
        c.argument(
            'log_analytics_workspace',
            help=
            'The Log Analytics workspace name or id. Use the current subscription or use --subscription flag to set the desired subscription.'
        )
        c.argument('log_analytics_workspace_key',
                   help='The Log Analytics workspace key.')

    with self.argument_context('container create',
                               arg_group='Git Repo Volume') as c:
        c.argument(
            'gitrepo_url',
            help='The URL of a git repository to be mounted as a volume')
        c.argument(
            'gitrepo_dir',
            validator=validate_gitrepo_directory,
            help=
            "The target directory path in the git repository. Must not contain '..'."
        )
        c.argument('gitrepo_revision',
                   help='The commit hash for the specified revision')
        c.argument(
            'gitrepo_mount_path',
            validator=validate_volume_mount_path,
            help=
            "The path within the container where the git repo volume should be mounted. Must not contain colon ':'."
        )

    with self.argument_context('container logs') as c:
        c.argument(
            'container_name',
            help=
            'The container name to tail the logs. If omitted, the first container in the container group will be chosen'
        )
        c.argument('follow',
                   help='Indicate to stream the tailing logs',
                   action='store_true')

    with self.argument_context('container export') as c:
        c.argument('file',
                   options_list=['--file', '-f'],
                   help="The file path to export the container group.")

    with self.argument_context('container exec') as c:
        c.argument(
            'container_name',
            help=
            'The container name where to execute the command. Can be ommitted for container groups with only one container.'
        )
        c.argument('exec_command',
                   help='The command to run from within the container')
        c.argument('terminal_row_size',
                   help='The row size for the command output')
        c.argument('terminal_col_size',
                   help='The col size for the command output')

    with self.argument_context('container attach') as c:
        c.argument(
            'container_name',
            help=
            'The container to attach to. If omitted, the first container in the container group will be chosen'
        )
Esempio n. 25
0
def load_arguments(self, _):
    (JsonWebKeyOperation, KeyAttributes, JsonWebKeyType, JsonWebKeyCurveName,
     SasTokenType, SasDefinitionAttributes, SecretAttributes,
     CertificateAttributes, StorageAccountAttributes,
     JsonWebKeyEncryptionAlgorithm) = self.get_models(
         'JsonWebKeyOperation',
         'KeyAttributes',
         'JsonWebKeyType',
         'JsonWebKeyCurveName',
         'SasTokenType',
         'SasDefinitionAttributes',
         'SecretAttributes',
         'CertificateAttributes',
         'StorageAccountAttributes',
         'JsonWebKeyEncryptionAlgorithm',
         resource_type=ResourceType.DATA_KEYVAULT)

    class CLIJsonWebKeyOperation(str, Enum):
        encrypt = "encrypt"
        decrypt = "decrypt"
        sign = "sign"
        verify = "verify"
        wrap_key = "wrapKey"
        unwrap_key = "unwrapKey"
        import_ = "import"

    JsonWebKeyOperation = CLIJsonWebKeyOperation  # TODO: Remove this patch when new SDK is released

    (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())
        c.argument('enabled_for_disk_encryption',
                   arg_type=get_three_state_flag())
        c.argument('enabled_for_template_deployment',
                   arg_type=get_three_state_flag())
        c.argument('enable_rbac_authorization',
                   arg_type=get_three_state_flag(),
                   is_preview=True)
        c.argument('enable_soft_delete',
                   arg_type=get_three_state_flag(),
                   deprecate_info=c.deprecate(expiration='2.11.0',
                                              hide='2.11.0'))
        c.argument('enable_purge_protection', arg_type=get_three_state_flag())

    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)
        c.argument(
            'retention_days',
            help='Soft delete data retention days. It accepts >=7 and <=90.',
            default='90')

    with self.argument_context('keyvault create',
                               arg_group='Network Rule') as c:
        c.argument(
            'network_acls',
            type=validate_file_or_dict,
            help=
            'Network ACLs. It accepts a JSON filename or a JSON string. JSON format: '
            '`{\\"ip\\":[<ip1>, <ip2>...],\\"vnet\\":[<vnet_name_1>/<subnet_name_1>,<subnet_id2>...]}`'
        )
        c.argument(
            'network_acls_ips',
            nargs='*',
            help='Network ACLs IP rules. Space-separated list of IP addresses.'
        )
        c.argument('network_acls_vnets',
                   nargs='*',
                   help='Network ACLS VNet rules. Space-separated list of '
                   'Vnet/subnet pairs or subnet resource ids.')

    with self.argument_context('keyvault update') as c:
        c.argument('enable_soft_delete',
                   arg_type=get_three_state_flag(),
                   deprecate_info=c.deprecate(expiration='2.11.0',
                                              hide='2.11.0'))
        c.argument(
            'retention_days',
            help='Soft delete data retention days. It accepts >=7 and <=90.')

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

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

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

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

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

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

    for item in ['approve', 'reject', 'delete', 'show', 'wait']:
        with self.argument_context(
                'keyvault private-endpoint-connection {}'.format(item),
                min_api='2018-02-14') as c:
            c.extra(
                'connection_id',
                options_list=['--id'],
                required=False,
                help=
                'The ID of the private endpoint connection associated with the Key Vault. '
                'If specified --vault-name and --name/-n, this should be omitted.'
            )
            c.argument('description',
                       help='Comments for the {} operation.'.format(item))
            c.argument(
                'private_endpoint_connection_name',
                options_list=['--name', '-n'],
                required=False,
                help=
                'The name of the private endpoint connection associated with the Key Vault. '
                'Required if --id is not specified')
            c.argument(
                'vault_name',
                vault_name_type,
                required=False,
                help='Name of the Key Vault. Required if --id is not specified'
            )

    with self.argument_context('keyvault private-link-resource',
                               min_api='2018-02-14') as c:
        c.argument('vault_name',
                   vault_name_type,
                   help='Name of the Key Vault.')
    # 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', 'decrypt', 'delete', 'download', 'encrypt',
                'list-versions', 'set-attributes', 'show'
        ]:
            with self.argument_context('keyvault {} {}'.format(item, cmd),
                                       arg_group='Id') as c:
                try:
                    c.extra(
                        'identifier',
                        options_list=['--id'],
                        help=
                        'Id of the {}. If specified all other \'Id\' arguments should be omitted.'
                        .format(item),
                        validator=validate_vault_id(item))
                except ValueError:
                    pass
                c.argument(
                    item + '_name',
                    help='Name of the {}. Required if --id is not specified.'.
                    format(item),
                    required=False)
                c.argument(
                    'vault_base_url',
                    help=
                    'Name of the key vault. Required if --id is not specified.',
                    required=False)
                c.argument(item + '_version', required=False)

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

        for cmd in ['list', 'list-deleted']:
            with self.argument_context('keyvault {} {}'.format(item,
                                                               cmd)) as c:
                c.argument('include_pending', arg_type=get_three_state_flag())
    # endregion

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

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

    with self.argument_context('keyvault key create') as c:
        c.argument(
            'kty',
            arg_type=get_enum_type(JsonWebKeyType),
            validator=validate_key_type,
            help=
            'The type of key to create. For valid values, see: https://docs.microsoft.com/en-us/rest/api/keyvault/createkey/createkey#jsonwebkeytype'
        )
        c.argument(
            'curve',
            arg_type=get_enum_type(JsonWebKeyCurveName),
            help=
            'Elliptic curve name. For valid values, see: https://docs.microsoft.com/en-us/rest/api/keyvault/createkey/createkey#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_string',
                   type=file_type,
                   help='PEM string containing the key to be imported.',
                   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(),
            validator=validate_key_import_source)
        c.argument(
            'byok_string',
            type=file_type,
            help=
            'BYOK string containing the key to be imported. Must not be password protected.',
            validator=validate_key_import_source)

    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 download') as c:
        c.argument('file_path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   help='File to receive the key contents.')
        c.argument('encoding',
                   arg_type=get_enum_type(key_format_values),
                   options_list=['--encoding', '-e'],
                   help='Encoding of the key, default: PEM',
                   default='PEM')

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

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

    for scope in ['encrypt', 'decrypt']:
        with self.argument_context('keyvault key {}'.format(scope)) as c:
            c.argument('algorithm',
                       options_list=['--algorithm', '-a'],
                       arg_type=get_enum_type(JsonWebKeyEncryptionAlgorithm))

    with self.argument_context('keyvault key encrypt') as c:
        c.argument(
            'value',
            help=
            'The value to be encrypted. Default data type is Base64 encoded string.',
            validator=validate_encryption)
        c.extra('data_type',
                help='The type of the original data.',
                arg_type=get_enum_type(KeyEncryptionDataType),
                default='base64')

    with self.argument_context('keyvault key decrypt') as c:
        c.argument(
            'value',
            help=
            'The value to be decrypted, which should be the result of "az keyvault encrypt"',
            validator=validate_decryption)
        c.extra('data_type',
                help='The type of the original data.',
                arg_type=get_enum_type(KeyEncryptionDataType),
                default='base64')

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

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

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

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

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

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

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

    # endregion

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('keyvault certificate issuer',
                               arg_group='Organization Detail') as c:
        c.argument('organization_id')
        c.argument('admin_first_name')
        c.argument('admin_last_name')
        c.argument('admin_email')
        c.argument('admin_phone')

    for scope in ['list', 'list-deleted', 'list-versions']:
        with self.argument_context(
                'keyvault certificate {}'.format(scope)) as c:
            c.argument('maxresults', options_list=['--maxresults'], type=int)
Esempio n. 26
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 device method result.",
        )
        context.argument(
            "method_connect_timeout",
            options_list=["--method-connect-timeout", "--mct"],
            type=int,
            help="Maximum number of seconds to wait on device connection.",
        )
        context.argument(
            "method_response_timeout",
            options_list=["--method-response-timeout", "--mrt"],
            type=int,
            help="Maximum number of seconds to wait for device 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",
        )
        context.argument(
            "repo_endpoint",
            options_list=["--endpoint", "-e"],
            help="IoT Plug and Play endpoint.",
        )
        context.argument(
            "repo_id",
            options_list=["--repo-id", "-r"],
            help="IoT Plug and Play repository Id.",
        )
        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(
            "content_type",
            options_list=["--content-type", "--ct"],
            help=
            "Specify the Content-Type of the message payload to automatically format the output to that type.",
        )
        context.argument(
            "device_query",
            options_list=["--device-query", "-q"],
            help="Specify a custom query to filter devices.",
        )
        context.argument(
            "edge_enabled",
            options_list=["--edge-enabled", "--ee"],
            arg_type=get_three_state_flag(),
            help="Flag indicating edge enablement.",
        )

    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",
        )
        context.argument("tags",
                         arg_group="Twin Patch",
                         options_list=["--tags"],
                         help="Twin tags.")
        context.argument(
            "desired",
            arg_group="Twin Patch",
            options_list=["--desired"],
            help="Twin desired properties.",
        )

    with self.argument_context("iot hub connection-string") as context:
        context.argument("show_all",
                         options_list=["--show-all", "--all"],
                         help="Allow to show all shared access policies.")
        context.argument(
            "default_eventhub",
            arg_type=get_three_state_flag(),
            options_list=["--default-eventhub", "--eh"],
            help=
            "Flag indicating the connection string returned is for the default EventHub endpoint. Default: false"
        )

    with self.argument_context("iot hub job") as context:
        context.argument("job_id",
                         options_list=["--job-id"],
                         help="IoT Hub job Id.")
        context.argument(
            "job_status",
            options_list=["--job-status", "--js"],
            help="The status of a scheduled job.",
            arg_type=get_enum_type(JobStatusType),
        )
        context.argument(
            "job_type",
            options_list=["--job-type", "--jt"],
            help="The type of scheduled job.",
            arg_type=get_enum_type(JobType),
        )
        context.argument(
            "query_condition",
            options_list=["--query-condition", "-q"],
            help=
            "Condition for device query to get devices to execute the job on. "
            "Required if job type is scheduleDeviceMethod or scheduleUpdateTwin. "
            'Note: The service will prefix "SELECT * FROM devices WHERE " to the input',
        )
        context.argument(
            "start_time",
            options_list=["--start-time", "--start"],
            help="The scheduled start of the job in ISO 8601 date time format. "
            "If no start time is provided, the job is queued for asap execution.",
        )
        context.argument(
            "ttl",
            options_list=["--ttl"],
            type=int,
            help="Max execution time in seconds, before job is terminated.",
        )
        context.argument(
            "twin_patch",
            options_list=["--twin-patch", "--patch"],
            help="The desired twin patch. Provide file path or raw json.",
        )
        context.argument(
            "wait",
            options_list=["--wait", "-w"],
            arg_type=get_three_state_flag(),
            help=
            "Block until the created job is in a completed, failed or cancelled state. "
            "Will regularly poll on interval specified by --poll-interval.",
        )
        context.argument(
            "poll_interval",
            options_list=["--poll-interval", "--interval"],
            type=int,
            help=
            "Interval in seconds that job status will be checked if --wait flag is passed in.",
        )
        context.argument(
            "poll_duration",
            options_list=["--poll-duration", "--duration"],
            type=int,
            help=
            "Total duration in seconds where job status will be checked if --wait flag is passed in.",
        )

    with self.argument_context("iot hub job create") as context:
        context.argument(
            "job_type",
            options_list=["--job-type", "--jt"],
            help="The type of scheduled job.",
            arg_type=get_enum_type(JobCreateType),
        )

    with self.argument_context("iot hub monitor-events") as context:
        context.argument("timeout", arg_type=event_timeout_type)
        context.argument("properties", arg_type=event_msg_prop_type)
        context.argument(
            "interface",
            options_list=["--interface", "-i"],
            help=
            "Target interface identifier to filter on. For example: dtmi:com:example:TemperatureController;1",
        )

    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(
            "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 create") as context:
        context.argument(
            "force",
            options_list=["--force", "-f"],
            help="Overwrites the non-edge device's parent device.",
        )
        context.argument(
            "set_parent_id",
            options_list=["--set-parent", "--pd"],
            help="Id of edge device.",
        )
        context.argument(
            "add_children",
            options_list=["--add-children", "--cl"],
            help=
            "Child device list (comma separated) includes only non-edge devices.",
        )

    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, read, and delete access to "
            "a blob container. This is used to output the status of the "
            "job and the results. Note: when using Identity-based authentication an "
            "https:// URI is still required. Input for this argument can be inline or from a file path.",
        )
        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.",
        )
        context.argument(
            "storage_authentication_type",
            options_list=["--auth-type", "--storage-authentication-type"],
            arg_type=get_enum_type(AuthenticationType),
            help=
            "Authentication type for communicating with the storage container.",
        )

    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. Note: when using Identity-based authentication "
            "an https:// URI is still required. Input for this argument can be inline "
            "or from a file path.",
        )
        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. Note: when using Identity-based "
            "authentication an https:// URI is still required. Input for "
            "this argument can be inline or from a file path.",
        )
        context.argument(
            "storage_authentication_type",
            options_list=["--auth-type", "--storage-authentication-type"],
            arg_type=get_enum_type(AuthenticationType),
            help=
            "Authentication type for communicating with the storage container.",
        )

    with self.argument_context(
            "iot hub device-identity get-parent") as context:
        context.argument("device_id", help="Id of non-edge device.")

    with self.argument_context(
            "iot hub device-identity set-parent") as context:
        context.argument("device_id", help="Id of non-edge device.")
        context.argument(
            "parent_id",
            options_list=["--parent-device-id", "--pd"],
            help="Id of edge device.",
        )
        context.argument(
            "force",
            options_list=["--force", "-f"],
            help="Overwrites the non-edge device's parent device.",
        )

    with self.argument_context(
            "iot hub device-identity add-children") as context:
        context.argument("device_id", help="Id of edge device.")
        context.argument(
            "child_list",
            options_list=["--child-list", "--cl"],
            help=
            "Child device list (comma separated) includes only non-edge devices.",
        )
        context.argument(
            "force",
            options_list=["--force", "-f"],
            help="Overwrites the non-edge device's parent device.",
        )

    with self.argument_context(
            "iot hub device-identity remove-children") as context:
        context.argument("device_id", help="Id of edge device.")
        context.argument(
            "child_list",
            options_list=["--child-list", "--cl"],
            help=
            "Child device list (comma separated) includes only non-edge devices.",
        )
        context.argument(
            "remove_all",
            options_list=["--remove-all", "-a"],
            help="To remove all children.",
        )

    with self.argument_context(
            "iot hub distributed-tracing update") as context:
        context.argument(
            "sampling_mode",
            options_list=["--sampling-mode", "--sm"],
            help=
            "Turns sampling for distributed tracing on and off. 1 is On and, 2 is Off.",
            arg_type=get_enum_type(DistributedTracingSamplingModeType),
        )
        context.argument(
            "sampling_rate",
            options_list=["--sampling-rate", "--sr"],
            help=
            "Controls the amount of messages sampled for adding trace context. This value is"
            "a percentage. Only values from 0 to 100 (inclusive) are permitted.",
        )

    with self.argument_context(
            "iot hub device-identity list-children") as context:
        context.argument("device_id", help="Id of edge device.")

    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", "-p"],
            help=info_param_properties_device(),
        )
        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",
        )
        context.argument("qos", arg_type=qos_type)

    with self.argument_context("iot device simulate") as context:
        context.argument(
            "properties",
            options_list=["--properties", "--props", "-p"],
            help=info_param_properties_device(include_http=True),
        )

    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="The correlation Id associated with the C2D message.",
        )
        context.argument(
            "properties",
            options_list=["--properties", "--props", "-p"],
            help=info_param_properties_device(include_mqtt=False),
        )
        context.argument(
            "expiry_time_utc",
            options_list=["--expiry-time-utc", "--expiry"],
            type=int,
            help="Units are milliseconds since unix epoch. "
            "If no time is indicated the default IoT Hub C2D message TTL is used.",
        )
        context.argument(
            "message_id",
            options_list=["--message-id", "--mid"],
            help=
            "The C2D message Id. If no message Id is provided a UUID will be generated.",
        )
        context.argument(
            "user_id",
            options_list=["--user-id", "--uid"],
            help="The C2D message, user Id property.",
        )
        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.",
        )
        context.argument(
            "content_type",
            options_list=["--content-type", "--ct"],
            help="The content type associated with the C2D message.",
        )
        context.argument(
            "content_encoding",
            options_list=["--content-encoding", "--ce"],
            help="The content encoding associated with the C2D message.",
        )

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

    with self.argument_context("iot hub configuration") as context:
        context.argument(
            "config_id",
            options_list=["--config-id", "-c"],
            help="Target device configuration name.",
        )
        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"],
            help="Target deployment name.",
        )
        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.",
        )
        context.argument(
            "layered",
            options_list=["--layered"],
            arg_type=get_three_state_flag(),
            help=
            "Layered deployments allow you to define desired properties in $edgeAgent, $edgeHub and user "
            "modules that will layer on top of a base deployment. For example the routes specified in a layered "
            "deployment will merge with routes of the base deployment. Routes with the same name will be "
            "overwritten based on deployment priority.",
        )

    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.",
        )
        context.argument(
            "webhook_url",
            options_list=["--webhook-url", "--wh"],
            help="The webhook URL used for custom allocation requests.",
        )
        context.argument(
            "api_version",
            options_list=["--api-version", "--av"],
            help=
            "The API version of the provisioning service types sent in the custom allocation"
            " request. Minimum supported version: 2018-09-01-preview.")

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

    with self.argument_context("iot dt") as context:
        context.argument(
            "repo_login",
            options_list=["--repo-login", "--rl"],
            help=
            "This command supports an entity connection string with rights to perform action. "
            "Use to avoid PnP endpoint and repository name if repository is private. "
            "If both an entity connection string and name are provided the connection string takes priority.",
        )
        context.argument(
            "interface",
            options_list=["--interface", "-i"],
            help=
            "Target interface name. This should be the name of the interface not the urn-id.",
        )
        context.argument(
            "command_name",
            options_list=["--command-name", "--cn"],
            help="IoT Plug and Play interface command name.",
        )
        context.argument(
            "command_payload",
            options_list=["--command-payload", "--cp", "--cv"],
            help="IoT Plug and Play interface command payload. "
            "Content can be directly input or extracted from a file path.",
        )
        context.argument(
            "interface_payload",
            options_list=["--interface-payload", "--ip", "--iv"],
            help="IoT Plug and Play interface payload. "
            "Content can be directly input or extracted from a file path.",
        )
        context.argument(
            "source_model",
            options_list=["--source", "-s"],
            help=
            "Choose your option to get model definition from specified source. ",
            arg_type=get_enum_type(ModelSourceType),
        )
        context.argument(
            "schema",
            options_list=["--schema"],
            help="Show interface with entity schema.",
        )

    with self.argument_context("iot dt monitor-events") as context:
        context.argument("timeout", arg_type=event_timeout_type)
        context.argument("properties", arg_type=event_msg_prop_type)
Esempio n. 27
0
def load_arguments(self, _):

    with self.argument_context('blueprint',
                               validator=blueprint_validator) as c:
        c.ignore(
            'scope')  # scope is divided into management_group and subscription
        c.ignore('_subscription')  # ignore the global subscription param
        c.argument('subscription', arg_type=subscription_type)
        c.argument('management_group', arg_type=management_group_type)

    with self.argument_context('blueprint create') as c:
        c.argument('blueprint_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint definition.')
        c.argument('display_name',
                   help='One-liner string explain this resource.')
        c.argument('description', help='Multi-line explain this resource.')
        c.argument(
            'target_scope',
            arg_type=get_enum_type(BlueprintTargetScope),
            default='subscription',
            help='The scope where this blueprint definition can be assigned.')
        c.argument(
            'parameters',
            arg_type=parameter_type,
            help=
            'Parameters required by this blueprint definition. It can be a JSON string or JSON file path.'
        )

    with self.argument_context('blueprint import') as c:
        c.argument('blueprint_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint definition.')
        c.argument(
            'input_path',
            type=file_type,
            help=
            'The directory path for json definitions of the blueprint and artifacts. The blueprint definition file should be named blueprint.json. Artifacts json files should be in a subdirectory named artifacts.',
            completer=FilesCompleter())

    with self.argument_context('blueprint update') as c:
        c.argument('blueprint_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint definition.')
        c.argument('description', help='Multi-line explain this resource.')
        c.argument(
            'parameters',
            arg_type=parameter_type,
            help=
            'Parameters required by this blueprint definition. It can be a JSON string or JSON file path.'
        )

    with self.argument_context('blueprint delete') as c:
        c.argument('blueprint_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint definition.')

    with self.argument_context('blueprint show') as c:
        c.argument('blueprint_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint definition.')

    with self.argument_context('blueprint list') as c:
        pass

    with self.argument_context('blueprint artifact delete') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint artifact.')

    with self.argument_context('blueprint artifact show') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint artifact.')

    with self.argument_context('blueprint artifact list') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')

    with self.argument_context('blueprint resource-group add') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument(
            'rg_name',
            help=
            'Name of this resource group. Leave empty if the resource group name will be specified during the blueprint assignment.'
        )
        c.argument(
            'rg_location',
            help=
            'Location of this resource group. Leave empty if the resource group location will be specified during the blueprint assignment.'
        )
        c.argument('artifact_name',
                   help='A unique name of this resource group artifact.')
        c.argument('display_name',
                   help='Display name of this resource group artifact.')
        c.argument('description',
                   help='Description of the blueprint artifact.')
        c.argument(
            'depends_on',
            nargs='+',
            help=
            'Artifacts which need to be deployed before the specified artifact.'
        )
        c.argument('tags',
                   tags_type,
                   help='Tags to be assigned to this resource group.')

    with self.argument_context('blueprint resource-group update') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument(
            'rg_name',
            help=
            'Name of this resource group. Leave empty if the resource group name will be specified during the blueprint assignment.'
        )
        c.argument(
            'rg_location',
            help=
            'Location of this resource group. Leave empty if the resource group location will be specified during the blueprint assignment.'
        )
        c.argument('artifact_name',
                   help='A unique name of this resource group artifact.')
        c.argument('display_name',
                   help='Display name of this resource group artifact.')
        c.argument('description',
                   help='Description of the blueprint artifact.')
        c.argument(
            'depends_on',
            nargs='+',
            help=
            'Artifacts which need to be deployed before the specified artifact.'
        )
        c.argument('tags',
                   tags_type,
                   arg_group='Resource Group',
                   help='Tags to be assigned to this resource group.')

    with self.argument_context('blueprint resource-group remove') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name',
                   help='A unique name of this resource group artifact.')

    with self.argument_context('blueprint resource-group show') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name',
                   help='A unique name of this resource group artifact.')

    with self.argument_context('blueprint resource-group list') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')

    with self.argument_context('blueprint artifact policy create') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name', help='Name of the blueprint artifact.')
        c.argument('display_name', help='DisplayName of this artifact.')
        c.argument('description',
                   help='Description of the blueprint artifact.')
        c.argument(
            'depends_on',
            nargs='+',
            help=
            'Artifacts which need to be deployed before the specified artifact.'
        )
        c.argument('policy_definition_id',
                   help='The full policy definition id.')
        c.argument(
            'resource_group_art',
            help=
            'Name of the resource group artifact to which the policy will be assigned.'
        )
        c.argument(
            'parameters',
            arg_type=parameter_type,
            help=
            'Parameters for policy assignment artifact. It can be a JSON string or JSON file path.'
        )

    with self.argument_context('blueprint artifact policy update') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name', help='Name of the blueprint artifact.')
        c.argument('display_name', help='DisplayName of this artifact.')
        c.argument('description',
                   help='Description of the blueprint artifact.')
        c.argument(
            'depends_on',
            nargs='+',
            help=
            'Artifacts which need to be deployed before the specified artifact.'
        )
        c.argument(
            'resource_group_art',
            help=
            'Name of the resource group artifact to which the policy will be assigned.'
        )
        c.argument(
            'parameters',
            arg_type=parameter_type,
            help=
            'Parameters for policy assignment artifact. It can be a JSON string or JSON file path.'
        )

    with self.argument_context('blueprint artifact role create') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name', help='Name of the blueprint artifact.')
        c.argument('display_name', help='DisplayName of this artifact.')
        c.argument('description',
                   help='Description of the blueprint artifact.')
        c.argument(
            'depends_on',
            nargs='+',
            help=
            'Artifacts which need to be deployed before the specified artifact.'
        )
        c.argument(
            'role_definition_id',
            help=
            'The full role definition id. Only built-in roles are supported.')
        c.argument(
            'resource_group_art',
            help=
            'Name of the resource group artifact to which the policy will be assigned.'
        )
        c.argument(
            'principal_ids',
            nargs='+',
            help=
            'Array of user or group identities in Azure Active Directory or a reference to the corresponding parameter in blueprint definiton. The roleDefinition will apply to each identity.'
        )

    with self.argument_context('blueprint artifact role update') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name', help='Name of the blueprint artifact.')
        c.argument('display_name', help='DisplayName of this artifact.')
        c.argument('description',
                   help='Description of the blueprint artifact.')
        c.argument(
            'depends_on',
            nargs='+',
            help=
            'Artifacts which need to be deployed before the specified artifact.'
        )
        c.argument(
            'resource_group_art',
            help=
            'Name of the resource group artifact to which the policy will be assigned.'
        )

    with self.argument_context('blueprint artifact template create') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name', help='Name of the blueprint artifact.')
        c.argument('display_name', help='DisplayName of this artifact.')
        c.argument('description',
                   help='Description of the blueprint artifact.')
        c.argument(
            'depends_on',
            nargs='+',
            help=
            'Artifacts which need to be deployed before the specified artifact.'
        )
        c.argument(
            'resource_group_art',
            help=
            'Name of the resource group artifact to which the policy will be assigned.'
        )
        c.argument(
            'parameters',
            arg_type=parameter_type,
            help=
            'Parameters for ARM template artifact. It can be a JSON string or JSON file path.'
        )
        c.argument('template', arg_type=template_type)

    with self.argument_context('blueprint artifact template update') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('artifact_name', help='Name of the blueprint artifact.')
        c.argument('display_name', help='DisplayName of this artifact.')
        c.argument('description',
                   help='Description of the blueprint artifact.')
        c.argument(
            'depends_on',
            nargs='+',
            help=
            'Artifacts which need to be deployed before the specified artifact.'
        )
        c.argument(
            'resource_group_art',
            help=
            'Name of the resource group artifact to which the policy will be assigned.'
        )
        c.argument(
            'parameters',
            arg_type=parameter_type,
            help=
            'Parameters for ARM template artifact. It can be a JSON string or JSON file path.'
        )
        c.argument('template', arg_type=template_type)

    with self.argument_context('blueprint publish') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('version_id',
                   options_list=['--version'],
                   help='Version of the published blueprint definition.')
        c.argument('change_notes', help='Version-specific change notes.')

    with self.argument_context('blueprint version delete') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('version_id',
                   options_list=['--version'],
                   help='Version of the published blueprint definition.')

    with self.argument_context('blueprint version show') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('version_id',
                   options_list=['--version'],
                   help='Version of the published blueprint definition.')

    with self.argument_context('blueprint version list') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')

    with self.argument_context('blueprint version artifact show') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('version_id',
                   options_list=['--version'],
                   help='Version of the published blueprint definition.')
        c.argument('artifact_name', help='Name of the blueprint artifact.')

    with self.argument_context('blueprint version artifact list') as c:
        c.argument('blueprint_name', help='Name of the blueprint definition.')
        c.argument('version_id',
                   options_list=['--version'],
                   help='Version of the published blueprint definition.')

    with self.argument_context('blueprint assignment',
                               validator=blueprint_assignment_validator) as c:
        # override help
        c.argument(
            'subscription',
            help=
            'Use subscription for the target scope of the blueprint assignment. Default susbcription will be used if option not specified.'
        )
        c.argument(
            'management_group',
            help=
            'Use management group for the target scope of the blueprint assignment. It is reserved for future use. Use --subscription instead.'
        )

    for scope in ['create', 'update']:
        with self.argument_context('blueprint assignment ' + scope) as c:
            from .action import ResourceGroupAssignAddAction
            c.argument('assignment_name',
                       options_list=['--name', '-n'],
                       help='Name of the blueprint assignment.')
            c.argument('location', arg_type=get_location_type(self.cli_ctx))
            c.argument(
                'user_assigned_identity',
                arg_group='Identity',
                help=
                'The user-assigned managed identity associated with the resource.'
            )
            c.argument('display_name',
                       help='One-liner string explain this resource.')
            c.argument('description', help='Multi-line explain this resource.')
            c.argument(
                'blueprint_id',
                options_list=['--blueprint-version'],
                help=
                'Resource ID of the published version of a blueprint definition.'
            )
            c.argument(
                'parameters',
                arg_type=parameter_type,
                help=
                'Blueprint assignment parameter values. It can be a JSON string or JSON file path.'
            )
            c.argument(
                'resource_groups',
                options_list=['--resource-group-value'],
                action=ResourceGroupAssignAddAction,
                nargs='+',
                help=
                "Key=Value pairs for a resource group. Keys include 'artifact_name'(required), 'name', 'location'."
            )
            c.argument('locks_mode',
                       arg_type=get_enum_type(AssignmentLockMode),
                       help='Lock mode.')
            c.argument(
                'locks_excluded_principals',
                help=
                'List of AAD principals excluded from blueprint locks. Up to 5 principals are permitted.',
                nargs='+')

    with self.argument_context('blueprint assignment create') as c:
        c.argument('identity_type',
                   arg_type=get_enum_type(ManagedServiceIdentityType),
                   default='SystemAssigned',
                   arg_group='Identity',
                   help='Type of the managed identity.')

    with self.argument_context('blueprint assignment update') as c:
        c.argument('identity_type',
                   arg_type=get_enum_type(ManagedServiceIdentityType),
                   arg_group='Identity',
                   help='Type of the managed identity.')

    with self.argument_context('blueprint assignment delete') as c:
        c.argument('assignment_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint assignment.')

    with self.argument_context('blueprint assignment show') as c:
        c.argument('assignment_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint assignment.')

    with self.argument_context('blueprint assignment list') as c:
        pass

    with self.argument_context('blueprint assignment wait') as c:
        # extra argument cannot be registered to a group-level scope, have to redefine
        # management_group and subscription as extra at command level here
        # for a non-custom command.
        c.extra(
            'subscription',
            arg_type=subscription_type,
            help=
            'Use subscription for the target scope of the blueprint assignment. Default susbcription will be used if option not specified.'
        )
        c.extra(
            'management_group',
            arg_type=management_group_type,
            help=
            'Use management group for the target scope of the blueprint assignment. It is reserved for future use. Use --subscription instead.'
        )
        c.argument('assignment_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint assignment.')

    with self.argument_context('blueprint assignment who') as c:
        c.argument('assignment_name',
                   options_list=['--name', '-n'],
                   help='Name of the blueprint assignment.')
Esempio n. 28
0
def load_arguments(self, _):

    with self.argument_context('redisenterprise operation-status show') as c:
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   id_part='name')
        c.argument('operation_id',
                   type=str,
                   help='The operation\'s unique identifier.',
                   id_part='child_name_1')

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

    with self.argument_context('redisenterprise show') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')

    with self.argument_context('redisenterprise create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.')
        c.argument('tags', tags_type)
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   required=False,
                   validator=get_default_location_from_resource_group)
        c.argument(
            'sku',
            arg_type=get_enum_type([
                'Enterprise_E10', 'Enterprise_E20', 'Enterprise_E50',
                'Enterprise_E100', 'EnterpriseFlash_F300',
                'EnterpriseFlash_F700', 'EnterpriseFlash_F1500'
            ]),
            help='The type of RedisEnterprise cluster '
            'to deploy. Possible values: (Enterprise_E10, EnterpriseFlash_F300 etc.)'
        )
        c.argument(
            'capacity',
            type=int,
            help=
            'The size of the RedisEnterprise cluster. Defaults to 2 or 3 depending '
            'on SKU. Valid values are (2, 4, 6, ...) for Enterprise SKUs and (3, 9, 15, ...) for Flash SKUs.'
        )
        c.argument('zones',
                   options_list=['--zones', '-z'],
                   nargs='+',
                   help='The Availability Zones where this cluster '
                   'will be deployed.')
        c.argument('minimum_tls_version',
                   arg_type=get_enum_type(['1.0', '1.1', '1.2']),
                   help='The minimum TLS version '
                   'for the cluster to support, e.g. \'1.2\'')

    with self.argument_context('redisenterprise update') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')
        c.argument(
            'sku',
            arg_type=get_enum_type([
                'Enterprise_E10', 'Enterprise_E20', 'Enterprise_E50',
                'Enterprise_E100', 'EnterpriseFlash_F300',
                'EnterpriseFlash_F700', 'EnterpriseFlash_F1500'
            ]),
            help='The type of RedisEnterprise cluster '
            'to deploy. Possible values: (Enterprise_E10, EnterpriseFlash_F300 etc.)'
        )
        c.argument(
            'capacity',
            type=int,
            help=
            'The size of the RedisEnterprise cluster. Defaults to 2 or 3 depending '
            'on SKU. Valid values are (2, 4, 6, ...) for Enterprise SKUs and (3, 9, 15, ...) for Flash SKUs.'
        )
        c.argument('tags', tags_type)
        c.argument('minimum_tls_version',
                   arg_type=get_enum_type(['1.0', '1.1', '1.2']),
                   help='The minimum TLS version '
                   'for the cluster to support, e.g. \'1.2\'')

    with self.argument_context('redisenterprise delete') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')

    with self.argument_context('redisenterprise wait') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')

    with self.argument_context('redisenterprise database list') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.')

    with self.argument_context('redisenterprise database show') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')

    with self.argument_context('redisenterprise database create') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.')
        c.argument(
            'client_protocol',
            arg_type=get_enum_type(['Encrypted', 'Plaintext']),
            help='Specifies whether '
            'redis clients can connect using TLS-encrypted or plaintext redis protocols. Default is '
            'TLS-encrypted.')
        c.argument(
            'port',
            type=int,
            help=
            'TCP port of the database endpoint. Specified at create time. Defaults to an '
            'available port.')
        c.argument('clustering_policy',
                   arg_type=get_enum_type(['EnterpriseCluster', 'OSSCluster']),
                   help='Clustering '
                   'policy - default is OSSCluster. Specified at create time.')
        c.argument('eviction_policy',
                   arg_type=get_enum_type([
                       'AllKeysLFU', 'AllKeysLRU', 'AllKeysRandom',
                       'VolatileLRU', 'VolatileLFU', 'VolatileTTL',
                       'VolatileRandom', 'NoEviction'
                   ]),
                   help='Redis eviction '
                   'policy - default is VolatileLRU')
        c.argument('persistence',
                   action=AddPersistence,
                   nargs='+',
                   help='Persistence settings',
                   is_preview=True)
        c.argument('modules',
                   action=AddModules,
                   nargs='+',
                   help='Optional set of redis modules to enable in this '
                   'database - modules can only be added at creation time.')
        c.argument('group_nickname',
                   type=str,
                   help='Name for the group of linked database resources',
                   arg_group='Geo '
                   'Replication')
        c.argument('linked_databases',
                   action=AddLinkedDatabases,
                   nargs='+',
                   help='List of database resources to link '
                   'with this database',
                   arg_group='Geo Replication')

    with self.argument_context('redisenterprise database update') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')
        c.argument(
            'client_protocol',
            arg_type=get_enum_type(['Encrypted', 'Plaintext']),
            help='Specifies whether '
            'redis clients can connect using TLS-encrypted or plaintext redis protocols. Default is '
            'TLS-encrypted.')
        c.argument('eviction_policy',
                   arg_type=get_enum_type([
                       'AllKeysLFU', 'AllKeysLRU', 'AllKeysRandom',
                       'VolatileLRU', 'VolatileLFU', 'VolatileTTL',
                       'VolatileRandom', 'NoEviction'
                   ]),
                   help='Redis eviction '
                   'policy - default is VolatileLRU')
        c.argument('persistence',
                   action=AddPersistence,
                   nargs='+',
                   help='Persistence settings',
                   is_preview=True)
        c.argument('group_nickname',
                   type=str,
                   help='Name for the group of linked database resources',
                   arg_group='Geo '
                   'Replication')
        c.argument('linked_databases',
                   action=AddLinkedDatabases,
                   nargs='+',
                   help='List of database resources to link '
                   'with this database',
                   arg_group='Geo Replication')

    with self.argument_context('redisenterprise database delete') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')

    with self.argument_context('redisenterprise database export') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')
        c.argument('sas_uri',
                   type=str,
                   help='SAS URI for the target directory to export to')

    with self.argument_context('redisenterprise database force-unlink') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')
        c.argument(
            'unlink_ids',
            nargs='+',
            help='The resource IDs of the database resources to be unlinked.')

    with self.argument_context('redisenterprise database import') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')
        c.argument('sas_uris',
                   nargs='+',
                   help='SAS URIs for the target blobs to import from')

    with self.argument_context('redisenterprise database list-keys') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.')

    with self.argument_context('redisenterprise database regenerate-key') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')
        c.argument('key_type',
                   arg_type=get_enum_type(['Primary', 'Secondary']),
                   help='Which access key to regenerate.')

    with self.argument_context('redisenterprise database wait') as c:
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('cluster_name',
                   options_list=['--cluster-name', '--name', '-n'],
                   type=str,
                   help='The name of the '
                   'RedisEnterprise cluster.',
                   id_part='name')
Esempio n. 29
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)
Esempio n. 30
0
def load_arguments(self, _):

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

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

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

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

    # Endpoint #

    with self.argument_context('cdn endpoint') as c:
        c.argument('content_paths', nargs='+')
        c.argument('endpoint_name',
                   name_arg_type,
                   id_part='child_name_1',
                   help='Name of the CDN endpoint.')
        c.argument('location',
                   validator=get_default_location_from_resource_group)
        c.argument(
            'origins',
            options_list='--origin',
            nargs='+',
            action=OriginType,
            validator=validate_origin,
            help=
            'Endpoint origin specified by the following space-delimited 6 tuple: '
            '`www.example.com http_port https_port private_link_resource_id private_link_location '
            'private_link_approval_message`. The HTTP and HTTPS ports and the private link resource ID and '
            'location are optional. The HTTP and HTTPS ports default to 80 and 443, respectively. Private '
            'link fields are only valid for the sku Standard_Microsoft, and private_link_location is '
            'required if private_link_resource_id is set.')
        c.argument(
            'is_http_allowed',
            arg_type=get_three_state_flag(invert=True),
            options_list='--no-http',
            help=
            'Indicates whether HTTP traffic is not allowed on the endpoint. '
            'Default is to allow HTTP traffic.')
        c.argument(
            'is_https_allowed',
            arg_type=get_three_state_flag(invert=True),
            options_list='--no-https',
            help=
            'Indicates whether HTTPS traffic is not allowed on the endpoint. '
            'Default is to allow HTTPS traffic.')
        c.argument(
            'origin_path',
            help=
            'A directory path on the origin that Azure CDN can use to retrieve content from.'
        )
        c.argument(
            'origin_host_header',
            help=
            "The Host header to send for requests to this origin. If you leave this blank, "
            "the request hostname determines this value. "
            "Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services "
            "require this host header value to match the origin hostname by default."
        )
        c.argument(
            'is_compression_enabled',
            arg_type=get_three_state_flag(),
            options_list='--enable-compression',
            help=
            'If compression is enabled, content will be served as compressed if '
            'user requests for a compressed version. Content won\'t be compressed '
            'on CDN when requested content is smaller than 1 byte or larger than 1 '
            'MB.')

        c.argument(
            'query_string_caching_behavior',
            options_list='--query-string-caching',
            arg_type=get_enum_type(QueryStringCachingBehavior),
            help="Defines how CDN caches requests that include query strings. "
            "You can ignore any query strings when caching, "
            "bypass caching to prevent requests that contain query strings from being cached, "
            "or cache every request with a unique URL.")

        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument(
            'content_types_to_compress',
            nargs='*',
            help=
            'List of content types on which compression applies. The value should be a valid MIME type.'
        )

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

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

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

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

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

    # Custom Domain #

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

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

    with self.argument_context('cdn custom-domain enable-https') as c:
        c.argument('profile_name',
                   id_part=None,
                   help='Name of the parent profile.')
        c.argument('endpoint_name', help='Name of the parent endpoint.')
        c.argument('custom_domain_name',
                   name_arg_type,
                   help='Resource name of the custom domain.')
        c.argument(
            'min_tls_version',
            help='The minimum TLS version required for the custom domain.',
            arg_type=get_enum_type(['none', '1.0', '1.2']))
        c.argument('user_cert_protocol_type',
                   arg_group='Bring Your Own Certificate',
                   help='The protocol type of the certificate.',
                   arg_type=get_enum_type(['sni', 'ip']))
        c.argument('user_cert_subscription_id',
                   arg_group='Bring Your Own Certificate',
                   help='The subscription id of the KeyVault certificate')
        c.argument('user_cert_group_name',
                   arg_group='Bring Your Own Certificate',
                   help='The resource group of the KeyVault certificate')
        c.argument('user_cert_vault_name',
                   arg_group='Bring Your Own Certificate',
                   help='The vault name of the KeyVault certificate')
        c.argument('user_cert_secret_name',
                   arg_group='Bring Your Own Certificate',
                   help='The secret name of the KeyVault certificate')
        c.argument(
            'user_cert_secret_version',
            arg_group='Bring Your Own Certificate',
            help=
            'The secret version of the KeyVault certificate, If not specified, the "Latest" version will '
            'always been used and the deployed certificate will be automatically rotated to the latest '
            'version when a newer version of the certificate is available.')

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

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

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

    # WAF #

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

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

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

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

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

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

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

    # AFD Profiles
    with self.argument_context('afd profile') as c:
        c.argument('sku',
                   arg_type=get_enum_type([
                       SkuName.standard_azure_front_door,
                       SkuName.premium_azure_front_door
                   ]),
                   help="The pricing tier of the AFD profile.")
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument(
            'origin_response_timeout_seconds',
            type=int,
            options_list=["--origin-response-timeout-seconds"],
            help="Send and receive timeout on forwarding request to the origin. "
            "When timeout is reached, the request fails and returns.")

    # AFD endpoint #
    with self.argument_context('afd endpoint') as c:
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('enabled_state',
                   arg_type=get_enum_type(EnabledState),
                   options_list=["--enabled-state"],
                   help="Whether to enable this endpoint.")
        c.argument(
            'auto_generated_domain_name_label_scope',
            arg_type=get_enum_type(AutoGeneratedDomainNameLabelScope),
            options_list=["--name-reuse-scope"],
            help=
            "Indicates the endpoint name reuse scope. The default value is TenantReuse."
        )

        c.argument(
            'endpoint_name',
            endpoint_name_type,
            id_part='child_name_1',
            help=
            'Name of the endpoint under the profile which is unique globally.')
        c.argument(
            'content_paths',
            nargs='+',
            help=
            "The path to the content to be purged. Can describe a file path or a wildcard directory."
        )
        c.argument('domains', nargs='+', help='List of domains.')

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

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

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

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

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

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

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

    # AFD Route #
    with self.argument_context('afd route') as c:
        c.argument('route_name',
                   route_name_type,
                   id_part='child_name_2',
                   help='Name of the route.')
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('endpoint_name',
                   endpoint_name_type,
                   id_part='child_name_1',
                   help='Name of the endpoint.')
        c.argument(
            'origin_group',
            help='Name or ID of the origin group to be associated with.')
        c.argument('patterns_to_match',
                   nargs='+',
                   help='The route patterns of the rule.')
        c.argument(
            'origin_path',
            help=
            'A directory path on the origin that Azure Front Door can use to retrieve content from.'
        )
        c.argument('custom_domains',
                   nargs='*',
                   help='Custom domains referenced by this endpoint.')
        c.argument('supported_protocols',
                   nargs='+',
                   arg_type=get_enum_type(AFDEndpointProtocols),
                   help="List of supported protocols for this route.")
        c.argument(
            'link_to_default_domain',
            arg_type=get_enum_type(LinkToDefaultDomain),
            help=
            "Whether this route will be linked to the default endpoint domain."
        )
        c.argument(
            'forwarding_protocol',
            arg_group="Action",
            arg_type=get_enum_type(ForwardingProtocol),
            help=
            "Protocol this rule will use when forwarding traffic to backends.")
        c.argument('enabled_state',
                   arg_type=get_enum_type(EnabledState),
                   options_list=["--enabled-state"],
                   help="Whether to enable this route.")
        c.argument(
            'https_redirect',
            arg_type=get_enum_type(HttpsRedirect),
            help=
            'Whether to automatically redirect HTTP traffic to HTTPS traffic.')
        c.argument(
            'rule_sets',
            nargs='*',
            help='Collection of ID or name of rule set referenced by the route.'
        )
        c.argument(
            'content_types_to_compress',
            nargs='+',
            help=
            'List of content types on which compression applies. The value should be a valid MIME type.'
        )
        c.argument('enable_caching',
                   arg_type=get_three_state_flag(invert=False),
                   help='Indicates whether caching is enanbled on that route.')
        c.argument(
            'query_string_caching_behavior',
            arg_type=get_enum_type(AfdQueryStringCachingBehavior),
            help="Defines how CDN caches requests that include query strings. "
            "You can ignore any query strings when caching, "
            "bypass caching to prevent requests that contain query strings from being cached, "
            "or cache every request with a unique URL.")
        c.argument('query_parameters',
                   nargs='*',
                   help="query parameters to include or exclude")

        c.argument(
            'is_compression_enabled',
            arg_type=get_three_state_flag(),
            options_list='--enable-compression',
            help=
            'Indicates whether content compression is enabled on AzureFrontDoor. Default value is false. '
            'If compression is enabled, content will be served as compressed if user requests for a '
            "compressed version. Content won't be compressed on AzureFrontDoor when requested content is "
            'smaller than 1 byte or larger than 1 MB.')

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

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

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

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

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

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

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

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

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

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

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

    # AFD Secret #
    with self.argument_context('afd secret') as c:
        c.argument('profile_name', help=profile_name_help, id_part='name')
        c.argument('secret_name',
                   secret_name_arg_type,
                   id_part="child_name_1",
                   help='Name of the secret.')
        c.argument(
            'use_latest_version',
            arg_type=get_three_state_flag(),
            help="Whether to use the latest version for the certificate.")
        c.argument(
            'secret_source',
            help='Resource ID of the Azure Key Vault certificate, '
            'expected format is like /subscriptions/sub1/resourceGroups/rg1/'
            'providers/Microsoft.KeyVault/vaults/vault1/secrets/cert1.')
        c.argument('secret_version',
                   help='Version of the certificate to be used.')

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

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

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

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

    with self.argument_context('afd waf-log-analytic') as c:
        c.argument('metrics',
                   nargs='+',
                   arg_type=get_enum_type(["clientRequestCount"]),
                   help="Metric types to be included.")
        c.argument('group_by',
                   nargs='+',
                   arg_type=get_enum_type(["httpStatusCode", "customDomain"]),
                   help="Aggregate demensions.")
        c.argument('actions',
                   nargs='+',
                   help="The WAF actions to be included.",
                   arg_type=get_enum_type(
                       ["allow", "block", "log", "redirect"]))
        c.argument('rule_types',
                   nargs='+',
                   help="The WAF rule types to be included.",
                   arg_type=get_enum_type(["managed", "custom", "bot"]))
        c.argument('rankings',
                   nargs='+',
                   help="The dimemsions to be included for ranking.",
                   arg_type=get_enum_type([
                       "action", "ruleGroup", "ruleId", "userAgent",
                       "clientIp", "url", "country", "ruleType"
                   ]))
        configure_log_analytic_common_parameters(c)
Esempio n. 31
0
def load_arguments(self, _):
    with self.argument_context(consts.EXTENSION_NAME) as c:
        c.argument('location',
                   validator=get_default_location_from_resource_group)
        c.argument('name',
                   options_list=['--name', '-n'],
                   help='Name of the extension instance')
        c.argument('extension_type', help='Name of the extension type.')
        c.argument('cluster_name',
                   options_list=['--cluster-name', '-c'],
                   help='Name of the Kubernetes cluster')
        c.argument(
            'cluster_type',
            arg_type=get_enum_type(
                ['connectedClusters', 'managedClusters', 'appliances']),
            options_list=['--cluster-type', '-t'],
            help=
            'Specify Arc clusters or AKS managed clusters or Arc appliances.')
        c.argument('scope',
                   arg_type=get_enum_type(['cluster', 'namespace']),
                   help='Specify the extension scope.')
        c.argument(
            'auto_upgrade_minor_version',
            arg_group="Version",
            options_list=['--auto-upgrade-minor-version', '--auto-upgrade'],
            arg_type=get_three_state_flag(),
            help=
            'Automatically upgrade minor version of the extension instance.')
        c.argument(
            'version',
            arg_group="Version",
            help='Specify the version to install for the extension instance if'
            ' --auto-upgrade-minor-version is not enabled.')
        c.argument('release_train',
                   arg_group="Version",
                   help='Specify the release train for the extension type.')
        c.argument(
            'configuration_settings',
            arg_group="Configuration",
            options_list=['--configuration-settings', '--config'],
            action=AddConfigurationSettings,
            nargs='+',
            help=
            'Configuration Settings as key=value pair.  Repeat parameter for each setting'
        )
        c.argument(
            'configuration_protected_settings',
            arg_group="Configuration",
            options_list=[
                '--configuration-protected-settings', '--config-protected'
            ],
            action=AddConfigurationProtectedSettings,
            nargs='+',
            help=
            'Configuration Protected Settings as key=value pair.  Repeat parameter for each setting'
        )
        c.argument(
            'configuration_settings_file',
            arg_group="Configuration",
            options_list=['--configuration-settings-file', '--config-file'],
            help='JSON file path for configuration-settings')
        c.argument('configuration_protected_settings_file',
                   arg_group="Configuration",
                   options_list=[
                       '--configuration-protected-settings-file',
                       '--config-protected-file'
                   ],
                   help='JSON file path for configuration-protected-settings')
        c.argument(
            'release_namespace',
            help='Specify the namespace to install the extension release.')
        c.argument(
            'target_namespace',
            help=
            'Specify the target namespace to install to for the extension instance. This'
            ' parameter is required if extension scope is set to \'namespace\''
        )

    with self.argument_context(f"{consts.EXTENSION_NAME} update") as c:
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Ignore confirmation prompts')

    with self.argument_context(f"{consts.EXTENSION_NAME} delete") as c:
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Ignore confirmation prompts')
        c.argument(
            'force',
            help=
            'Specify whether to force delete the extension from the cluster.')
Esempio n. 32
0
def configure_rule_parameters(c, is_afdx):
    c.argument('rule_name', help='Name of the rule.')
    c.argument(
        'order',
        type=int,
        help=
        'The order in which the rules are applied for the endpoint. Possible values {0,1,2,3,………}. '
        'A rule with a lower order will be applied before one with a higher order. '
        'Rule with order 0 is a special rule. '
        'It does not require any condition and actions listed in it will always be applied.'
    )

    if is_afdx:
        c.argument(
            'match_variable',
            arg_group="Match Condition",
            help='Name of the match condition: '
            'https://docs.microsoft.com/en-us/azure/frontdoor/rules-match-conditions',
            arg_type=get_enum_type(
                DeliveryRuleCondition._subtype_map["name"].keys()))
    else:
        c.argument(
            'match_variable',
            arg_group="Match Condition",
            help='Name of the match condition: '
            'https://docs.microsoft.com/en-us/azure/cdn/cdn-standard-rules-engine-match-conditions',
            arg_type=get_enum_type(
                DeliveryRuleCondition._subtype_map["name"].keys()))

    c.argument('operator',
               arg_group="Match Condition",
               help='Operator of the match condition.')
    c.argument('selector',
               arg_group="Match Condition",
               help='Selector of the match condition.')
    c.argument('match_values',
               arg_group="Match Condition",
               nargs='+',
               help='Match values of the match condition.')

    if not is_afdx:
        c.argument('transform',
                   arg_group="Match Condition",
                   arg_type=get_enum_type(['Lowercase', 'Uppercase']),
                   nargs='+',
                   help='Transform to apply before matching.')
    else:
        transforms = [item.value for item in list(Transform)]
        c.argument('transforms',
                   arg_group="Match Condition",
                   arg_type=get_enum_type(transforms),
                   nargs='+',
                   help='Transform to apply before matching.')

    c.argument('negate_condition',
               arg_group="Match Condition",
               arg_type=get_three_state_flag(),
               help='If true, negates the condition')

    all_actions = list(DeliveryRuleAction._subtype_map["name"].keys())
    if is_afdx:
        excldued_actions = [
            "UrlSigning", "CacheExpiration", "CacheKeyQueryString",
            "OriginGroupOverride"
        ]
        c.argument(
            'action_name',
            arg_group="Action",
            help='The name of the action for the delivery rule: '
            'https://docs.microsoft.com/en-us/azure/frontdoor/front-door-rules-engine-actions',
            arg_type=get_enum_type([
                action for action in all_actions
                if action not in excldued_actions
            ]))

        c.argument('cache_behavior',
                   arg_group="Action",
                   arg_type=get_enum_type([
                       'HonorOrigin', 'OverrideAlways',
                       'OverrideIfOriginMissing'
                   ]),
                   help='Caching behavior for the requests.')
        c.argument(
            'query_string_caching_behavior',
            arg_group="Action",
            arg_type=get_enum_type(AfdQueryStringCachingBehavior),
            help="Defines how CDN caches requests that include query strings. "
            "You can ignore any query strings when caching, "
            "bypass caching to prevent requests that contain query strings from being cached, "
            "or cache every request with a unique URL.")

        c.argument('query_parameters',
                   arg_group="Action",
                   nargs='*',
                   help="query parameters to include or exclude")
        c.argument(
            'forwarding_protocol',
            arg_group="Action",
            arg_type=get_enum_type(ForwardingProtocol),
            help=
            "Protocol this rule will use when forwarding traffic to backends.")
        c.argument(
            'is_compression_enabled',
            arg_group="Action",
            arg_type=get_three_state_flag(),
            options_list='--enable-compression',
            help=
            'Indicates whether content compression is enabled on AzureFrontDoor. Default value is false. '
            'If compression is enabled, content will be served as compressed if user requests for a '
            "compressed version. Content won't be compressed on AzureFrontDoor when requested content is "
            'smaller than 1 byte or larger than 1 MB.')
        c.argument('enable_caching',
                   arg_type=get_three_state_flag(invert=False),
                   options_list='--enable-caching',
                   arg_group="Action",
                   help='Indicates whether to enable caching on the route.')
    else:
        excldued_actions = ["RouteConfigurationOverride", "UrlSigning"]
        c.argument(
            'action_name',
            arg_group="Action",
            help='The name of the action for the delivery rule: '
            'https://docs.microsoft.com/en-us/azure/cdn/cdn-standard-rules-engine-actions',
            arg_type=get_enum_type([
                action for action in all_actions
                if action not in excldued_actions
            ]))

        # CacheExpirationAction parameters
        c.argument('cache_behavior',
                   arg_group="Action",
                   arg_type=get_enum_type(
                       ['BypassCache', 'Override', 'SetIfMissing']),
                   help='Caching behavior for the requests.')
        c.argument(
            'query_string_caching_behavior',
            options_list='--query-string-caching',
            arg_type=get_enum_type(QueryStringCachingBehavior),
            help="Defines how CDN caches requests that include query strings. "
            "You can ignore any query strings when caching, "
            "bypass caching to prevent requests that contain query strings from being cached, "
            "or cache every request with a unique URL.")

        # CacheKeyQueryStringAction parameters
        c.argument(
            'query_parameters',
            arg_group="Action",
            help='Query parameters to include or exclude (comma separated).')
        c.argument('query_string_behavior',
                   arg_group="Action",
                   arg_type=get_enum_type(
                       ['Include', 'IncludeAll', 'Exclude', 'ExcludeAll']),
                   help='Query string behavior for the requests.')

    c.argument('cache_duration',
               arg_group="Action",
               help='The duration for which the content needs to be cached. \
               Allowed format is [d.]hh:mm:ss.')
    c.argument('header_action',
               arg_group="Action",
               arg_type=get_enum_type(['Append', 'Overwrite', 'Delete']),
               help='Header action for the requests.')
    c.argument('header_name',
               arg_group="Action",
               help='Name of the header to modify.')
    c.argument('header_value', arg_group="Action", help='Value of the header.')
    c.argument(
        'redirect_type',
        arg_group="Action",
        arg_type=get_enum_type(
            ['Moved', 'Found', 'TemporaryRedirect', 'PermanentRedirect']),
        help='The redirect type the rule will use when redirecting traffic.')
    c.argument('redirect_protocol',
               arg_group="Action",
               arg_type=get_enum_type(['MatchRequest', 'Http', 'Https']),
               help='Protocol to use for the redirect.')
    c.argument('custom_hostname',
               arg_group="Action",
               help='Host to redirect. \
               Leave empty to use the incoming host as the destination host.')
    c.argument(
        'custom_path',
        arg_group="Action",
        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_querystring',
        arg_group="Action",
        help='The set of query strings to be placed in the redirect URL. \
               leave empty to preserve the incoming query string.')
    c.argument('custom_fragment',
               arg_group="Action",
               help='Fragment to add to the redirect URL.')

    c.argument(
        'source_pattern',
        arg_group="Action",
        help=
        'A request URI pattern that identifies the type of requests that may be rewritten.'
    )
    c.argument('destination',
               arg_group="Action",
               help='The destination path to be used in the rewrite.')
    c.argument('preserve_unmatched_path',
               arg_group="Action",
               arg_type=get_three_state_flag(),
               help='If True, the remaining path after the source \
               pattern will be appended to the new destination path.')
    c.argument('index', type=int, help='The index of the condition/action')
    c.argument(
        'origin_group',
        arg_group="Action",
        help=
        'Name or ID of the OriginGroup that would override the default OriginGroup'
    )
Esempio n. 33
0
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=['--boostrap-acc-pwd', '-b'],
            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())
Esempio n. 34
0
def load_arguments(self, _):
    from ._completers import subnet_completion_list, cluster_admin_account_completion_list, \
        cluster_user_group_completion_list, get_resource_name_completion_list_under_subscription
    from knack.arguments import CLIArgumentType
    from azure.mgmt.hdinsight.models import Tier, JsonWebKeyEncryptionAlgorithm
    from argcomplete.completers import FilesCompleter
    node_size_type = CLIArgumentType(arg_group='Node',
                                     help='The size of the node. See also: https://docs.microsoft.com/azure/'
                                          'hdinsight/hdinsight-hadoop-provision-linux-clusters#configure-cluster-size')

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

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

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

        # Node
        c.argument('headnode_size', arg_type=node_size_type)
        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('kafka_management_node_size', arg_type=node_size_type)
        c.argument('workernode_count', options_list=['--workernode-count', '-c'], arg_group='Node',
                   help='The number of worker nodes in the cluster.')
        c.argument('kafka_management_node_count', arg_group='Node',
                   help='The number of kafka management node in the cluster')

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

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

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

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

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

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

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

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

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

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

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

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

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

    quotes = '""' if platform.system() == 'Windows' else "''"

    tc_url_type = CLIArgumentType(
        options_list=['--base-url', '-u'],
        help=
        'Base url of the TeamCloud instance. Use `az configure --defaults tc-base-url=<url>` '
        'to configure a default.',
        configured_default='tc-base-url',
        validator=base_url_validator)

    user_name_type = CLIArgumentType(options_list=['--name', '-n'],
                                     help='User email.',
                                     validator=user_name_validator)

    user_name_or_id_type = CLIArgumentType(options_list=['--name', '-n'],
                                           help='User id (uuid) or email.',
                                           validator=user_name_or_id_validator)

    project_name_or_id_type = CLIArgumentType(
        options_list=['--project', '-p'],
        help='Project id (uuid) or name.',
        validator=project_name_or_id_validator,
        completer=get_project_completion_list)

    properties_type = CLIArgumentType(
        validator=properties_validator,
        help='Space-separated properties: key[=value] [key[=value] ...].'
        'Use {} to clear existing properties.'.format(quotes),
        nargs='*')

    # Global

    # ignore global az arg --subscription and requre base_url for everything except `tc deploy`
    for scope in [
            'tc status', 'tc upgrade', 'tc user', 'tc project',
            'tc project-type', 'tc provider', 'tc tag'
    ]:
        with self.argument_context(scope, arg_group='TeamCloud') as c:
            c.ignore('_subscription')
            c.argument('base_url', tc_url_type)

    # Tags

    for scope in [
            'tc tag create', 'tc tag show', 'tc tag delete',
            'tc project tag create', 'tc project tag show',
            'tc project tag delete'
    ]:
        with self.argument_context(scope) as c:
            c.argument('tag_key',
                       options_list=['--key', '-k'],
                       help='Tag key.')

    for scope in ['tc tag create', 'tc project tag create']:
        with self.argument_context(scope) as c:
            c.argument('tag_value',
                       options_list=['--value', '-v'],
                       help='Tag value.')

    with self.argument_context('tc project tag') as c:
        c.argument('project', project_name_or_id_type)

    # TeamCloud

    # tc deploy uses a command level validator, param validators will be ignored
    with self.argument_context('tc deploy') as c:
        c.argument(
            'name',
            options_list=['--name', '-n'],
            help=
            'Name of app. Must be globally unique and will be the subdomain '
            'for the TeamCloud instance service endpoint.')
        c.argument('resource_group_name',
                   resource_group_name_type,
                   default='TeamCloud')
        c.argument('principal_name',
                   help='Service principal name, or object id.')
        c.argument('principal_password',
                   help="Service principal password, aka 'client secret'.")
        c.argument('tags', tags_type)
        c.argument('version',
                   options_list=['--version', '-v'],
                   help='TeamCloud version. Default: latest stable.')
        c.argument(
            'skip_app_deployment',
            action='store_true',
            help=
            "Only create Azure resources, skip deploying the TeamCloud API and Orchestrator apps."
        )
        c.argument(
            'skip_name_validation',
            action='store_true',
            help=
            "Skip name validaiton. Useful when attempting to redeploy a partial or failed deployment."
        )
        c.argument('skip_admin_user',
                   action='store_true',
                   help="Skip adding Admin user.")

    with self.argument_context('tc upgrade') as c:
        c.argument('resource_group_name',
                   resource_group_name_type,
                   default='TeamCloud')
        c.argument('version',
                   options_list=['--version', '-v'],
                   help='TeamCloud version. Default: latest stable.',
                   validator=source_version_validator)

    with self.argument_context('tc status') as c:
        c.argument('project', project_name_or_id_type)
        c.argument('tracking_id',
                   options_list=['--tracking-id', '-t'],
                   type=str,
                   help='Operation tracking id.',
                   validator=tracking_id_validator)

    # TeamCloud Users

    with self.argument_context('tc user create') as c:
        c.argument('user_name', user_name_type)
        c.argument('user_role',
                   get_enum_type(['Admin', 'Creator'], default='Creator'),
                   options_list=['--role', '-r'],
                   help='User role.')
        c.argument('tags', tags_type)

    for scope in ['tc user show', 'tc user delete']:
        with self.argument_context(scope) as c:
            c.argument('user', user_name_or_id_type)

    # Projects

    with self.argument_context('tc project create') as c:
        c.argument('name',
                   options_list=['--name', '-n'],
                   type=str,
                   help='Project name.',
                   validator=project_name_validator)
        c.argument(
            'project_type',
            options_list=['--project-type', '-t'],
            type=str,
            help=
            'Project type id. Use `az tc project-type list` to get available project types',
            validator=project_type_id_validator)
        c.argument('tags', tags_type)

    for scope in ['tc project show', 'tc project delete']:
        with self.argument_context(scope) as c:
            c.argument('project',
                       options_list=['--name', '-n'],
                       type=str,
                       help='Project name or id (uuid).',
                       validator=project_name_or_id_validator,
                       completer=get_project_completion_list)

    # Project Users

    with self.argument_context('tc project user') as c:
        c.argument('project', project_name_or_id_type)

    with self.argument_context('tc project user create') as c:
        c.argument('user_name', user_name_type)
        c.argument('user_role',
                   get_enum_type(['Owner', 'Member'], default='Member'),
                   options_list=['--role', '-r'],
                   help='User role.')
        c.argument('tags', tags_type)

    for scope in ['tc project user show', 'tc project user delete']:
        with self.argument_context(scope) as c:
            c.argument('user', user_name_or_id_type)

    # Project Types

    with self.argument_context('tc project-type create') as c:
        c.argument('project_type',
                   options_list=['--name', '-n'],
                   type=str,
                   help='Project type id.',
                   validator=project_type_id_validator_name)
        c.argument('location',
                   get_location_type(self.cli_ctx),
                   help='Project type region.')
        c.argument('subscriptions',
                   nargs='+',
                   help='Space-seperated subscription ids (uuids).',
                   validator=subscriptions_list_validator)
        c.argument('subscription_capacity',
                   type=int,
                   default=10,
                   help='Maximum number of projects per subscription.')
        c.argument('default',
                   action='store_true',
                   help='Set as the default project type.')
        c.argument('resource_group_name_prefix',
                   type=str,
                   help='Prepended to all project resource group names.')
        c.argument(
            'provider',
            nargs='+',
            action=CreateProviderReference,
            help='Project type provider: provider_id [key=value ...]. '
            'Use depends_on key to define dependencies. '
            'Use multiple --provider arguemnts to specify additional providers.'
        )
        c.argument('tags', tags_type)
        c.argument('properties', properties_type)
        c.ignore('providers')

    for scope in ['tc project-type show', 'tc project-type delete']:
        with self.argument_context(scope) as c:
            c.argument('project_type',
                       options_list=['--name', '-n'],
                       type=str,
                       help='Project type id.',
                       validator=project_type_id_validator_name,
                       completer=get_project_type_completion_list)

    # Providers

    with self.argument_context('tc provider create') as c:
        c.argument('provider',
                   options_list=['--name', '-n'],
                   type=str,
                   help='Provider id.',
                   validator=provider_id_validator)

    for scope in ['tc provider show', 'tc provider delete']:
        with self.argument_context(scope) as c:
            c.argument('provider',
                       options_list=['--name', '-n'],
                       type=str,
                       help='Provider id.',
                       validator=provider_id_validator,
                       completer=get_provider_completion_list)

    for scope in ['tc provider create', 'tc provider deploy']:
        with self.argument_context(scope) as c:
            c.argument('events',
                       nargs='+',
                       help='Space-seperated provider ids.',
                       validator=provider_event_list_validator)
            c.argument('properties', properties_type)

    with self.argument_context('tc provider create') as c:
        c.argument('url',
                   type=str,
                   help='Provider url.',
                   validator=url_validator)
        c.argument('auth_code',
                   type=str,
                   help='Provider auth code.',
                   validator=auth_code_validator)

    for scope in ['tc provider deploy', 'tc provider upgrade']:
        with self.argument_context(scope) as c:
            c.argument('provider',
                       get_enum_type([
                           'azure.appinsights', 'azure.devops',
                           'azure.devtestlabs'
                       ]),
                       options_list=['--name', '-n'],
                       help='Provider id.')
            c.argument('resource_group_name',
                       resource_group_name_type,
                       help='Name of resource group.')
            c.argument('version',
                       options_list=['--version', '-v'],
                       type=str,
                       help='Provider version. Default: latest stable.',
                       validator=source_version_validator)

    with self.argument_context('tc provider deploy') as c:
        c.argument('location', get_location_type(self.cli_ctx))
        c.argument('tags', tags_type)
Esempio n. 36
0
def load_arguments(self, _):  # pylint: disable=too-many-statements

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

    def _complex_params(command_group):
        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('mysql server replica') as c:
            c.argument(
                'source_server',
                options_list=['--source-server', '-s'],
                help=
                'The name or ID of the master server to 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.')

    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 [
            '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.')
Esempio n. 37
0
def load_arguments(self, _):

    ExpressRoutePeeringType = self.get_models('ExpressRoutePeeringType')

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

    with self.argument_context('network cross-connection') as c:
        c.argument('cross_connection_name',
                   cross_connection_name_type,
                   options_list=('--name', '-n'))

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

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

    with self.argument_context('network cross-connection peering list') as c:
        c.argument('cross_connection_name', id_part=None)
Esempio n. 38
0
def load_arguments(self, _):

    name_arg_type = CLIArgumentType(options_list=('--name', '-n'),
                                    metavar='NAME')
    endpoint_name_type = CLIArgumentType(options_list=('--endpoint-name'),
                                         metavar='ENDPOINT_NAME')
    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('content_paths', nargs='+')
        c.argument('endpoint_name',
                   name_arg_type,
                   id_part='child_name_1',
                   help='Name of the CDN endpoint.')
        c.argument('location',
                   validator=get_default_location_from_resource_group)
        c.argument(
            'origins',
            options_list='--origin',
            nargs='+',
            action=OriginType,
            validator=validate_origin,
            help='Endpoint origin specified by the following space-delimited 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.')
        c.argument('profile_name', help=profile_name_help, id_part='name')

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

    with self.argument_context('cdn endpoint rule') as c:
        c.argument('rule_name', help='Name of the rule.')
        c.argument(
            'order',
            help=
            'The order of the rule. The order number must start from 0 and consecutive.\
                    Rule with higher order will be applied later.')
        c.argument('match_variable',
                   arg_group="Match Condition",
                   help='Name of the match condition.')
        c.argument('operator',
                   arg_group="Match Condition",
                   help='Operator of the match condition.')
        c.argument('selector',
                   arg_group="Match Condition",
                   help='Selector of the match condition.')
        c.argument(
            'match_values',
            arg_group="Match Condition",
            nargs='+',
            help='Match values of the match condition (comma separated).')
        c.argument('transform',
                   arg_group="Match Condition",
                   arg_type=get_enum_type(['Lowercase', 'Uppercase']),
                   nargs='+',
                   help='Transform to apply before matching.')
        c.argument('negate_condition',
                   arg_group="Match Condition",
                   arg_type=get_three_state_flag(),
                   help='If true, negates the condition')
        c.argument('action_name',
                   arg_group="Action",
                   help='Name of the action.')
        c.argument('cache_behavior',
                   arg_group="Action",
                   arg_type=get_enum_type(
                       ['BypassCache', 'Override', 'SetIfMissing']),
                   help='Caching behavior for the requests.')
        c.argument(
            'cache_duration',
            arg_group="Action",
            help='The duration for which the content needs to be cached. \
                   Allowed format is [d.]hh:mm:ss.')
        c.argument('header_action',
                   arg_group="Action",
                   arg_type=get_enum_type(['Append', 'Overwrite', 'Delete']),
                   help='Header action for the requests.')
        c.argument('header_name',
                   arg_group="Action",
                   help='Name of the header to modify.')
        c.argument('header_value',
                   arg_group="Action",
                   help='Value of the header.')
        c.argument(
            'redirect_type',
            arg_group="Action",
            arg_type=get_enum_type(
                ['Moved', 'Found', 'TemporaryRedirect', 'PermanentRedirect']),
            help='The redirect type the rule will use when redirecting traffic.'
        )
        c.argument('redirect_protocol',
                   arg_group="Action",
                   arg_type=get_enum_type(['MatchRequest', 'Http', 'Https']),
                   help='Protocol to use for the redirect.')
        c.argument('custom_hostname',
                   arg_group="Action",
                   help='Host to redirect. \
                   Leave empty to use the incoming host as the destination host.'
                   )
        c.argument(
            'custom_path',
            arg_group="Action",
            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_querystring',
            arg_group="Action",
            help='The set of query strings to be placed in the redirect URL. \
                   leave empty to preserve the incoming query string.')
        c.argument('custom_fragment',
                   arg_group="Action",
                   help='Fragment to add to the redirect URL.')
        c.argument('query_string_behavior',
                   arg_group="Action",
                   arg_type=get_enum_type(
                       ['Include', 'IncludeAll', 'Exclude', 'ExcludeAll']),
                   help='Query string behavior for the requests.')
        c.argument(
            'query_parameters',
            arg_group="Action",
            help='Query parameters to include or exclude (comma separated).')
        c.argument(
            'source_pattern',
            arg_group="Action",
            help=
            'A request URI pattern that identifies the type of requests that may be rewritten.'
        )
        c.argument('destination',
                   help='The destination path to be used in the rewrite.')
        c.argument('preserve_unmatched_path',
                   arg_group="Action",
                   arg_type=get_three_state_flag(),
                   help='If True, the remaining path after the source \
                   pattern will be appended to the new destination path.')
        c.argument('index', type=int, help='The index of the condition/action')

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

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

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

    # Custom Domain #

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

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

    # Origin #
    with self.argument_context('cdn origin') as c:
        c.argument('origin_name', name_arg_type, id_part='name')

    # WAF #

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

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

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

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

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

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

    with self.argument_context('spring-cloud') as c:
        c.argument('resource_group', arg_type=resource_group_name_type)
        c.argument('name', options_list=[
            '--name', '-n'], help='Name of Azure Spring Cloud.')

    # A refactoring work item to move validators to command level to reduce the duplications.
    # https://dev.azure.com/msazure/AzureDMSS/_workitems/edit/11002857/
    with self.argument_context('spring-cloud create') as c:
        c.argument('location', arg_type=get_location_type(self.cli_ctx), validator=validate_location)
        c.argument('reserved_cidr_range', help='Comma-separated list of IP address ranges in CIDR format. The IP ranges are reserved to host underlying Azure Spring Cloud infrastructure, which should be 3 at least /16 unused IP ranges, must not overlap with any Subnet IP ranges.', validator=validate_vnet_required_parameters)
        c.argument('vnet', help='The name or ID of an existing Virtual Network into which to deploy the Spring Cloud instance.', validator=validate_vnet_required_parameters)
        c.argument('app_subnet', help='The name or ID of an existing subnet in "vnet" into which to deploy the Spring Cloud app. Required when deploying into a Virtual Network. Smaller subnet sizes are supported, please refer: https://aka.ms/azure-spring-cloud-smaller-subnet-vnet-docs', validator=validate_vnet_required_parameters)
        c.argument('service_runtime_subnet', options_list=['--service-runtime-subnet', '--svc-subnet'], help='The name or ID of an existing subnet in "vnet" into which to deploy the Spring Cloud service runtime. Required when deploying into a Virtual Network.', validator=validate_vnet)
        c.argument('service_runtime_network_resource_group', options_list=['--service-runtime-network-resource-group', '--svc-nrg'], help='The resource group where all network resources for Azure Spring Cloud service runtime will be created in.', validator=validate_node_resource_group)
        c.argument('app_network_resource_group', options_list=['--app-network-resource-group', '--app-nrg'], help='The resource group where all network resources for apps will be created in.', validator=validate_node_resource_group)
        c.argument('enable_java_agent',
                   arg_type=get_three_state_flag(),
                   help="Java in process agent is now GA-ed and used by default when Application Insights enabled. "
                        "This parameter is no longer needed and will be removed in future release.",
                   validator=validate_java_agent_parameters,
                   deprecate_info=c.deprecate(target='--enable-java-agent', hide=True))
        c.argument('app_insights_key',
                   help="Connection string (recommended) or Instrumentation key of the existing Application Insights.",
                   validator=validate_tracing_parameters_asc_create)
        c.argument('app_insights',
                   help="Name of the existing Application Insights in the same Resource Group. "
                        "Or Resource ID of the existing Application Insights in a different Resource Group.",
                   validator=validate_tracing_parameters_asc_create)
        c.argument('sampling_rate',
                   type=float,
                   help="Sampling Rate of application insights. Minimum is 0, maximum is 100.",
                   validator=validate_tracing_parameters_asc_create)
        c.argument('disable_app_insights',
                   arg_type=get_three_state_flag(),
                   help="Disable Application Insights, "
                        "if not disabled and no existing Application Insights specified with "
                        "--app-insights-key or --app-insights, "
                        "will create a new Application Insights instance in the same resource group.",
                   validator=validate_tracing_parameters_asc_create)

    with self.argument_context('spring-cloud update') as c:
        c.argument('app_insights_key',
                   help="Connection string (recommended) or Instrumentation key of the existing Application Insights.",
                   validator=validate_tracing_parameters_asc_update,
                   deprecate_info=c.deprecate(target='az spring-cloud update --app-insights-key',
                                              redirect='az spring-cloud app-insights update --app-insights-key',
                                              hide=True))
        c.argument('app_insights',
                   help="Name of the existing Application Insights in the same Resource Group. "
                        "Or Resource ID of the existing Application Insights in a different Resource Group.",
                   validator=validate_tracing_parameters_asc_update,
                   deprecate_info=c.deprecate(target='az spring-cloud update --app-insights',
                                              redirect='az spring-cloud app-insights update --app-insights',
                                              hide=True))
        c.argument('disable_app_insights',
                   arg_type=get_three_state_flag(),
                   help="Disable Application Insights, "
                        "if not disabled and no existing Application Insights specified with "
                        "--app-insights-key or --app-insights, "
                        "will create a new Application Insights instance in the same resource group.",
                   validator=validate_tracing_parameters_asc_update,
                   deprecate_info=c.deprecate(target='az spring-cloud update --disable-app-insights',
                                              redirect='az spring-cloud app-insights update --disable',
                                              hide=True))

    for scope in ['spring-cloud create', 'spring-cloud update']:
        with self.argument_context(scope) as c:
            c.argument('sku', type=str, validator=validate_sku, help='Name of SKU, the value is "Basic" or "Standard"')
            c.argument('tags', arg_type=tags_type)

    with self.argument_context('spring-cloud test-endpoint renew-key') as c:
        c.argument('type', type=str, arg_type=get_enum_type(
            TestKeyType), help='Type of test-endpoint key')

    with self.argument_context('spring-cloud app') as c:
        c.argument('service', service_name_type)
        c.argument('name', name_type, help='Name of app.')

    with self.argument_context('spring-cloud app create') as c:
        c.argument('assign_endpoint', arg_type=get_three_state_flag(),
                   help='If true, assign endpoint URL for direct access.', default=False,
                   options_list=['--assign-endpoint', c.deprecate(target='--is-public', redirect='--assign-endpoint', hide=True)])
        c.argument('assign_identity', arg_type=get_three_state_flag(),
                   help='If true, assign managed service identity.')
        c.argument('cpu', type=str, default="1",
                   help='CPU resource quantity. Should be 500m or number of CPU cores.')
        c.argument('memory', type=str, default="1Gi",
                   help='Memory resource quantity. Should be 512Mi or #Gi, e.g., 1Gi, 3Gi.')
        c.argument('instance_count', type=int,
                   default=1, help='Number of instance.', validator=validate_instance_count)
        c.argument('persistent_storage', type=str,
                   help='A json file path for the persistent storages to be mounted to the app')
        c.argument('loaded_public_certificate_file', options_list=['--loaded-public-certificate-file', '-f'], type=str,
                   help='A json file path indicates the certificates which would be loaded to app')

    with self.argument_context('spring-cloud app update') as c:
        c.argument('assign_endpoint', arg_type=get_three_state_flag(),
                   help='If true, assign endpoint URL for direct access.',
                   options_list=['--assign-endpoint', c.deprecate(target='--is-public', redirect='--assign-endpoint', hide=True)])
        c.argument('https_only', arg_type=get_three_state_flag(), help='If true, access app via https', default=False)
        c.argument('enable_end_to_end_tls', arg_type=get_three_state_flag(), help='If true, enable end to end tls')
        c.argument('persistent_storage', type=str,
                   help='A json file path for the persistent storages to be mounted to the app')
        c.argument('loaded_public_certificate_file', type=str, options_list=['--loaded-public-certificate-file', '-f'],
                   help='A json file path indicates the certificates which would be loaded to app')

    with self.argument_context('spring-cloud app append-persistent-storage') as c:
        c.argument('storage_name', type=str,
                   help='Name of the storage resource you created in Azure Spring Cloud.')
        c.argument('persistent_storage_type', options_list=['--persistent-storage-type', '-t'], type=str, help='Type of the persistent storage volumed.')
        c.argument('share_name', type=str,
                   help="The name of the pre-created file share. "
                        "ShareName should be provided only if the type of the persistent storage volume is AzureFileVolume.")
        c.argument('mount_path', type=str, help='The path for the persistent storage volume to be mounted.')
        c.argument('mount_options', nargs='+', help='[optional] The mount options for the persistent storage volume.', default=None)
        c.argument('read_only', arg_type=get_three_state_flag(), help='[optional] If true, the persistent storage volume will be read only.', default=False)

    for scope in ['spring-cloud app update', 'spring-cloud app start', 'spring-cloud app stop', 'spring-cloud app restart', 'spring-cloud app deploy', 'spring-cloud app scale', 'spring-cloud app set-deployment', 'spring-cloud app show-deploy-log']:
        with self.argument_context(scope) as c:
            c.argument('deployment', options_list=[
                '--deployment', '-d'], help='Name of an existing deployment of the app. Default to the production deployment if not specified.', validator=fulfill_deployment_param)
            c.argument('main_entry', options_list=[
                '--main-entry', '-m'], help="The path to the .NET executable relative to zip root.")

    for scope in ['spring-cloud app identity', 'spring-cloud app unset-deployment']:
        with self.argument_context(scope) as c:
            c.argument('name', name_type, help='Name of app.', validator=active_deployment_exist)

    with self.argument_context('spring-cloud app identity assign') 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")

    def prepare_logs_argument(c):
        '''`app log tail` is deprecated. `app logs` is the new choice. They share the same command processor.'''
        c.argument('instance', options_list=['--instance', '-i'], help='Name of an existing instance of the deployment.')
        c.argument('lines', type=int, help='Number of lines to show. Maximum is 10000', validator=validate_log_lines)
        c.argument('follow', options_list=['--follow ', '-f'], help='Specify if the logs should be streamed.', action='store_true')
        c.argument('since', help='Only return logs newer than a relative duration like 5s, 2m, or 1h. Maximum is 1h', validator=validate_log_since)
        c.argument('limit', type=int, help='Maximum kilobytes of logs to return. Ceiling number is 2048.', validator=validate_log_limit)
        c.argument('deployment', options_list=[
            '--deployment', '-d'], help='Name of an existing deployment of the app. Default to the production deployment if not specified.', validator=fulfill_deployment_param)
        c.argument('format_json', nargs='?', const='{timestamp} {level:>5} [{thread:>15.15}] {logger{39}:<40.40}: {message}\n{stackTrace}',
                   help='Format JSON logs if structured log is enabled')

    with self.argument_context('spring-cloud app logs') as c:
        prepare_logs_argument(c)

    with self.argument_context('spring-cloud app log tail') as c:
        prepare_logs_argument(c)

    with self.argument_context('spring-cloud app set-deployment') as c:
        c.argument('deployment', options_list=[
            '--deployment', '-d'], help='Name of an existing deployment of the app.', validator=validate_deployment_name)

    for scope in ['spring-cloud app create', 'spring-cloud app update']:
        with self.argument_context(scope) as c:
            c.argument('enable_persistent_storage', arg_type=get_three_state_flag(),
                       help='If true, mount a 50G (Standard Pricing tier) or 1G (Basic Pricing tier) disk with default path.')

    for scope in ['spring-cloud app update', 'spring-cloud app deployment create', 'spring-cloud app deploy', 'spring-cloud app create']:
        with self.argument_context(scope) as c:
            c.argument('runtime_version', arg_type=get_enum_type(RuntimeVersion),
                       help='Runtime version of used language')
            c.argument('jvm_options', type=str, validator=validate_jvm_options,
                       help="A string containing jvm options, use '=' instead of ' ' for this argument to avoid bash parse error, eg: --jvm-options='-Xms1024m -Xmx2048m'")
            c.argument('env', env_type)
            c.argument('disable_probe', arg_type=get_three_state_flag(), help='If true, disable the liveness and readiness probe.')

    with self.argument_context('spring-cloud app scale') as c:
        c.argument('cpu', type=str, help='CPU resource quantity. Should be 500m or number of CPU cores.')
        c.argument('memory', type=str, help='Memory resource quantity. Should be 512Mi or #Gi, e.g., 1Gi, 3Gi.')
        c.argument('instance_count', type=int, help='Number of instance.', validator=validate_instance_count)

    for scope in ['spring-cloud app deploy', 'spring-cloud app deployment create']:
        with self.argument_context(scope) as c:
            c.argument(
                'artifact_path', options_list=['--artifact-path',
                                               c.deprecate(target='--jar-path', redirect='--artifact-path', hide=True),
                                               c.deprecate(target='-p', redirect='--artifact-path', hide=True)],
                help='Deploy the specified pre-built artifact (jar or netcore zip).', validator=validate_jar)
            c.argument(
                'source_path', nargs='?', const='.',
                help="Deploy the specified source folder. The folder will be packed into tar, uploaded, and built using kpack. Default to the current folder if no value provided.")
            c.argument(
                'disable_validation', arg_type=get_three_state_flag(),
                help='If true, disable jar validation.')
            c.argument(
                'main_entry', options_list=[
                    '--main-entry', '-m'], help="A string containing the path to the .NET executable relative to zip root.")
            c.argument(
                'target_module', help='Child module to be deployed, required for multiple jar packages built from source code.')
            c.argument(
                'version', help='Deployment version, keep unchanged if not set.')

    with self.argument_context('spring-cloud app deployment create') as c:
        c.argument('skip_clone_settings', help='Create staging deployment will automatically copy settings from production deployment.',
                   action='store_true')
        c.argument('cpu', type=str, help='CPU resource quantity. Should be 500m or number of CPU cores.')
        c.argument('memory', type=str, help='Memory resource quantity. Should be 512Mi or #Gi, e.g., 1Gi, 3Gi.')
        c.argument('instance_count', type=int, help='Number of instance.', validator=validate_instance_count)

    with self.argument_context('spring-cloud app deployment') as c:
        c.argument('app', app_name_type, help='Name of app.',
                   validator=validate_app_name)
        c.argument('name', name_type, help='Name of deployment.')

    for scope in ['spring-cloud app deployment generate-heap-dump', 'spring-cloud app deployment generate-thread-dump']:
        with self.argument_context(scope) as c:
            c.argument('deployment', options_list=[
                '--deployment', '-d'], help='Name of an existing deployment of the app. Default to the production deployment if not specified.', validator=fulfill_deployment_param)
            c.argument('app_instance', help='Target app instance you want to dump.')
            c.argument('file_path', help='The mount file path for your dump file.')

    with self.argument_context('spring-cloud app deployment start-jfr') as c:
        c.argument('deployment', options_list=[
            '--deployment', '-d'], help='Name of an existing deployment of the app. Default to the production deployment if not specified.', validator=fulfill_deployment_param)
        c.argument('app_instance', help='Target app instance you want to dump.')
        c.argument('file_path', help='The mount file path for your dump file.')
        c.argument('duration', type=str, default="60s", help='Duration of JFR.')

    with self.argument_context('spring-cloud app binding') as c:
        c.argument('app', app_name_type, help='Name of app.',
                   validator=active_deployment_exist_under_app)
        c.argument('name', name_type, help='Name of service binding.')

    for scope in ['spring-cloud app binding cosmos add', 'spring-cloud app binding mysql add', 'spring-cloud app binding redis add']:
        with self.argument_context(scope) as c:
            c.argument('resource_id', validator=validate_resource_id,
                       help='Azure resource ID of the service to bind with.')

    for scope in ['spring-cloud app binding cosmos add', 'spring-cloud app binding cosmos update']:
        with self.argument_context(scope) as c:
            c.argument(
                'database_name', help='Name of database. Required for mongo, sql, gremlin')
            c.argument(
                'key_space', help='Cassandra key space. Required for cassandra')
            c.argument('collection_name',
                       help='Name of collection. Required for gremlin')

    with self.argument_context('spring-cloud app binding cosmos add') as c:
        c.argument('api_type', help='Type of API.', arg_type=get_enum_type(
            ApiType), validator=validate_cosmos_type)

    for scope in ['spring-cloud app binding mysql add', 'spring-cloud app binding mysql update']:
        with self.argument_context(scope) as c:
            c.argument('key', help='API key of the service.')
            c.argument('username', help='Username of the database')
            c.argument('database_name', help='Database name')

    for scope in ['spring-cloud app binding redis add', 'spring-cloud app binding redis update']:
        with self.argument_context(scope) as c:
            c.argument('key', help='Api key of the service.')
            c.argument('disable_ssl', arg_type=get_three_state_flag(), help='If true, disable SSL. If false, enable SSL.', default=False)

    with self.argument_context('spring-cloud app append-loaded-public-certificate') as c:
        c.argument('certificate_name', help='Name of the certificate to be appended')
        c.argument('load_trust_store', arg_type=get_three_state_flag(), help='If true, the certificate would be loaded into trust store for Java applications', default=False)

    with self.argument_context('spring-cloud config-server set') as c:
        c.argument('config_file',
                   help='A yaml file path for the configuration of Spring Cloud config server')

    for scope in ['spring-cloud config-server git set', 'spring-cloud config-server git repo add', 'spring-cloud config-server git repo update']:
        with self.argument_context(scope) as c:
            c.argument('uri', help='Uri of the added config.')
            c.argument('label', help='Label of the added config.')
            c.argument(
                'search_paths', help='search_paths of the added config, use , as delimiter for multiple paths.')
            c.argument('username', help='Username of the added config.')
            c.argument('password', help='Password of the added config.')
            c.argument('host_key', help='Host key of the added config.')
            c.argument('host_key_algorithm',
                       help='Host key algorithm of the added config.')
            c.argument('private_key', help='Private_key of the added config.')
            c.argument('strict_host_key_checking',
                       help='Strict_host_key_checking of the added config.')

    for scope in ['spring-cloud config-server git repo add', 'spring-cloud config-server git repo update', 'spring-cloud config-server git repo remove']:
        with self.argument_context(scope) as c:
            c.argument('repo_name', help='Name of the repo.')

    for scope in ['spring-cloud config-server git repo add', 'spring-cloud config-server git repo update']:
        with self.argument_context(scope) as c:
            c.argument(
                'pattern', help='Pattern of the repo, use , as delimiter for multiple patterns')

    with self.argument_context('spring-cloud test-endpoint list') as c:
        c.argument('app', app_name_type, help='Name of app.',
                   validator=validate_app_name)
        c.argument('deployment', options_list=[
            '--deployment', '-d'], help='Name of an existing deployment of the app. Default to the production deployment if not specified.', validator=validate_deployment_name)

    with self.argument_context('spring-cloud storage') as c:
        c.argument('service', service_name_type)
        c.argument('name', help='Name of storage.')

    with self.argument_context('spring-cloud storage add') as c:
        c.argument('storage_type', help='The type of the torage. e.g. StorageAccount')
        c.argument('account_name', help='The name of the storage account.')
        c.argument('account_key', help='The account key of the storage account.')

    with self.argument_context('spring-cloud storage update') as c:
        c.argument('storage_type', help='The type of the torage. e.g. StorageAccount')
        c.argument('account_name', help='The name of the storage account.')
        c.argument('account_key', help='The account key of the storage account.')

    with self.argument_context('spring-cloud certificate') as c:
        c.argument('service', service_name_type)
        c.argument('name', help='Name of certificate.')

    with self.argument_context('spring-cloud certificate add') as c:
        c.argument('vault_uri', help='The key vault uri where store the certificate')
        c.argument('vault_certificate_name', help='The certificate name in key vault')
        c.argument('only_public_cert', arg_type=get_three_state_flag(),
                   help='If true, only import public certificate part from key vault.', default=False)
        c.argument('public_certificate_file', options_list=['--public-certificate-file', '-f'],
                   help='A file path for the public certificate to be uploaded')

    with self.argument_context('spring-cloud certificate list') as c:
        c.argument('certificate_type', help='Type of uploaded certificate',
                   arg_type=get_enum_type(['KeyVaultCertificate', 'ContentCertificate']))

    with self.argument_context('spring-cloud app custom-domain') as c:
        c.argument('service', service_name_type)
        c.argument('app', app_name_type, help='Name of app.', validator=active_deployment_exist_under_app)
        c.argument('domain_name', help='Name of custom domain.')

    with self.argument_context('spring-cloud app custom-domain bind') as c:
        c.argument('certificate', type=str, help='Certificate name in Azure Spring Cloud.')
        c.argument('enable_end_to_end_tls', arg_type=get_three_state_flag(), help='If true, enable end to end tls')

    with self.argument_context('spring-cloud app custom-domain update') as c:
        c.argument('certificate', help='Certificate name in Azure Spring Cloud.')
        c.argument('enable_end_to_end_tls', arg_type=get_three_state_flag(), help='If true, enable end to end tls')

    with self.argument_context('spring-cloud app-insights update') as c:
        c.argument('app_insights_key',
                   help="Connection string (recommended) or Instrumentation key of the existing Application Insights.",
                   validator=validate_app_insights_parameters)
        c.argument('app_insights',
                   help="Name of the existing Application Insights in the same Resource Group. "
                        "Or Resource ID of the existing Application Insights in a different Resource Group.",
                   validator=validate_app_insights_parameters)
        c.argument('sampling_rate',
                   type=float,
                   help="Sampling Rate of application insights. Maximum is 100.",
                   validator=validate_app_insights_parameters)
        c.argument('disable',
                   arg_type=get_three_state_flag(),
                   help="Disable Application Insights.",
                   validator=validate_app_insights_parameters)
Esempio n. 40
0
def load_team_arguments(self, _):
    with self.argument_context('devops login') as context:
        context.argument(
            'organization',
            help=
            'Azure DevOps organization URL. Example: https://dev.azure.com/MyOrganizationName'
        )

    with self.argument_context('devops logout') as context:
        context.argument(
            'organization',
            help=
            'Azure DevOps organization URL. Example: https://dev.azure.com/MyOrganizationName/. '
            'If no organization is specified, all organizations will be logged out.'
        )

    with self.argument_context('devops configure') as context:
        context.argument('defaults',
                         options_list=('--defaults', '-d'),
                         nargs='*')
        context.argument('use_git_aliases', arg_type=get_three_state_flag())
        context.argument('list_config', options_list=('--list', '-l'))

    with self.argument_context('devops') as context:
        context.argument('repository', options_list=('--repository', '-r'))

    with self.argument_context('devops project') as context:
        context.argument('process', options_list=('--process', '-p'))
        context.argument('source_control',
                         options_list=('--source-control', '-s'),
                         **enum_choice_list(_SOURCE_CONTROL_VALUES))
        context.argument('description', options_list=('--description', '-d'))
        context.argument('state', **enum_choice_list(_STATE_VALUES))
        context.argument('visibility',
                         **enum_choice_list(_PROJECT_VISIBILITY_VALUES))

    with self.argument_context('devops project delete') as context:
        context.argument('yes',
                         options_list=['--yes', '-y'],
                         action='store_true',
                         help='Do not prompt for confirmation.')

    with self.argument_context('devops project list') as context:
        context.argument(
            'state_filter',
            arg_type=get_enum_type(_PROJECT_GET_STATE_VALUE_FILTER),
            help='State filter.')
        context.argument(
            'continuation_token',
            help='Continuation token. '
            'This can be retrived from previous run of this command if more results are present.'
        )
        context.argument('get_default_team_image_url',
                         arg_type=get_three_state_flag(),
                         help='Whether to get default team image url or not.')

    with self.argument_context('devops service-endpoint create') as context:
        context.argument('encoding',
                         help='Encoding of the input file.',
                         **enum_choice_list(_FILE_ENCODING_TYPE_VALUES))

    with self.argument_context('devops invoke') as context:
        context.argument('route_parameters',
                         nargs='*',
                         help='Specifies the list of route parameters')
        context.argument('query_parameters',
                         nargs='*',
                         help='Specifies the list of query parameters')
        context.argument('http_method',
                         arg_type=get_enum_type(_HTTP_METHOD_VALUES),
                         help='Specifies the method used for the request.')
        context.argument('media_type',
                         help='Specifies the content type of the request.')
        context.argument('accept_media_type',
                         help='Specifies the content type of the response.')
        context.argument(
            'in_file',
            help=
            'Path and file name to the file that contains the contents of the request.'
        )
        context.argument(
            'encoding',
            help=
            'Encoding of the input file. Used in conjunction with --in-file.',
            **enum_choice_list(_FILE_ENCODING_TYPE_VALUES))
        context.argument(
            'out_file',
            help=
            'Path and file name to the file  for which this function saves the response body.'
        )
        context.argument('area', help='The area to find the resource.')
        context.argument('resource',
                         help='The name of the resource to operate on.')
        context.argument('api_version',
                         help='The version of the API to target')

    with self.argument_context('devops user') as context:
        context.argument('license_type',
                         arg_type=get_enum_type(_LICENSE_TYPES))
    with self.argument_context('devops user add') as context:
        context.argument(
            'send_email_invite',
            arg_type=get_three_state_flag(),
            help='Whether to send email invite for new user or not.')

    with self.argument_context('devops security group create') as context:
        context.argument(
            'project',
            help=
            'Name or ID of the project in which Azure DevOps group should be created.'
        )
        context.argument('scope', **enum_choice_list(_SCOPE_VALUES))

    with self.argument_context('devops security group list') as context:
        context.argument('project',
                         help='List groups for a particular project')
        context.argument('scope', **enum_choice_list(_SCOPE_VALUES))

    with self.argument_context('devops security group membership') as context:
        context.argument('relationship',
                         arg_type=get_enum_type(_RELATIONSHIP_TYPES),
                         help='Get member of/members for this group.')

    with self.argument_context('devops security permission') as context:
        context.argument('namespace_id',
                         options_list=('--namespace-id', '--id'),
                         help='ID of security namespace')
        context.argument('token', help='Security token.')
        context.argument('subject', help='User Email ID or Group descriptor')

    with self.argument_context('devops security permission update') as context:
        context.argument(
            'merge',
            arg_type=get_three_state_flag(),
            help='If set, the existing ACE has its allow and deny merged with \
                         the incoming ACE\'s allow and deny. If unset, the existing ACE is displaced.'
        )
        context.argument(
            'allow_bit',
            type=int,
            help=
            'Allow bit or addition of bits. Required if --deny-bit is missing.'
        )
        context.argument(
            'deny_bit',
            type=int,
            help=
            'Deny bit or addition of bits. Required if --allow-bit is missing.'
        )

    with self.argument_context('devops security permission reset') as context:
        context.argument(
            'permission_bit',
            type=int,
            help=
            'Permission bit or addition of permission bits which needs to be reset\
                         for given user/group and token.')

    with self.argument_context('devops extension') as context:
        context.argument('include_built_in',
                         arg_type=get_three_state_flag(),
                         help='Include built in extensions.')
        context.argument('include_disabled',
                         arg_type=get_three_state_flag(),
                         help='Include disabled extensions.')
        context.argument('publisher_name', help='Publisher Name')
        context.argument('extension_name', help='Extension Name')
        context.argument('search_query',
                         options_list=('--search-query', '-q'),
                         help='Search term')

    with self.argument_context('devops') as context:
        load_global_args(context)

    with self.argument_context('repos') as context:
        load_global_args(context)

    with self.argument_context('artifacts') as context:
        load_global_args(context)

    with self.argument_context('boards') as context:
        load_global_args(context)

    with self.argument_context('pipelines') as context:
        load_global_args(context)

    with self.argument_context('devops wiki') as context:
        context.argument('wiki_type',
                         options_list=('--wiki-type', '--type'),
                         **enum_choice_list(_WIKI_TYPE_VALUES))
        context.argument('version', options_list=('--version', '-v'))
        context.argument('encoding',
                         **enum_choice_list(_FILE_ENCODING_TYPE_VALUES))

    with self.argument_context('devops wiki list') as context:
        context.argument('scope', **enum_choice_list(_SCOPE_VALUES))
Esempio n. 41
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")
        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')
Esempio n. 42
0
def load_arguments(self, _):
    from argcomplete.completers import FilesCompleter

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

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

    from knack.arguments import ignore_type, CLIArgumentType

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

    # BASIC PARAMETER CONFIGURATION

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('policy assignment 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('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'])
Esempio n. 43
0
def load_arguments(self, _):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    for scope in ['mysql server configuration', 'postgres server configuration']:
        with self.argument_context(scope) as c:
            c.argument('server_name', options_list=['--server-name', '-s'])
            c.argument('configuration_name', id_part='child_name_1', options_list=['--name', '-n'])
Esempio n. 45
0
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())
Esempio n. 46
0
def load_arguments(self, _):
    batch_name_type = CLIArgumentType(
        help='Name of the Batch account.',
        options_list=('--account-name',),
        completer=get_resource_name_completion_list('Microsoft.Batch/batchAccounts'),
        id_part=None)

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

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

    with self.argument_context('batch account show') as c:
        c.argument('resource_group_name', resource_group_name_type, help='Name of the resource group. If not specified will display currently set account.', required=False)
        c.argument('account_name', batch_name_type, options_list=('--name', '-n'), help='Name of the batch account to show. If not specified will display currently set account.', required=False)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('batch pool create') as c:
        c.argument('os_family', arg_type=get_enum_type(['2', '3', '4', '5']))
        c.argument('auto_scale_formula', help='A formula for the desired number of compute nodes in the pool. The formula is checked for validity before the pool is created. If the formula is not valid, the Batch service rejects the request with detailed error information. For more information about specifying this formula, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/.')
        c.extra('image', completer=load_node_agent_skus, arg_group="Pool: Virtual Machine Configuration",
                help="OS image reference. This can be either 'publisher:offer:sku[:version]' format, or a fully qualified ARM image id of the form '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName}'. If 'publisher:offer:sku[:version]' format, version is optional and if omitted latest will be used. Valid values can be retrieved via 'az batch pool node-agent-skus list'. For example: 'MicrosoftWindowsServer:WindowsServer:2012-R2-Datacenter:latest'")

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

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

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

    for item in ['batch certificate delete', 'batch certificate create', 'batch pool resize', 'batch pool reset', 'batch job list', 'batch task create']:
        with self.argument_context(item) as c:
            c.extra('account_name', arg_group='Batch Account', validator=validate_client_parameters,
                    help='The Batch account name. Alternatively, set by environment variable: AZURE_BATCH_ACCOUNT')
            c.extra('account_key', arg_group='Batch Account',
                    help='The Batch account key. Alternatively, set by environment variable: AZURE_BATCH_ACCESS_KEY')
            c.extra('account_endpoint', arg_group='Batch Account',
                    help='Batch service endpoint. Alternatively, set by environment variable: AZURE_BATCH_ENDPOINT')
Esempio n. 47
0
def load_arguments(self, _):
    from argcomplete.completers import FilesCompleter

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

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

    from knack.arguments import ignore_type, CLIArgumentType

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

    # 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'])
Esempio n. 48
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'))
Esempio n. 49
0
def load_arguments(self, _):
    # ARGUMENT DEFINITIONS
    datalake_store_name_type = CLIArgumentType(help='Name of the Data Lake Store account.', options_list=['--account_name'], completer=get_resource_name_completion_list('Microsoft.DataLakeStore/accounts'), id_part='name')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('dls fs access remove-all') as c:
        c.argument('default_acl', help='A switch that, if specified, indicates that the remove ACL operation should remove the default ACL of the folder. Otherwise the regular ACL is removed.', action='store_true')
Esempio n. 50
0
def load_arguments(self, _):
    with self.argument_context('dataprotection backup-instance create') as c:
        c.argument('backup_instance',
                   type=validate_file_or_dict,
                   help='Request body for operation Expected value: '
                   'json-string/@json-file.')

    with self.argument_context(
            'dataprotection backup-instance validate-for-backup') as c:
        c.argument('backup_instance',
                   type=validate_file_or_dict,
                   help='Request body for operation Expected value: '
                   'json-string/@json-file.')

    with self.argument_context(
            'dataprotection backup-instance initialize') as c:
        c.argument(
            'datasource_type',
            arg_type=get_enum_type(get_datasource_types()),
            help="Specify the datasource type of the resource to be backed up")
        c.argument('datasource_id',
                   type=str,
                   help="ARM Id of the resource to be backed up")
        c.argument('datasource_location',
                   options_list=['--datasource-location', '-l'],
                   arg_type=get_location_type(self.cli_ctx))
        c.argument(
            'policy_id',
            type=str,
            help="Id of the backup policy the datasource will be associated")
        c.argument(
            'secret_store_type',
            arg_type=get_enum_type(get_secret_store_type_values()),
            help="Specify the secret store type to use for authentication")
        c.argument(
            'secret_store_uri',
            type=str,
            help="specify the secret store uri to use for authentication")

    with self.argument_context(
            'dataprotection backup-instance update-policy') as c:
        c.argument('backup_instance_name',
                   type=str,
                   help="Backup instance name.")
        c.argument('resource_group_name', resource_group_name_type)
        c.argument('vault_name', type=str, help="Name of the vault.")
        c.argument(
            'policy_id',
            type=str,
            help=
            "specify the ID of the new policy with which backup instance will be associated with."
        )

    with self.argument_context('dataprotection recovery-point list') as c:
        c.argument('start_time',
                   type=datetime_type,
                   help="specify the start date in UTC (yyyy-mm-ddTHH:MM:SS)")
        c.argument('end_time',
                   type=datetime_type,
                   help="specify the end date in UTC (yyyy-mm-ddTHH:MM:SS)")

    with self.argument_context('dataprotection backup-policy create') as c:
        c.argument('policy',
                   type=validate_file_or_dict,
                   help='Request body for operation Expected value: '
                   'json-string/@json-file.')

    with self.argument_context(
            'dataprotection backup-policy get-default-policy-template') as c:
        c.argument(
            'datasource_type',
            arg_type=get_enum_type(get_datasource_types()),
            help="Specify the datasource type of the resource to be backed up")

    with self.argument_context(
            'dataprotection backup-instance list-from-resourcegraph') as c:
        c.argument('subscriptions',
                   type=str,
                   nargs='+',
                   help="List of subscription Ids.")
        c.argument('resource_groups',
                   type=str,
                   nargs='+',
                   help="List of resource groups.")
        c.argument('vaults', type=str, nargs='+', help="List of vault names.")
        c.argument('datasource_type',
                   arg_type=get_enum_type(get_datasource_types()),
                   help="Specify the datasource type")
        c.argument('subscriptions',
                   type=str,
                   nargs='+',
                   help="List of subscription Ids.")
        c.argument('protection_status',
                   arg_type=get_enum_type(get_protection_status_values()),
                   nargs='+',
                   help="specify protection status.")
        c.argument('datasource_id',
                   type=str,
                   nargs='+',
                   help="specify datasource id filter to apply.")

    with self.argument_context(
            'dataprotection job list-from-resourcegraph') as c:
        c.argument('subscriptions',
                   type=str,
                   nargs='+',
                   help="List of subscription Ids.")
        c.argument('resource_groups',
                   type=str,
                   nargs='+',
                   help="List of resource groups.")
        c.argument('vaults', type=str, nargs='+', help="List of vault names.")
        c.argument('datasource_type',
                   arg_type=get_enum_type(get_datasource_types()),
                   help="Specify the datasource type")
        c.argument('subscriptions',
                   type=str,
                   nargs='+',
                   help="List of subscription Ids.")
        c.argument(
            'start_time',
            type=schedule_days_type,
            help="specify start time of the job in UTC (yyyy-mm-ddTHH:MM:SS).")
        c.argument(
            'end_time',
            type=schedule_days_type,
            help="specify end time of the job in UTC (yyyy-mm-ddTHH:MM:SS).")
        c.argument('status',
                   arg_type=get_enum_type(get_job_status_values()),
                   nargs='+',
                   help="specify job status values for filter.")
        c.argument('operation',
                   arg_type=get_enum_type(get_job_operation_values()),
                   nargs='+',
                   help="specify job operation values for filter.")
        c.argument('datasource_id',
                   type=str,
                   nargs='+',
                   help="specify datasource id filter to apply")

    with self.argument_context(
            'dataprotection backup-policy trigger create-schedule') as c:
        c.argument('interval_type',
                   arg_type=get_enum_type(get_backup_frequency_values()),
                   help="Specify Backup Frequency.")
        c.argument('interval_count',
                   type=int,
                   help="Specify duration of backup frequency.")
        c.argument(
            'schedule_days',
            type=schedule_days_type,
            nargs='+',
            help="specify the backup schedule time in UTC (yyyy-mm-ddTHH:MM:SS)"
        )

    with self.argument_context(
            'dataprotection backup-policy trigger set') as c:
        c.argument('policy',
                   type=validate_file_or_dict,
                   help="Existing policy Json string or file.")
        c.argument('schedule',
                   type=str,
                   nargs='+',
                   help="Specify schedule time intervals for backup rule.")

    with self.argument_context(
            'dataprotection backup-policy retention-rule create-lifecycle'
    ) as c:
        c.argument('source_datastore',
                   arg_type=get_enum_type(get_datastore_type_values()),
                   help="Specify source datastore.")
        c.argument('target_datastore',
                   arg_type=get_enum_type(get_datastore_type_values()),
                   help="Specify target datastore.")
        c.argument('retention_duration_type',
                   options_list=['--retention-duration-type', '--type'],
                   arg_type=get_enum_type(get_duration_type_values()),
                   help="Retention duration type.")
        c.argument('retention_duration_count',
                   options_list=['--retention-duration-count', '--count'],
                   type=int,
                   help="Retention duration count.")
        c.argument(
            'copy_option',
            arg_type=get_enum_type(get_copy_option_values()),
            help=
            "Specify copy option from source datastore to target datastore.")

    with self.argument_context(
            'dataprotection backup-policy retention-rule set') as c:
        c.argument(
            'name',
            arg_type=get_enum_type(get_retention_rule_name_values()),
            help="Specify the retention rule name to be edited in policy.")
        c.argument('policy',
                   type=validate_file_or_dict,
                   help="Policy Json string or file.")
        c.argument(
            'lifecycles',
            type=validate_file_or_dict,
            nargs='+',
            help=
            "lifecycles to be associated with the retention rule. Specify space separated json file names."
        )

    with self.argument_context(
            'dataprotection backup-policy retention-rule remove') as c:
        c.argument(
            'name',
            arg_type=get_enum_type(get_retention_rule_name_values()),
            help="Specify the retention rule name to be removed in policy.")
        c.argument('policy',
                   type=validate_file_or_dict,
                   help="Existing policy Json string or file.")

    with self.argument_context(
            'dataprotection backup-policy tag create-absolute-criteria') as c:
        c.argument('absolute_criteria',
                   arg_type=get_enum_type(get_absolute_criteria_values()),
                   help="Specify retention criteria.")

    with self.argument_context(
            'dataprotection backup-policy tag create-generic-criteria') as c:
        c.argument('days_of_week',
                   nargs='+',
                   arg_type=get_enum_type(get_days_of_week_values()),
                   help="Specify days of week.")
        c.argument('weeks_of_month',
                   nargs='+',
                   arg_type=get_enum_type(get_weeks_of_month_values()),
                   help="Specify weeks of month")
        c.argument('months_of_year',
                   nargs='+',
                   arg_type=get_enum_type(get_months_of_year_values()),
                   help="Specify months of year.")
        c.argument(
            'days_of_month',
            nargs='+',
            type=str,
            help="Specify days of month. Allowed values are 1 to 28 and Last")

    with self.argument_context('dataprotection backup-policy tag set') as c:
        c.argument('name',
                   arg_type=get_enum_type(get_tag_name_values()),
                   help="Specify the tag name to be edited in policy.")
        c.argument('policy',
                   type=validate_file_or_dict,
                   help="Policy Json string or file.")
        c.argument(
            'criteria',
            type=validate_file_or_dict,
            nargs='+',
            help=
            "crtierias to be associated with the tag. Specify space separated json file names."
        )

    with self.argument_context('dataprotection backup-policy tag remove') as c:
        c.argument('name',
                   arg_type=get_enum_type(get_tag_name_values()),
                   help="Specify the tag name to be removed in policy.")
        c.argument('policy',
                   type=validate_file_or_dict,
                   help="Existing policy Json string or file.")

    with self.argument_context(
            'dataprotection backup-instance restore initialize-for-data-recovery'
    ) as c:
        c.argument(
            'target_resource_id',
            type=str,
            help="specify the resource ID to which the data will be restored.")
        c.argument(
            'recovery_point_id',
            type=str,
            help=
            "specify the recovery point ID which will be used for restoring the data."
        )
        c.argument(
            'point_in_time',
            type=datetime_type,
            help=
            "specify the point in time which will be used for restoring the data in UTC (yyyy-mm-ddTHH:MM:SS)"
        )
        c.argument('datasource_type',
                   arg_type=get_enum_type(get_datasource_types()),
                   help="Specify the datasource type")
        c.argument(
            'source_datastore',
            arg_type=get_enum_type(get_datastore_type_values()),
            help=
            "Specify the datastore type of the given recovery point or point in time."
        )
        c.argument('restore_location',
                   type=str,
                   help="Specify the restore location.")
        c.argument(
            'secret_store_type',
            arg_type=get_enum_type(get_secret_store_type_values()),
            help="Specify the secret store type to use for authentication")
        c.argument(
            'secret_store_uri',
            type=str,
            help="Specify the secret store uri to use for authentication")
        c.argument(
            'rehydration_priority',
            arg_type=get_enum_type(get_rehydration_priority_values()),
            help="Specify the rehydration priority for rehydrate restore.")
        c.argument(
            'rehydration_duration',
            type=int,
            help="Specify the rehydration duration for rehydrate restore.")

    with self.argument_context(
            'dataprotection backup-instance restore initialize-for-data-recovery-as-files'
    ) as c:
        c.argument(
            'target_blob_container_url',
            type=str,
            help=
            "specify the blob container url to which the data will be restored."
        )
        c.argument(
            'target_file_name',
            type=str,
            help="specify the file name to which the data will be restored.")
        c.argument(
            'recovery_point_id',
            type=str,
            help=
            "specify the recovery point ID which will be used for restoring the data."
        )
        c.argument(
            'point_in_time',
            type=datetime_type,
            help=
            "specify the point in time which will be used for restoring the data in UTC (yyyy-mm-ddTHH:MM:SS)"
        )
        c.argument('datasource_type',
                   arg_type=get_enum_type(get_datasource_types()),
                   help="Specify the datasource type")
        c.argument(
            'source_datastore',
            arg_type=get_enum_type(get_datastore_type_values()),
            help=
            "Specify the datastore type of the given recovery point or point in time."
        )
        c.argument('restore_location',
                   type=str,
                   help="specify the restore location.")
        c.argument(
            'rehydration_priority',
            arg_type=get_enum_type(get_rehydration_priority_values()),
            help="Specify the rehydration priority for rehydrate restore.")
        c.argument(
            'rehydration_duration',
            type=int,
            help="Specify the rehydration duration for rehydrate restore.")

    with self.argument_context(
            'dataprotection backup-instance restore initialize-for-item-recovery'
    ) as c:
        c.argument('restore_location',
                   type=str,
                   help="specify the restore location.")
        c.argument(
            'recovery_point_id',
            type=str,
            help=
            "specify the recovery point ID which will be used for restoring the data."
        )
        c.argument(
            'point_in_time',
            type=datetime_type,
            help=
            "specify the point in time which will be used for restoring the data in UTC (yyyy-mm-ddTHH:MM:SS)."
        )
        c.argument(
            'source_datastore',
            arg_type=get_enum_type(get_datastore_type_values()),
            help=
            "Specify the datastore type of the given recovery point or point in time."
        )
        c.argument('backup_instance_id',
                   type=str,
                   help="specify the backup instance ID.")
        c.argument('datasource_type',
                   arg_type=get_enum_type(get_datasource_types()),
                   help="Specify the datasource type")
        c.argument('container_list',
                   type=str,
                   nargs='+',
                   help="specify the list of containers to restore.")
        c.argument('from_prefix_pattern',
                   type=str,
                   nargs='+',
                   help="specify the prefix pattern for start range.")
        c.argument('to_prefix_pattern',
                   type=str,
                   nargs='+',
                   help="specify the prefix pattern for end range.")

    with self.argument_context('dataprotection backup-vault list') as c:
        c.argument('resource_group_name', resource_group_name_type)
Esempio n. 51
0
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',
                   arg_type=get_enum_type(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',
                   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', arg_type=image_by_tag_type, 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('os_type',
                   options_list=['--os'],
                   help='The operating system type required for the build.',
                   arg_type=get_enum_type(OsType))

    with self.argument_context('acr import') as c:
        c.argument(
            'source',
            help=
            "The source identifier in the format '[registry.azurecr.io/]repository[:tag]' or '[registry.azurecr.io/]repository@digest'."
        )
        c.argument(
            'source_registry',
            options_list=['--registry', '-r'],
            help=
            'The source container registry can be name, login server or resource ID of the source registry.'
        )
        c.argument('target_tags', arg_type=image_by_tag_type, action='append')
        c.argument(
            'repository',
            help='The repository name to do a manifest-only copy for images.',
            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(
            'status',
            help="Indicates whether content-trust is enabled or disabled.",
            arg_type=get_enum_type(PolicyStatus))

    with self.argument_context('acr repository') as c:
        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 delete') as c:
        c.argument('manifest',
                   nargs='?',
                   required=False,
                   const='',
                   default=None,
                   help=argparse.SUPPRESS)
        c.argument('tag', help=argparse.SUPPRESS)

    with self.argument_context('acr repository untag') as c:
        c.argument('image', arg_type=image_by_tag_type)

    with self.argument_context('acr create') as c:
        c.argument('registry_name', completer=None)
        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.',
            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').",
            completer=FilesCompleter())
        c.argument(
            'file',
            options_list=['--file', '-f'],
            help=
            "The task template/definition file path relative to the source context."
        )
        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.",
                   action='append',
                   validator=validate_set)
        c.argument('set_secret',
                   help="Secret value in 'name[=value]' format.",
                   action='append',
                   validator=validate_set_secret)

    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('arg',
                   options_list=['--build-arg'],
                   help="Build argument in 'name[=value]' format.",
                   action='append',
                   validator=validate_arg)
        c.argument('secret_arg',
                   options_list=['--secret-build-arg'],
                   help="Secret build argument in 'name[=value]' format.",
                   action='append',
                   validator=validate_secret_arg)

    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.',
                   arg_type=get_enum_type(BuildTaskStatus))
        c.argument(
            'cpu',
            type=int,
            help=
            'The CPU configuration in terms of number of cores required for the build.'
        )
        c.argument('repository_url',
                   options_list=['--context', '-c'],
                   help="The full URL to the source code repository.")
        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."
        )
        c.argument(
            'with_secure_properties',
            help=
            "Indicates whether the secure properties of a build task should be returned.",
            action='store_true')
        # 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_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(
            'base_image_trigger',
            help=
            "The type of the auto trigger for base image dependency updates.",
            arg_type=get_enum_type(BuildBaseImageTriggerType))
        # 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.',
                   arg_type=get_enum_type(BuildStatus))
        c.argument('image', arg_type=image_by_tag_or_digest_type)
        c.argument('no_archive',
                   help='Indicates whether the build should be archived.',
                   arg_type=get_three_state_flag())
        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)

    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=
            "The relative path of the the task/docker file to the source code root folder. Task files must be suffixed with '.yaml'."
        )
        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)."
        )
        c.argument('arg',
                   help="Build argument in 'name[=value]' format.",
                   action='append',
                   validator=validate_arg)
        c.argument('secret_arg',
                   help="Secret build argument in 'name[=value]' format.",
                   action='append',
                   validator=validate_secret_arg)
        c.argument('set_value',
                   options_list=['--set'],
                   help="Task value in 'name[=value]' format.",
                   action='append',
                   validator=validate_set)
        c.argument('set_secret',
                   help="Secret task value in 'name[=value]' format.",
                   action='append',
                   validator=validate_set_secret)

        # Source Trigger parameters
        c.argument('source_trigger_name',
                   help="The name of the source trigger.")
        c.argument(
            'commit_trigger_enabled',
            help=
            "Indicates whether the source control commit trigger is enabled.",
            arg_type=get_three_state_flag())
        c.argument(
            'pull_request_trigger_enabled',
            help=
            "Indicates whether the source control pull request 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."
        )
        c.argument('branch', help="The source control branch name.")
        c.argument('base_image_trigger_name',
                   help="The name of the base image trigger.")
        c.argument('base_image_trigger_enabled',
                   help="Indicates whether the base image trigger is enabled.",
                   arg_type=get_three_state_flag())
        c.argument(
            'base_image_trigger_type',
            help=
            "The type of the auto trigger for base image dependency updates.",
            arg_type=get_enum_type(BaseImageTriggerType))

        # Run related parameters
        c.argument('top',
                   help='Limit the number of latest runs in the results.')
        c.argument('run_id', help='The unique run identifier.')
        c.argument('run_status',
                   help='The current status of run.',
                   arg_type=get_enum_type(RunStatus))
        c.argument('no_archive',
                   help='Indicates whether the run should be archived.',
                   arg_type=get_three_state_flag())

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

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

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

    with self.argument_context('acr helm') as c:
        c.argument('resource_group_name', help=argparse.SUPPRESS)
        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')
Esempio n. 52
0
def load_arguments(self, _):

    with self.argument_context('connectedk8s connect') 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)
        c.argument('cluster_name', options_list=['--name', '-n'], help='The name of the connected cluster.')
        c.argument('kube_config', options_list=['--kube-config'], help='Path to the kube config file.')
        c.argument('kube_context', options_list=['--kube-context'], help='Kubconfig context from current machine.')
        c.argument('https_proxy', options_list=['--proxy-https'], arg_group='Proxy', help='Https proxy URL to be used.')
        c.argument('http_proxy', options_list=['--proxy-http'], arg_group='Proxy', help='Http proxy URL to be used.')
        c.argument('no_proxy', options_list=['--proxy-skip-range'], arg_group='Proxy', help='List of URLs/CIDRs for which proxy should not to be used.')
        c.argument('proxy_cert', options_list=['--proxy-cert'], arg_group='Proxy', type=file_type, completer=FilesCompleter(), help='Path to the certificate file for proxy')
        c.argument('distribution', options_list=['--distribution'], help='The Kubernetes distribution which will be running on this connected cluster.', arg_type=get_enum_type(Distribution_Enum_Values))
        c.argument('infrastructure', options_list=['--infrastructure'], help='The infrastructure on which the Kubernetes cluster represented by this connected cluster will be running on.', arg_type=get_enum_type(Infrastructure_Enum_Values))
        c.argument('disable_auto_upgrade', options_list=['--disable-auto-upgrade'], action='store_true', help='Flag to disable auto upgrade of arc agents.')
        c.argument('cl_oid', options_list=['--custom-locations-oid'], help="OID of 'custom-locations' app")
        c.argument('onboarding_timeout', options_list=['--onboarding-timeout'], arg_group='Timeout', help='Time required (in seconds) for the arc-agent pods to be installed on the kubernetes cluster. Override this value if the hardware/network constraints on your cluster requires more time for installing the arc-agent pods.')
        c.argument('no_wait', options_list=['--no-wait'], arg_group='Timeout', help="Do not wait for the long-running operation to finish.")

    with self.argument_context('connectedk8s update') as c:
        c.argument('cluster_name', options_list=['--name', '-n'], id_part='name', help='The name of the connected cluster.')
        c.argument('kube_config', options_list=['--kube-config'], help='Path to the kube config file.')
        c.argument('kube_context', options_list=['--kube-context'], help='Kubconfig context from current machine.')
        c.argument('https_proxy', options_list=['--proxy-https'], arg_group='Proxy', help='Https proxy URL to be used.')
        c.argument('http_proxy', options_list=['--proxy-http'], arg_group='Proxy', help='Http proxy URL to be used.')
        c.argument('no_proxy', options_list=['--proxy-skip-range'], arg_group='Proxy', help='List of URLs/CIDRs for which proxy should not to be used.')
        c.argument('proxy_cert', options_list=['--proxy-cert'], arg_group='Proxy', type=file_type, completer=FilesCompleter(), help='Path to the any additional certificate file (for proxy as well)')
        c.argument('disable_proxy', options_list=['--disable-proxy'], arg_group='Proxy', action='store_true', help='Disables proxy settings for agents')
        c.argument('auto_upgrade', options_list=['--auto-upgrade'], help='Flag to enable/disable auto upgrade of arc agents. By default, auto upgrade of agents is enabled.', arg_type=get_enum_type(["true", "false"]))

    with self.argument_context('connectedk8s upgrade') as c:
        c.argument('cluster_name', options_list=['--name', '-n'], id_part='name', help='The name of the connected cluster.')
        c.argument('kube_config', options_list=['--kube-config'], help='Path to the kube config file.')
        c.argument('kube_context', options_list=['--kube-context'], help='Kubconfig context from current machine.')
        c.argument('arc_agent_version', options_list=['--agent-version'], help='Version of agent to update the helm charts to.')
        c.argument('upgrade_timeout', options_list=['--upgrade-timeout'], help='Time required (in seconds) for the arc-agent pods to be upgraded on the kubernetes cluster. Override this value if the hardware/network constraints on your cluster requires more time for upgrading the arc-agent pods.')

    with self.argument_context('connectedk8s enable-features') as c:
        c.argument('cluster_name', options_list=['--name', '-n'], id_part='name', help='The name of the connected cluster.')
        c.argument('kube_config', options_list=['--kube-config'], help='Path to the kube config file.')
        c.argument('kube_context', options_list=['--kube-context'], help='Kubconfig context from current machine.')
        c.argument('features', features_types, options_list=['--features'], help='Space-separated list of features you want to enable.')
        c.argument('azrbac_client_id', options_list=['--app-id'], arg_group='Azure RBAC', help='Application ID for enabling Azure RBAC. Specify when enabling azure-rbac.')
        c.argument('azrbac_client_secret', options_list=['--app-secret'], arg_group='Azure RBAC', help='Application secret for enabling Azure RBAC. Specify when enabling azure-rbac.')
        c.argument('azrbac_skip_authz_check', options_list=['--skip-azure-rbac-list'], arg_group='Azure RBAC', help='Comma separated list of names of usernames/email/oid. Azure RBAC will be skipped for these users. Specify when enabling azure-rbac.')
        c.argument('cl_oid', options_list=['--custom-locations-oid'], help="OID of 'custom-locations' app")

    with self.argument_context('connectedk8s disable-features') as c:
        c.argument('cluster_name', options_list=['--name', '-n'], id_part='name', help='The name of the connected cluster.')
        c.argument('kube_config', options_list=['--kube-config'], help='Path to the kube config file.')
        c.argument('kube_context', options_list=['--kube-context'], help='Kubconfig context from current machine.')
        c.argument('features', features_types, options_list=['--features'], help='Space-separated list of features you want to disable.')
        c.argument('yes', options_list=['--yes', '-y'], help='Do not prompt for confirmation.', action='store_true')

    with self.argument_context('connectedk8s list') as c:
        pass

    with self.argument_context('connectedk8s show') as c:
        c.argument('cluster_name', options_list=['--name', '-n'], id_part='name', help='The name of the connected cluster.')

    with self.argument_context('connectedk8s delete') as c:
        c.argument('cluster_name', options_list=['--name', '-n'], id_part='name', help='The name of the connected cluster.')
        c.argument('kube_config', options_list=['--kube-config'], help='Path to the kube config file.')
        c.argument('kube_context', options_list=['--kube-context'], help='Kubconfig context from current machine.')

    with self.argument_context('connectedk8s proxy') as c:
        c.argument('cluster_name', options_list=['--name', '-n'], id_part='name', help='The name of the connected cluster.')
        c.argument('token', options_list=['--token'], help='Service account token to use to authenticate to the kubernetes cluster.')
        c.argument('context_name', options_list=['--kube-context'], help='If specified, overwrite the default context name.')
        c.argument('path', options_list=['--file', '-f'], type=file_type, completer=FilesCompleter(), default=os.path.join(os.path.expanduser('~'), '.kube', 'config'), help="Kubernetes configuration file to update. If not provided, updates the file '~/.kube/config'. Use '-' to print YAML to stdout instead.")
        c.argument('api_server_port', options_list=['--port'], help='Port used for accessing connected cluster.')
Esempio n. 53
0
from .advanced_filter import EventSubscriptionAddFilter

included_event_types_type = CLIArgumentType(
    help="A space-separated list of event types. Example: Microsoft.Storage.BlobCreated Microsoft.Storage.BlobDeleted. To subscribe to all default event types, do not specify any value for this argument.",
    nargs='+'
)

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

input_schema_type = CLIArgumentType(
    help="Schema in which incoming events will be published to this topic/domain. If you specify customeventschema as the value for this parameter, you must also provide values for at least one of --input_mapping_default_values / --input_mapping_fields.",
    arg_type=get_enum_type(['eventgridschema', 'customeventschema', 'cloudeventv01schema'], default='eventgridschema')
)

input_mapping_fields_type = CLIArgumentType(
    help="When input-schema is specified as customeventschema, this parameter is used to specify input mappings based on field names. Specify space separated mappings in 'key=value' format. Allowed key names are 'id', 'topic', 'eventtime', 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the names of the fields in the custom input schema. If a mapping for either 'id' or 'eventtime' is not provided, Event Grid will auto-generate a default value for these two fields.",
    arg_type=tags_type
)

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

odata_query_type = CLIArgumentType(
    help="The query used to filter the results using OData syntax.",
    options_list=['--odata-query']
Esempio n. 54
0
def load_arguments(self, _):
    with self.argument_context('container') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('name',
                   options_list=['--name', '-n'],
                   help="The name of the container group",
                   id_part='name')
        c.argument('location', arg_type=get_location_type(self.cli_ctx))

    with self.argument_context('container create') as c:
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument('image', help='The container image name')
        c.argument('cpu',
                   type=int,
                   help='The required number of CPU cores of the containers')
        c.argument('memory',
                   type=float,
                   help='The required memory of the containers in GB')
        c.argument('os_type',
                   arg_type=get_enum_type(OperatingSystemTypes),
                   help='The OS type of the containers')
        c.argument('ip_address',
                   arg_type=get_enum_type(IP_ADDRESS_TYPES),
                   help='The IP address type of the container group')
        c.argument('ports',
                   type=int,
                   nargs='+',
                   default=[80],
                   help='The ports to open')
        c.argument(
            'dns_name_label',
            help='The dns name label for container group with public IP')
        c.argument(
            'restart_policy',
            arg_type=get_enum_type(ContainerGroupRestartPolicy),
            help='Restart policy for all containers within the container group'
        )
        c.argument(
            'command_line',
            help=
            'The command line to run when the container is started, e.g. \'/bin/bash -c myscript.sh\''
        )
        c.argument(
            'environment_variables',
            nargs='+',
            options_list=['--environment-variables', '-e'],
            type=_environment_variables_type,
            help=
            'A list of environment variable for the container. Space-separated values in \'key=value\' format.'
        )
        c.argument('secrets', secrets_type)
        c.argument(
            'secrets_mount_path',
            validator=validate_volume_mount_path,
            help=
            'The path within the container where the secrets volume should be mounted. Must not contain colon (:).'
        )

    with self.argument_context('container create',
                               arg_group='Image Registry') as c:
        c.argument('registry_login_server',
                   help='The container image registry login server')
        c.argument(
            'registry_username',
            help='The username to log in container image registry server')
        c.argument(
            'registry_password',
            help='The password to log in container image registry server')

    with self.argument_context('container create',
                               arg_group='Azure File Volume') as c:
        c.argument(
            'azure_file_volume_share_name',
            help='The name of the Azure File share to be mounted as a volume')
        c.argument(
            'azure_file_volume_account_name',
            help=
            'The name of the storage account that contains the Azure File share'
        )
        c.argument(
            'azure_file_volume_account_key',
            help=
            'The storage account access key used to access the Azure File share'
        )
        c.argument(
            'azure_file_volume_mount_path',
            validator=validate_volume_mount_path,
            help=
            'The path within the container where the volume should be mounted. Must not contain colon (:).'
        )

    with self.argument_context('container logs') as c:
        c.argument(
            'container_name',
            help=
            'The container name to tail the logs. If omitted, the first container in the container group will be chosen'
        )
        c.argument('follow',
                   help='Indicate to stream the tailing logs',
                   action='store_true')

    with self.argument_context('container attach') as c:
        c.argument(
            'container_name',
            help=
            'The container to attach to. If omitted, the first container in the container group will be chosen'
        )
Esempio n. 55
0
def load_arguments(self, _):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        restore_point_arg_group = 'Restore Point'

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

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

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

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

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

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

        search_arg_group = 'Search'

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

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

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

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

        c.ignore('type')

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

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

        auth_group = 'Authentication'

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        policy_arg_group = 'Policy'

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

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

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

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

        policy_arg_group = 'Policy'
        notification_arg_group = 'Notification'

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

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

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

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

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

        # TODO: use server default

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

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

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

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

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

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

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

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

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

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

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

        c.argument('elastic_pool_name',
                   options_list=['--name', '-n'],
                   help='The name of the elastic pool.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

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

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

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

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

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

        search_arg_group = 'Search'

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

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

    #####
    #           sql elastic-pool op
    #####
    with self.argument_context('sql elastic-pool op') as c:
        c.argument('elastic_pool_name',
                   options_list=['--elastic-pool'],
                   help='Name of the Azure SQL Elastic Pool.')

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

    ###############################################
    #                sql server                   #
    ###############################################
    with self.argument_context('sql server') as c:
        c.argument('server_name', options_list=['--name', '-n'],
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')
        c.argument('administrator_login', options_list=['--admin-user', '-u'])
        c.argument('administrator_login_password', options_list=['--admin-password', '-p'])

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

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

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

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

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

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

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

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

    #####
    #           sql server dns-alias
    #####
    with self.argument_context('sql server dns-alias') as c:
        c.argument('server_name', arg_type=server_param_type)
        c.argument('dns_alias_name', options_list=('--name', '-n'))
        c.argument('original_server_name', options_list=('--original-server'),
                   help='The name of the server to which alias is currently pointing')
        c.argument('original_resource_group_name', options_list=('--original-resource-group'))
        c.argument('original_subscription_id', options_list=('--original-subscription-id'))

    #####
    #           sql server firewall-rule
    #####
    with self.argument_context('sql server firewall-rule') as c:
        # Help text needs to be specified because 'sql server firewall-rule update' is a custom
        # command.
        c.argument('server_name',
                   arg_type=server_param_type,
                   # Allow --ids command line argument. id_part=name is 1st name in uri
                   id_part='name')

        c.argument('firewall_rule_name',
                   options_list=['--name', '-n'],
                   help='The name of the firewall rule.',
                   # Allow --ids command line argument. id_part=child_name_1 is 2nd name in uri
                   id_part='child_name_1')

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

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

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

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

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

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

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

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

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

    with self.argument_context('sql server vnet-rule create') as c:
        c.extra('vnet_name', options_list=['--vnet-name'], help='The virtual network name')
Esempio n. 56
0
def load_arguments(self, _):
    from azext_attestation.vendored_sdks.azure_attestation.models._attestation_client_enums import TeeKind

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

    for item in ['create', 'show', 'update', 'delete']:
        with self.argument_context('attestation {}'.format(item)) as c:
            c.argument('provider_name',
                       provider_name_type,
                       help='Name of the attestation service instance.')

    for item in ['show', 'delete']:
        with self.argument_context('attestation {}'.format(item)) as c:
            c.extra(
                'identifier',
                options_list=['--id'],
                help=
                'Resource ID of the provider. Please omit --resource-group/-g or --name/-n '
                'if you have already specified --id.')

    for item in ['create', 'update']:
        with self.argument_context('attestation {}'.format(item)) as c:
            c.argument('tags', tags_type, nargs='+')

    with self.argument_context('attestation create') as c:
        c.argument(
            'certs_input_path',
            nargs='+',
            help=
            'Space-separated file paths to PEM/DER files containing certificates.'
        )

    with self.argument_context('attestation get-default-by-location') as c:
        c.argument('loc',
                   options_list=['--location', '-l'],
                   help='Location. (eg: "West US")')

    for item in ['list', 'add', 'remove']:
        with self.argument_context('attestation signer {}'.format(item)) as c:
            c.extra('resource_group_name',
                    resource_group_name_type,
                    required=False)
            c.extra('provider_name', provider_name_type, required=False)
            c.extra(
                'identifier',
                options_list=['--id'],
                help=
                'Resource ID of the provider. Please omit --resource-group/-g or --name/-n '
                'if you have already specified --id.')
            if item in ['add', 'remove']:
                c.ignore('tenant_base_url')
                c.argument(
                    'signer',
                    help=
                    'The policy certificate to {}. An RFC7519 JSON Web Token containing a claim named '
                    '"maa-policyCertificate" whose value is an RFC7517 JSON Web Key which specifies a '
                    'new key to update. The RFC7519 JWT must be signed with one of the existing signing '
                    'certificates'.format(item))
                c.argument(
                    'signer_file',
                    options_list=['--signer-file', '-f'],
                    help=
                    'File name of the signer. (--signer and --signer-file/-f are mutually exclusive.)'
                )

    for item in ['show', 'set', 'reset']:
        with self.argument_context('attestation policy {}'.format(item)) as c:
            c.argument('attestation_type',
                       arg_type=get_enum_type(TeeKind),
                       help='Type of the attestation.')
            c.argument('provider_name', provider_name_type, required=False)
            c.extra(
                'identifier',
                options_list=['--id'],
                help=
                'Resource ID of the provider. Please omit --resource-group/-g or --name/-n '
                'if you have already specified --id.')

            if item in ['set']:
                c.argument(
                    'policy_format',
                    arg_type=get_enum_type(['Text', 'JWT']),
                    default='Text',
                    help=
                    'Specifies the format for the policy, either Text or JWT (JSON Web Token).'
                )
                c.argument(
                    'new_attestation_policy',
                    help='Content of the new attestation policy (Text or JWT).'
                )
                c.argument(
                    'new_attestation_policy_file',
                    options_list=['--new-attestation-policy-file', '-f'],
                    help='File name of the new attestation policy.')
Esempio n. 57
0
def load_arguments(self, _):

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

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

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

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

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

    with self.argument_context('acs kubernetes get-credentials') as c:
        c.argument('path', options_list=['--file', '-f'])

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

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

    with self.argument_context('aks create') as c:
        c.argument('name', validator=validate_linux_host_name)
        c.argument('kubernetes_version', completer=get_k8s_versions_completion_list)
        c.argument('admin_username', options_list=['--admin-username', '-u'], default='azureuser')
        c.argument('dns_name_prefix', options_list=['--dns-name-prefix', '-p'])
        c.argument('generate_ssh_keys', action='store_true', validator=validate_create_parameters)
        c.argument('node_vm_size', options_list=['--node-vm-size', '-s'], completer=get_vm_size_completion_list)
        c.argument('ssh_key_value', required=False, type=file_type, default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(), validator=validate_ssh_key)

    with self.argument_context('aks get-credentials') as c:
        c.argument('admin', options_list=['--admin', '-a'], default=False)
        c.argument('path', options_list=['--file', '-f'], type=file_type, completer=FilesCompleter(),
                   default=os.path.join(os.path.expanduser('~'), '.kube', 'config'))

    with self.argument_context('aks install-cli') as c:
        c.argument('client_version', validator=validate_k8s_client_version)
        c.argument('install_location', default=_get_default_install_location('kubectl'))

    with self.argument_context('aks install-connector') as c:
        c.argument('aci_resource_group', help='The resource group to create the ACI container groups')
        c.argument('chart_url', default=aci_connector_chart_url, help='URL to the chart')
        c.argument('client_secret', help='Client secret to use with the service principal for making calls to Azure APIs')
        c.argument('connector_name', help='The name for the ACI Connector', validator=validate_connector_name)
        c.argument('image_tag', help='The image tag of the virtual kubelet')
        c.argument('location', help='The location to create the ACI container groups')
        c.argument('os_type', get_enum_type(aci_connector_os_type), help='The OS type of the connector')
        c.argument('service_principal',
                   help='Service principal for making calls into Azure APIs. If not set, auto generate a new service principal of Contributor role, and save it locally for reusing')

    with self.argument_context('aks remove-connector') as c:
        c.argument('connector_name', help='The name for the ACI Connector', validator=validate_connector_name)
        c.argument('graceful', action='store_true',
                   help='Mention if you want to drain/uncordon your aci-connector to move your applications')
        c.argument('os_type', get_enum_type(aci_connector_os_type), help='The OS type of the connector')

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

    with self.argument_context('aks upgrade-connector') as c:
        c.argument('aci_resource_group')
        c.argument('chart_url', default=aci_connector_chart_url)
        c.argument('client_secret')
        c.argument('connector_name', validator=validate_connector_name)
        c.argument('image_tag')
        c.argument('location')
        c.argument('os_type', get_enum_type(aci_connector_os_type))
        c.argument('service_principal')
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('yes', options_list=['--yes', '-y'], help='Do not prompt for confirmation.', action='store_true')

    with self.argument_context('aks update') as c:
        c.argument('enable_cluster_autoscaler', options_list=["--enable-cluster-autoscaler", "-e"], action='store_true')
        c.argument('disable_cluster_autoscaler', options_list=["--disable-cluster-autoscaler", "-d"], action='store_true')
        c.argument('update_cluster_autoscaler', options_list=["--update-cluster-autoscaler", "-u"], action='store_true')
        c.argument('cluster_autoscaler_profile', nargs='+', validator=validate_cluster_autoscaler_profile)
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('uptime_sla', action='store_true')
        c.argument('no_uptime_sla', action='store_true')
        c.argument('load_balancer_managed_outbound_ip_count', type=int)
        c.argument('load_balancer_outbound_ips', type=str, validator=validate_load_balancer_outbound_ips)
        c.argument('load_balancer_outbound_ip_prefixes', type=str, validator=validate_load_balancer_outbound_ip_prefixes)
        c.argument('load_balancer_outbound_ports', type=int, validator=validate_load_balancer_outbound_ports)
        c.argument('load_balancer_idle_timeout', type=int, validator=validate_load_balancer_idle_timeout)
        c.argument('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')

    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 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)
Esempio n. 59
0
def load_arguments(self, _):

    from azure.cli.core.commands.parameters import tags_type
    from azure.cli.core.commands.validators import get_default_location_from_resource_group

    with self.argument_context('apim') as c:
        c.argument('resource_group_name', arg_type=resource_group_name_type)
        c.argument('tags', tags_type)
        c.argument('service_name',
                   options_list=['--name', '-n'],
                   help="The name of the api management service instance",
                   id_part=None)
        c.argument('name',
                   options_list=['--name', '-n'],
                   help="The name of the api management service instance",
                   id_part=None)
        c.argument('location',
                   validator=get_default_location_from_resource_group)

    with self.argument_context('apim create') as c:
        c.argument('location',
                   arg_type=get_location_type(self.cli_ctx),
                   validator=get_default_location_from_resource_group)
        c.argument(
            'publisher_name',
            help=
            'The name of your organization for use in the developer portal and e-mail notifications.',
            required=True)
        c.argument(
            'publisher_email',
            help='The e-mail address to receive all system notifications.')
        c.argument(
            'enable_client_certificate',
            arg_type=get_three_state_flag(),
            help=
            'Enforces a client certificate to be presented on each request to the gateway and also enables the ability to authenticate the certificate in the policy on the gateway.'
        )
        c.argument('virtual_network_type',
                   get_enum_type(VNET_TYPES),
                   options_list=['--virtual-network', '-v'],
                   help='The virtual network type.')
        c.argument('sku_name',
                   arg_type=get_enum_type(SKU_TYPES),
                   help='The sku of the api management instance')
        c.argument('sku_capacity',
                   type=int,
                   help='The number of deployed units of the SKU.')
        c.argument(
            'enable_managed_identity',
            arg_type=get_three_state_flag(),
            help=
            'Create a managed identity for the API Management service to access other Azure resources.'
        )

    with self.argument_context('apim update') as c:
        c.argument(
            'publisher_name',
            help=
            'The name of your organization for use in the developer portal and e-mail notifications.'
        )
        c.argument(
            'publisher_email',
            help='The e-mail address to receive all system notifications.')
        c.argument(
            'enable_client_certificate',
            arg_type=get_three_state_flag(),
            help=
            'Enforces a client certificate to be presented on each request to the gateway and also enables the ability to authenticate the certificate in the policy on the gateway.'
        )
        c.argument('virtual_network_type',
                   get_enum_type(VNET_TYPES),
                   options_list=['--virtual-network', '-v'],
                   help='The virtual network type.')
        c.argument('sku_name',
                   arg_type=get_enum_type(SKU_TYPES),
                   help='The sku of the api management instance')
        c.argument('sku_capacity',
                   type=int,
                   help='The number of deployed units of the SKU.')
        c.argument(
            'enable_managed_identity',
            arg_type=get_three_state_flag(),
            help=
            'Create a managed identity for the API Management service to access other Azure resources.'
        )

    with self.argument_context('apim backup') as c:
        c.argument('backup_name',
                   help='The name of the backup file to create.')
        c.argument(
            'storage_account_name',
            arg_group='Storage',
            help='The name of the storage account used to place the backup.')
        c.argument(
            'storage_account_key',
            arg_group='Storage',
            help=
            'The access key of the storage account used to place the backup.')
        c.argument(
            'storage_account_container',
            arg_group='Storage',
            help=
            'The name of the storage account container used to place the backup.'
        )

    with self.argument_context('apim api show') as c:
        c.argument('service_name',
                   options_list=['--service-name'],
                   help='The name of the API Management service instance.')
        c.argument(
            'api_id',
            help=
            'API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.'
        )

    with self.argument_context('apim api create') as c:
        c.argument('service_name',
                   options_list=['--service-name'],
                   help='The name of the API Management service instance.')
        c.argument(
            'api_id',
            help=
            'API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.',
            required=True)
        c.argument(
            'path',
            help=
            'Required. Relative URL uniquely identifying this API and all of its resource paths within the API Management service instance.',
            required=True)
        c.argument('display_name',
                   help='API name. Must be 1 to 300 characters long.',
                   required=True)
        c.argument(
            'description',
            help='Description of the API. May include HTML formatting tags.')
        c.argument('subscription_key_parameter_names',
                   help='Protocols over which API is made available.')
        c.argument(
            'api_revision',
            help=
            'Describes the Revision of the Api. If no value is provided, default revision 1 is created.'
        )
        c.argument(
            'api_version',
            help=
            'Indicates the Version identifier of the API if the API is versioned.'
        )
        c.argument('is_current',
                   help='Indicates if API revision is current api revision.')
        c.argument(
            'service_url',
            help=
            'Absolute URL of the backend service implementing this API. Cannot be more than 2000 characters long.'
        )
        c.argument(
            'protocols',
            arg_type=get_enum_type(API_PROTOCOLS),
            help=
            'Describes on which protocols the operations in this API can be invoked.'
        )
        c.argument('api_type',
                   arg_type=get_enum_type(API_TYPES),
                   help='The type of the API.')
        c.argument(
            'subscription_required',
            arg_type=get_three_state_flag(),
            help='If true, the API requires a subscription key on requests.')
        c.argument('tags', tags_type)

    with self.argument_context('apim api delete') as c:
        c.argument('service_name',
                   options_list=['--service-name'],
                   help='The name of the API Management service instance.')
        c.argument(
            'api_id',
            help=
            'API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.'
        )
        c.argument('delete_revisions', help='Delete all revisions of the Api.')

    with self.argument_context('apim api update') as c:
        c.argument('service_name',
                   options_list=['--service-name'],
                   help='The name of the API Management service instance.')
        c.argument(
            'api_id',
            help=
            'API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.',
            required=True)
        c.argument('display_name',
                   help='API name. Must be 1 to 300 characters long.')
        c.argument(
            'path',
            help=
            'Required. Relative URL uniquely identifying this API and all of its resource paths within the API Management service instance.'
        )
        c.argument(
            'description',
            help='Description of the API. May include HTML formatting tags.')
        c.argument('subscription_key_parameter_names',
                   help='Protocols over which API is made available.')
        c.argument(
            'api_revision',
            help=
            'Describes the Revision of the Api. If no value is provided, default revision 1 is created.'
        )
        c.argument(
            'api_version',
            help=
            'Indicates the Version identifier of the API if the API is versioned.'
        )
        c.argument('is_current',
                   arg_type=get_three_state_flag(),
                   help='Indicates if API revision is current api revision.')
        c.argument(
            'service_url',
            help=
            'Absolute URL of the backend service implementing this API. Cannot be more than 2000 characters long.'
        )
        c.argument(
            'protocols',
            arg_type=get_enum_type(API_PROTOCOLS),
            help=
            'Describes on which protocols the operations in this API can be invoked.'
        )
        c.argument('api_type',
                   arg_type=get_enum_type(API_TYPES),
                   help='The type of the API.')
        c.argument(
            'subscription_required',
            arg_type=get_three_state_flag(),
            help='If true, the API requires a subscription key on requests.')
        c.argument('tags', tags_type)
Esempio n. 60
0
def load_arguments(self, _):  # pylint: disable=too-many-statements
    # PARAMETER REGISTRATION
    application_parameters = CLIArgumentType(
        options_list=['--parameters', '--application-parameters'],
        action=addAppParamsAction,
        nargs='+',
        help=
        'Specify the application parameters as key/value pairs. These parameters must exist in the application manifest. '
        'for example: --application-parameters param1=value1 param2=value2')

    minimum_nodes = CLIArgumentType(
        options_list=['--min-nodes', '--minimum-nodes'],
        help=
        'Specify the minimum number of nodes where Service Fabric will reserve capacity for this application, '
        'this does not mean that the application is guaranteed to have replicas on all those nodes. The value of this parameter must be a non-negative integer. '
        'Default value for this is zero, which means no capacity is reserved for the application.'
    )

    maximum_nodes = CLIArgumentType(
        options_list=['--max-nodes', '--maximum-nodes'],
        help=
        'Specify the maximum number of nodes on which to place an application. '
        'The value of this parameter must be a non-negative integer. The default value is 0, which indicates the application can be placed on any number of nodes in the cluster.'
    )

    application_type_version = CLIArgumentType(
        options_list=['--version', '--application-type-version'],
        help='Specify the application type version.')

    package_url = CLIArgumentType(
        help='Specify the url of the application package sfpkg file.')

    with self.argument_context('sf') as c:
        c.argument(
            'resource_group_name',
            arg_type=resource_group_name_type,
            id_part=None,
            help=
            'Specify the resource group name. You can configure the default group using `az configure --defaults group=<name>`'
        )
        c.argument(
            'cluster_name',
            options_list=['--cluster-name', '-c'],
            help=
            'Specify the name of the cluster, if not given it will be same as resource group name'
        )
        c.argument('location',
                   validator=get_default_location_from_resource_group)
        c.argument('secret_identifier',
                   help='The existing Azure key vault secret URL')
        c.argument(
            'certificate_file',
            help=
            'The existing certificate file path for the primary cluster certificate.'
        )
        c.argument('parameter_file',
                   help='The path to the template parameter file.')
        c.argument('template_file', help='The path to the template file.')
        c.argument('vm_password', help='The password of the Vm')
        c.argument(
            'certificate_output_folder',
            help='The folder of the new certificate file to be created.')
        c.argument('certificate_password',
                   help='The password of the certificate file.')
        c.argument('certificate_subject_name',
                   help='The subject name of the certificate to be created.')
        c.argument(
            'vault_resource_group_name',
            options_list=['--vault-resource-group'],
            help=
            'Key vault resource group name, if not given it will be cluster resource group name'
        )
        c.argument(
            'vault_name',
            help=
            'Azure key vault name, it not given it will be the cluster resource group name'
        )
        c.argument(
            'cluster_size',
            options_list=['--cluster-size', '-s'],
            help='The number of nodes in the cluster. Default are 5 nodes')
        c.argument('vm_sku', help='VM Sku')
        c.argument(
            'vm_user_name',
            help='The user name for logging to Vm. Default will be adminuser')
        c.argument(
            'vm_os',
            arg_type=get_enum_type([
                'WindowsServer2012R2Datacenter', 'WindowsServer2016Datacenter',
                'WindowsServer2016DatacenterwithContainers',
                'UbuntuServer1604', 'WindowsServer1709',
                'WindowsServer1709withContainers',
                'WindowsServer1803withContainers',
                'WindowsServer1809withContainers',
                'WindowsServer2019Datacenter',
                'WindowsServer2019DatacenterwithContainers'
            ]),
            default='WindowsServer2016Datacenter',
            options_list=['--vm-os', '--os'],
            help='The Operating System of the VMs that make up the cluster.')
        c.argument('node_type', help='the Node type name.')

    # cluster
    with self.argument_context('sf cluster list') as c:
        c.argument('resource_group_name',
                   arg_type=resource_group_name_type,
                   id_part=None,
                   help='The resource group name')

    with self.argument_context('sf client certificate') as c:
        c.argument('certificate_common_name',
                   help='client certificate common name.')
        c.argument(
            'admin_client_thumbprints',
            nargs='+',
            help=
            'Space-separated list of client certificate thumbprint that only has admin permission, '
        )
        c.argument('certificate_issuer_thumbprint',
                   help='client certificate issuer thumbprint.')

    with self.argument_context('sf cluster certificate') as c:
        c.argument('thumbprint',
                   help='The cluster certificate thumbprint to be removed')

    with self.argument_context('sf cluster client-certificate') as c:
        c.argument('is_admin', help='Client authentication type.')
        c.argument('certificate_issuer_thumbprint',
                   help='client certificate issuer thumbprint.')
        c.argument('certificate_common_name',
                   help='client certificate common name.')
        c.argument(
            'admin_client_thumbprints',
            nargs='+',
            help='client certificate thumbprint that only has admin permission.'
        )
        c.argument(
            'readonly_client_thumbprints',
            nargs='+',
            help=
            'Space-separated list of client certificate thumbprint that has read only permission.'
        )

    with self.argument_context('sf cluster client-certificate add') as c:
        c.argument('thumbprint', help='client certificate thumbprint.')

    with self.argument_context('sf cluster client-certificate remove') as c:
        c.argument(
            'thumbprints',
            nargs='+',
            help=
            'A single or Space-separated list of client certificate thumbprint(s) to be remove.'
        )

    with self.argument_context('sf cluster node') as c:
        c.argument('number_of_nodes_to_add', help='number of nodes to add.')
        c.argument('number_of_nodes_to_remove',
                   help='number of nodes to remove.')

    with self.argument_context('sf cluster node-type') as c:
        c.argument(
            'capacity',
            help=
            'The capacity tag applied to nodes in the node type. The cluster resource manager uses these tags to understand how much capacity a node has.'
        )
        c.argument('vm_tier', help='VM tier.')

    with self.argument_context('sf cluster') as c:
        c.argument('durability_level',
                   arg_type=get_enum_type(['Bronze', 'Silver', 'Gold']),
                   help='durability level.')

    with self.argument_context('sf cluster setting') as c:
        c.argument('parameter', help='parameter name')
        c.argument('section', help='section name')
        c.argument('value', help='Specify the value')
        c.argument('settings_section_description', help='Specify the value')

    with self.argument_context('sf cluster upgrade-type set') as c:
        c.argument('version', help='cluster code version')
        c.argument('upgrade_mode',
                   arg_type=get_enum_type(['manual', 'automatic']),
                   help='cluster upgrade mode')

    with self.argument_context('sf cluster reliability') as c:
        c.argument('reliability_level',
                   arg_type=get_enum_type(
                       ['Bronze', 'Silver', 'Gold', 'Platinum']),
                   help='durability level.')
        c.argument(
            'auto_add_node',
            help='Add node count automatically when changing reliability.')

    with self.argument_context('sf cluster setting set') as c:
        c.argument(
            'settings_section_description',
            type=get_json_object,
            help=
            'JSON encoded parameters configuration. Use @{file} to load from a file. '
            'For example: [{"section": "NamingService","parameter": "MaxOperationTimeout","value": 1000},{"section": "MaxFileOperationTimeout","parameter": "Max2","value": 1000]'
        )

    with self.argument_context('sf cluster setting remove') as c:
        c.argument(
            'settings_section_description',
            type=get_json_object,
            help=
            'JSON encoded parameters configuration. Use @{file} to load from a file. '
            'For example: [{"section": "NamingService","parameter": "MaxOperationTimeout"}]'
        )

    with self.argument_context('sf cluster client-certificate remove') as c:
        c.argument(
            'client_certificate_common_names',
            type=get_json_object,
            help=
            'JSON encoded parameters configuration. Use @{file} to load from a file. '
            'For example: [{"certificateCommonName": "test.com","certificateIssuerThumbprint": "22B4AE296B504E512DF880A77A2CAE20200FF922"}]'
        )

    with self.argument_context('sf cluster client-certificate add') as c:
        c.argument(
            'client_certificate_common_names',
            type=get_json_object,
            help=
            'JSON encoded parameters configuration. Use @{file} to load from a file. '
            'For example: [{"isAdmin":true, "certificateCommonName": "test.com", '
            '"certificateIssuerThumbprint": "22B4AE296B504E512DF880A77A2CAE20200FF922"}]'
        )

    # application-type
    with self.argument_context('sf application-type') as c:
        c.argument('application_type_name',
                   options_list=['--name', '--application-type-name'],
                   help='Specify the application type name.')

    # application-type version
    with self.argument_context('sf application-type version') as c:
        c.argument('version', arg_type=application_type_version)
        c.argument('package_url', arg_type=package_url)

    # application
    with self.argument_context('sf application') as c:
        c.argument('application_name',
                   options_list=['--name', '--application-name'],
                   help='Specify the application name.')

    with self.argument_context('sf application update',
                               validator=validate_update_application) as c:
        c.argument('application_type_version',
                   arg_type=application_type_version)
        c.argument('application_parameters', arg_type=application_parameters)
        c.argument('minimum_nodes', arg_type=minimum_nodes)
        c.argument('maximum_nodes', arg_type=maximum_nodes)
        c.argument(
            'force_restart',
            arg_type=get_three_state_flag(),
            help=
            'Indicates that the service host restarts even if the upgrade is a configuration-only change.'
        )
        c.argument(
            'service_type_health_policy_map',
            help=
            'Specify the map of the health policy to use for different service types as a hash table in the following format: {\"ServiceTypeName\" : \"MaxPercentUnhealthyPartitionsPerService,MaxPercentUnhealthyReplicasPerPartition,MaxPercentUnhealthyServices\"}. For example: @{ \"ServiceTypeName01\" = \"5,10,5\"; \"ServiceTypeName02\" = \"5,5,5\" }'
        )

    with self.argument_context('sf application update',
                               arg_group='Upgrade description') as c:
        c.argument(
            'upgrade_replica_set_check_timeout',
            help=
            'Specify the maximum time, in seconds, that Service Fabric waits for a service to reconfigure into a safe state, if not already in a safe state, before Service Fabric proceeds with the upgrade.'
        )
        c.argument(
            'failure_action',
            arg_type=get_enum_type(['Rollback', 'Manual']),
            help=
            'Specify the action to take if the monitored upgrade fails. The acceptable values for this parameter are Rollback or Manual.'
        )
        c.argument(
            'health_check_retry_timeout',
            options_list=[
                '--hc-retry-timeout', '--health-check-retry-timeout'
            ],
            help=
            'Specify the duration, in seconds, after which Service Fabric retries the health check if the previous health check fails.'
        )
        c.argument(
            'health_check_wait_duration',
            options_list=[
                '--hc-wait-duration', '--health-check-wait-duration'
            ],
            help=
            'Specify the duration, in seconds, that Service Fabric waits before it performs the initial health check after it finishes the upgrade on the upgrade domain.'
        )
        c.argument(
            'health_check_stable_duration',
            options_list=[
                '--hc-stable-duration', '--health-check-stable-duration'
            ],
            help=
            'Specify the duration, in seconds, that Service Fabric waits in order to verify that the application is stable before moving to the next upgrade domain or completing the upgrade. This wait duration prevents undetected changes of health right after the health check is performed.'
        )
        c.argument(
            'upgrade_domain_timeout',
            options_list=['--ud_timeout', '--upgrade-domain-timeout'],
            help=
            'Specify the maximum time, in seconds, that Service Fabric takes to upgrade a single upgrade domain. After this period, the upgrade fails.'
        )
        c.argument(
            'upgrade_timeout',
            help=
            'Specify the maximum time, in seconds, that Service Fabric takes for the entire upgrade. After this period, the upgrade fails.'
        )
        c.argument(
            'consider_warning_as_error',
            options_list=['--warning-as-error', '--consider-warning-as-error'],
            arg_type=get_three_state_flag(),
            help=
            'Indicates whether to treat a warning health event as an error event during health evaluation.'
        )
        c.argument(
            'default_service_type_max_percent_unhealthy_partitions_per_service',
            options_list=['--max-porcent-unhealthy-partitions'],
            help=
            'Specify the maximum percent of unhelthy partitions per service allowed by the health policy for the default service type to use for the monitored upgrade. Allowed values are form 0 to 100.'
        )
        c.argument(
            'default_service_type_max_percent_unhealthy_replicas_per_partition',
            options_list=['--max-porcent-unhealthy-replicas'],
            help=
            'Specify the maximum percent of unhelthy replicas per service allowed by the health policy for the default service type to use for the monitored upgrade. Allowed values are form 0 to 100.'
        )
        c.argument(
            'default_service_type_max_percent_unhealthy_services',
            options_list=['--max-porcent-unhealthy-services'],
            help=
            'Specify the maximum percent of unhelthy services allowed by the health policy for the default service type to use for the monitored upgrade. Allowed values are form 0 to 100.'
        )
        c.argument(
            'max_percent_unhealthy_deployed_applications',
            options_list=['--max-porcent-unhealthy-apps'],
            help=
            'Specify the mximum percentage of the application instances deployed on the nodes in the cluster that have a health state of error before the application health state for the cluster is error. Allowed values are form 0 to 100.'
        )

    with self.argument_context('sf application create',
                               validator=validate_create_application) as c:
        c.argument('application_type_name',
                   options_list=['--type-name', '--application-type-name'],
                   help='Specify the application type name.')
        c.argument('application_type_version',
                   arg_type=application_type_version)
        c.argument('package_url', arg_type=package_url)
        c.argument('application_parameters', arg_type=application_parameters)
        c.argument('minimum_nodes', arg_type=minimum_nodes)
        c.argument('maximum_nodes', arg_type=maximum_nodes)

    # service
    with self.argument_context('sf service') as c:
        c.argument(
            'service_name',
            options_list=['--name', '--service-name'],
            help=
            'Specify the name of the service. The application name must be a prefix of the service name, for example: appName~serviceName'
        )

    with self.argument_context('sf service create',
                               validator=validate_create_service) as c:
        c.argument(
            'service_type',
            help=
            'Specify the service type name of the application, it should exist in the application manifest.'
        )
        c.argument(
            'application_name',
            options_list=['--application', '--application-name'],
            help=
            'Specify the name of the service. The application name must be a prefix of the service name, for example: appName~serviceName'
        )
        c.argument('state',
                   arg_type=get_enum_type(['stateless', 'stateful']),
                   help='Specify if the service is stateless or stateful.')
        c.argument(
            'instance_count',
            help=
            'Specify the instance count for the stateless service. If -1 is used, it means it will run on all the nodes.'
        )
        c.argument(
            'min_replica_set_size',
            help='Specify the min replica set size for the stateful service.')
        c.argument(
            'target_replica_set_size',
            help='Specify the target replica set size for the stateful service.'
        )
        c.argument(
            'default_move_cost',
            arg_type=get_enum_type(['Zero', 'Low', 'Medium', 'High']),
            help=
            'Specify the default cost for a move. Higher costs make it less likely that the Cluster Resource Manager will move the replica when trying to balance the cluster.'
        )
        c.argument(
            'partition_scheme',
            arg_type=get_enum_type(['singleton', 'uniformInt64', 'named']),
            help='Specify what partition scheme to use. '
            'Singleton partitions are typically used when the service does not require any additional routing. '
            'UniformInt64 means that each partition owns a range of int64 keys. '
            'Named is usually for services with data that can be bucketed, within a bounded set. Some common examples of data fields used as named partition keys would be regions, postal codes, customer groups, or other business boundaries.'
        )