Beispiel #1
0
register_cli_argument('webapp log config',
                      'web_server_logging',
                      help='configure Web server logging',
                      **enum_choice_list(server_log_switch_options))

register_cli_argument(
    'webapp log tail',
    'provider',
    help=
    "scope the live traces to certain providers/folders, for example:'application', 'http' for server log, 'kudu/trace', etc"
)
register_cli_argument('webapp log download',
                      'log_file',
                      default='webapp_logs.zip',
                      type=file_type,
                      completer=FilesCompleter(),
                      help='the downloaded zipped log file path')

for scope in ['appsettings', 'connection-string']:
    register_cli_argument(
        'webapp config ' + scope,
        'settings',
        nargs='+',
        help="space separated {} in a format of <name>=<value>".format(scope))
    register_cli_argument(
        'webapp config ' + scope,
        'slot_settings',
        nargs='+',
        help="space separated slot {} in a format of <name>=<value>".format(
            scope))
    register_cli_argument('webapp config ' + scope,
Beispiel #2
0
from __future__ import absolute_import, unicode_literals

# Optional argcomplete library for CLI (BASH-based) tab completion
try:
    from argcomplete import autocomplete
    from argcomplete.completers import FilesCompleter, DirectoriesCompleter
except ImportError:

    def _argcomplete_noop(*args, **kwargs):
        del args, kwargs

    autocomplete = _argcomplete_noop
    # noinspection PyPep8Naming
    FilesCompleter = DirectoriesCompleter = _argcomplete_noop

# Someday add *.meta (once more testing is done with those files
conf_files_completer = FilesCompleter(allowednames=["*.conf"])
Beispiel #3
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, up to 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('outbound_type',
                   arg_type=get_enum_type([
                       CONST_OUTBOUND_TYPE_LOAD_BALANCER,
                       CONST_OUTBOUND_TYPE_USER_DEFINED_ROUTING
                   ]))
        c.argument('enable_cluster_autoscaler', action='store_true')
        c.argument(
            'cluster_autoscaler_profile',
            nargs='+',
            options_list=["--cluster-autoscaler-profile", "--ca-profile"],
            validator=validate_cluster_autoscaler_profile,
            help=
            "Space-separated list of key=value pairs for configuring cluster autoscaler. Pass an empty string to clear the profile."
        )
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('vm_set_type', type=str, validator=validate_vm_set_type)
        c.argument(
            'zones',
            zones_type,
            options_list=['--zones', '-z'],
            help=
            'Space-separated list of availability zones where agent nodes will be placed.'
        )
        c.argument('uptime_sla', action='store_true')
        c.argument('enable_addons', options_list=['--enable-addons', '-a'])
        c.argument('disable_rbac', action='store_true')
        c.argument('enable_rbac',
                   action='store_true',
                   options_list=['--enable-rbac', '-r'],
                   deprecate_info=c.deprecate(redirect="--disable-rbac",
                                              hide="2.0.45"))
        c.argument('max_pods', type=int, options_list=['--max-pods', '-m'])
        c.argument('network_plugin',
                   arg_type=get_enum_type(['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('ppg', type=str, validator=validate_ppg)
        c.argument('vnet_subnet_id',
                   type=str,
                   validator=validate_vnet_subnet_id)
        c.argument('workspace_resource_id')
        c.argument('skip_subnet_role_assignment', action='store_true')
        c.argument('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)
        c.argument('attach_acr', acr_arg_type)
        c.argument('enable_private_cluster', action='store_true')
        c.argument(
            'nodepool_tags',
            nargs='*',
            validator=validate_nodepool_tags,
            help=
            'space-separated tags: key[=value] [key[=value] ...]. Use "" to clear existing tags.'
        )
        c.argument('enable_managed_identity', action='store_true')
        c.argument('assign_identity',
                   type=str,
                   validator=validate_assign_identity)
        c.argument(
            'nodepool_labels',
            nargs='*',
            validator=validate_nodepool_labels,
            help=
            'space-separated labels: key[=value] [key[=value] ...]. You can not change the node labels through CLI after creation. See https://aka.ms/node-labels for syntax of labels.'
        )
        c.argument('enable_node_public_ip',
                   action='store_true',
                   is_preview=True)
        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('node_osdisk_diskencryptionset_id',
                   type=str,
                   options_list=['--node-osdisk-diskencryptionset-id', '-d'])
        c.argument('aci_subnet_name')
        c.argument('appgw_name',
                   options_list=['--appgw-name'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_cidr',
                   options_list=['--appgw-subnet-cidr'],
                   arg_group='Application Gateway')
        c.argument('appgw_id',
                   options_list=['--appgw-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_id',
                   options_list=['--appgw-subnet-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_watch_namespace',
                   options_list=['--appgw-watch-namespace'],
                   arg_group='Application Gateway')
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.',
                   action='store_true')
        c.argument('enable_sgxquotehelper', action='store_true')

    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(
            'cluster_autoscaler_profile',
            nargs='+',
            options_list=["--cluster-autoscaler-profile", "--ca-profile"],
            validator=validate_cluster_autoscaler_profile,
            help=
            "Space-separated list of key=value pairs for configuring cluster autoscaler. Pass an empty string to clear the profile."
        )
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('uptime_sla', action='store_true')
        c.argument('load_balancer_managed_outbound_ip_count', type=int)
        c.argument('load_balancer_outbound_ips',
                   type=str,
                   validator=validate_load_balancer_outbound_ips)
        c.argument('load_balancer_outbound_ip_prefixes',
                   type=str,
                   validator=validate_load_balancer_outbound_ip_prefixes)
        c.argument('load_balancer_outbound_ports',
                   type=int,
                   validator=validate_load_balancer_outbound_ports)
        c.argument('load_balancer_idle_timeout',
                   type=int,
                   validator=validate_load_balancer_idle_timeout)
        c.argument('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)
        c.argument('enable_ahub', options_list=['--enable-ahub'])
        c.argument('disable_ahub', options_list=['--disable-ahub'])

    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.')
        c.argument('appgw_name',
                   options_list=['--appgw-name'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_cidr',
                   options_list=['--appgw-subnet-cidr'],
                   arg_group='Application Gateway')
        c.argument('appgw_id',
                   options_list=['--appgw-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_id',
                   options_list=['--appgw-subnet-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_watch_namespace',
                   options_list=['--appgw-watch-namespace'],
                   arg_group='Application Gateway')
        c.argument('enable_sgxquotehelper', action='store_true')

    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_kubectl_version,
                       help='Version of kubectl to install.')
            c.argument('install_location',
                       default=_get_default_install_location('kubectl'),
                       help='Path at which to install kubectl.')
            c.argument('base_src_url',
                       help='Base download source URL for kubectl releases.')
            c.argument('kubelogin_version',
                       validator=validate_kubelogin_version,
                       help='Version of kubelogin to install.')
            c.argument('kubelogin_install_location',
                       default=_get_default_install_location('kubelogin'),
                       help='Path at which to install kubelogin.')
            c.argument('kubelogin_base_src_url',
                       options_list=['--kubelogin-base-src-url', '-l'],
                       help='Base download source URL for kubelogin releases.')

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

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

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

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

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

    for scope in ['aks nodepool add']:
        with self.argument_context(scope) as c:
            c.argument('nodepool_name',
                       type=str,
                       options_list=['--name', '-n'],
                       validator=validate_nodepool_name,
                       help='The node pool name.')
            c.argument(
                'zones',
                zones_type,
                options_list=['--zones', '-z'],
                help=
                'Space-separated list of availability zones where agent nodes will be placed.'
            )
            c.argument('node_vm_size',
                       options_list=['--node-vm-size', '-s'],
                       completer=get_vm_size_completion_list)
            c.argument('max_pods', type=int, options_list=['--max-pods', '-m'])
            c.argument('os_type', type=str)
            c.argument('enable_cluster_autoscaler',
                       options_list=["--enable-cluster-autoscaler", "-e"],
                       action='store_true')
            c.argument('node_taints', type=str, validator=validate_taints)
            c.argument('priority',
                       arg_type=get_enum_type([
                           CONST_SCALE_SET_PRIORITY_REGULAR,
                           CONST_SCALE_SET_PRIORITY_SPOT
                       ]),
                       validator=validate_priority)
            c.argument('eviction_policy',
                       arg_type=get_enum_type([
                           CONST_SPOT_EVICTION_POLICY_DELETE,
                           CONST_SPOT_EVICTION_POLICY_DEALLOCATE
                       ]),
                       validator=validate_eviction_policy)
            c.argument('spot_max_price',
                       type=float,
                       validator=validate_spot_max_price)
            c.argument('tags', tags_type)
            c.argument('labels', nargs='*', validator=validate_nodepool_labels)
            c.argument('mode', get_enum_type(nodepool_mode_type))
            c.argument('enable_node_public_ip',
                       action='store_true',
                       is_preview=True)
            c.argument('ppg', type=str, validator=validate_ppg)
            c.argument('max_surge', type=str, validator=validate_max_surge)
            c.argument('node_os_disk_type',
                       arg_type=get_enum_type([
                           CONST_OS_DISK_TYPE_MANAGED,
                           CONST_OS_DISK_TYPE_EPHEMERAL
                       ]))

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

    with self.argument_context('aks nodepool update') as c:
        c.argument('enable_cluster_autoscaler',
                   options_list=["--enable-cluster-autoscaler", "-e"],
                   action='store_true')
        c.argument('disable_cluster_autoscaler',
                   options_list=["--disable-cluster-autoscaler", "-d"],
                   action='store_true')
        c.argument('update_cluster_autoscaler',
                   options_list=["--update-cluster-autoscaler", "-u"],
                   action='store_true')
        c.argument('tags', tags_type)
        c.argument('mode', get_enum_type(nodepool_mode_type))
        c.argument('max_surge', type=str, validator=validate_max_surge)

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

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

    # OpenShift command argument configuration
    with self.argument_context('openshift') 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.'
        )
Beispiel #4
0
from argcomplete.completers import FilesCompleter
from milc import cli

import qmk.keymap
import qmk.path
from qmk.json_encoders import InfoJSONEncoder
from qmk.keyboard import keyboard_completer, keyboard_folder
from qmk.errors import CppError


@cli.argument('--no-cpp', arg_only=True, action='store_false', help='Do not use \'cpp\' on keymap.c')
@cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
@cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
@cli.argument('-kb', '--keyboard', arg_only=True, type=keyboard_folder, completer=keyboard_completer, required=True, help='The keyboard\'s name')
@cli.argument('-km', '--keymap', arg_only=True, required=True, help='The keymap\'s name')
@cli.argument('filename', arg_only=True, completer=FilesCompleter('.c'), help='keymap.c file')
@cli.subcommand('Creates a keymap.json from a keymap.c file.')
def c2json(cli):
    """Generate a keymap.json from a keymap.c file.

    This command uses the `qmk.keymap` module to generate a keymap.json from a keymap.c file. The generated keymap is written to stdout, or to a file if -o is provided.
    """
    if cli.args.filename != '-':
        cli.args.filename = qmk.path.normpath(cli.args.filename)

        # Error checking
        if not cli.args.filename.exists():
            cli.log.error('C file does not exist!')
            cli.print_usage()
            return False
Beispiel #5
0
def create_argparse_analyze(subparsers):
    subparse = subparsers.add_parser(
        "a",  # aliases=("analyze",),
        help="Analyze a given file",
    )
    subparse.add_argument(
        dest="path",
        type=str,
        help="Path to checkout on the server",
    ).completer = FilesCompleter(directories=False)

    group = subparse.add_mutually_exclusive_group()
    group.add_argument(
        "-o",
        "--output",
        dest="output",
        type=str,
        help="The file to write the binary output to",
    )
    group.add_argument(
        "-f",
        "--format",
        dest="format",
        type=str,
        help="The format to output",
    ).completer = ChoicesCompleter(['print', 'binary', 'json', 'json-pretty'])
    group.add_argument(
        "-s",
        "--store",
        dest="store",
        type=str,
        help="The store to write the binary output to",
    ).completer = FilesCompleter(['ignore'])

    def analyze(path, output, format_type, store):
        from .analyzer import Analyzer
        from .metadatastore import MetaDataStore
        from damn_at.serialization import SerializeThriftMsg
        from .utilities import calculate_hash_for_file

        analyzer = Analyzer()
        descr = analyzer.analyze_file(path)
        descr.file.hash = calculate_hash_for_file(path)
        if not format_type and not output and not store:
            LOG.info(serialize_file_description(descr, 'print'))
            # print(serialize_file_description(descr, 'print'))
        elif not output and not store:
            print(serialize_file_description(descr, format_type))
            # print(serialize_file_description(descr, format_type))
        elif output:
            with open(output, 'wb') as file:
                data = SerializeThriftMsg(descr)
                file.write(data)
        elif store:
            store = MetaDataStore(store)
            hash = descr.file.hash
            store.write_metadata('', hash, descr)
        else:
            assert False  # Error in logic

    subparse.set_defaults(func=lambda args: analyze(args.path, args.output,
                                                    args.format, args.store), )
Beispiel #6
0
def load_arguments(self, _):

    with self.argument_context('backup') as c:
        c.argument('force', action='store_true', help='Force completion of the requested action.')

    # Vault
    with self.argument_context('backup vault') as c:
        c.argument('vault_name', vault_name_type, options_list=['--name', '-n'], id_part='name')
        c.argument('location', validator=get_default_location_from_resource_group)

    with self.argument_context('backup vault backup-properties set') as c:
        c.argument('backup_storage_redundancy', arg_type=get_enum_type(['GeoRedundant', 'LocallyRedundant']), help='Sets backup storage properties for a Recovery Services vault.')
        c.argument('soft_delete_feature_state', arg_type=get_enum_type(['Enable', 'Disable']), help='Set soft-delete feature state for a Recovery Services Vault.')

    # Container
    with self.argument_context('backup container') as c:
        c.argument('vault_name', vault_name_type, id_part='name')
        c.ignore('status')

    with self.argument_context('backup container show') as c:
        c.argument('name', container_name_type, options_list=['--name', '-n'], help='Name of the container. You can use the backup container list command to get the name of a container.')
        c.argument('backup_management_type', backup_management_type)
    with self.argument_context('backup container list') as c:
        c.argument('vault_name', vault_name_type, id_part=None)
        c.argument('backup_management_type', backup_management_type)

    with self.argument_context('backup container unregister') as c:
        c.argument('backup_management_type', backup_management_type)
        c.argument('container_name', container_name_type)

    with self.argument_context('backup container re-register') as c:
        c.argument('backup_management_type', backup_management_type)
        c.argument('container_name', container_name_type)
        c.argument('workload_type', workload_type)

    with self.argument_context('backup container register') as c:
        c.argument('backup_management_type', backup_management_type)
        c.argument('resource_id', resource_id_type)
        c.argument('workload_type', workload_type)

    # Item
    with self.argument_context('backup item') as c:
        c.argument('vault_name', vault_name_type, id_part='name')
        c.argument('container_name', container_name_type)

    with self.argument_context('backup item show') as c:
        c.argument('name', item_name_type, options_list=['--name', '-n'], help='Name of the backed up item. You can use the backup item list command to get the name of a backed up item.')
        c.argument('backup_management_type', backup_management_type)
        c.argument('workload_type', workload_type)

    # TODO: Need to use item.id once https://github.com/Azure/msrestazure-for-python/issues/80 is fixed.
    with self.argument_context('backup item set-policy') as c:
        c.argument('item_name', item_name_type, options_list=['--name', '-n'], id_part='name', help='Name of the backed up item. You can use the backup item list command to get the name of a backed up item.')
        c.argument('policy_name', policy_name_type, help='Name of the Backup policy. You can use the backup policy list command to get the name of a backup policy.')
        c.argument('backup_management_type', options_list=['--backup-management-type'], help=backup_management_type_help)
        c.argument('workload_type', workload_type)

    with self.argument_context('backup item list') as c:
        c.argument('vault_name', vault_name_type, id_part=None)
        c.argument('backup_management_type', backup_management_type)
        c.argument('workload_type', workload_type)

    # Policy
    with self.argument_context('backup policy') as c:
        c.argument('vault_name', vault_name_type, id_part='name')

    for command in ['show', 'delete', 'list-associated-items']:
        with self.argument_context('backup policy ' + command) as c:
            c.argument('name', policy_name_type, options_list=['--name', '-n'], help='Name of the backup policy. You can use the backup policy list command to get the name of a policy.')

    with self.argument_context('backup policy list-associated-items') as c:
        c.argument('backup_management_type', backup_management_type)

    with self.argument_context('backup policy set') as c:
        c.argument('policy', type=file_type, help='JSON encoded policy definition. Use the show command with JSON output to obtain a policy object. Modify the values using a file editor and pass the object.', completer=FilesCompleter())
        c.argument('name', options_list=['--name', '-n'], help='Name of the Policy.')

    with self.argument_context('backup policy create') as c:
        c.argument('policy', type=file_type, help='JSON encoded policy definition. Use the show command with JSON output to obtain a policy object. Modify the values using a file editor and pass the object.', completer=FilesCompleter())
        c.argument('name', options_list=['--name', '-n'], help='Name of the Policy.')
        c.argument('backup_management_type', backup_management_type)
        c.argument('workload_type', workload_type)

    with self.argument_context('backup policy list') as c:
        c.argument('vault_name', vault_name_type, id_part=None)
        c.argument('backup_management_type', backup_management_type)
        c.argument('workload_type', workload_type)

    # Recovery Point
    # TODO: Need to use item.id once https://github.com/Azure/msrestazure-for-python/issues/80 is fixed.
    with self.argument_context('backup recoverypoint') as c:
        c.argument('vault_name', vault_name_type, id_part='name')
        c.argument('container_name', container_name_type)
        c.argument('item_name', item_name_type)

    for command in ['list', 'show-log-chain']:
        with self.argument_context('backup recoverypoint ' + command) as c:
            c.argument('vault_name', vault_name_type, id_part=None)
            c.argument('start_date', type=datetime_type, help='The start date of the range in UTC (d-m-Y).')
            c.argument('end_date', type=datetime_type, help='The end date of the range in UTC (d-m-Y).')
            c.argument('backup_management_type', backup_management_type)
            c.argument('container_name', container_name_type)
            c.argument('workload_type', workload_type)

    with self.argument_context('backup recoverypoint show') as c:
        c.argument('name', rp_name_type, options_list=['--name', '-n'], help='Name of the recovery point. You can use the backup recovery point list command to get the name of a backed up item.')
        c.argument('backup_management_type', backup_management_type)
        c.argument('container_name', container_name_type)
        c.argument('workload_type', workload_type)

    # Protection
    with self.argument_context('backup protection') as c:
        c.argument('vault_name', vault_name_type, id_part='name')
        c.argument('vm', help='Name or ID of the Virtual Machine to be protected.')
        c.argument('policy_name', policy_name_type)

    # TODO: Need to use item.id once https://github.com/Azure/msrestazure-for-python/issues/80 is fixed.
    for command in ['backup-now', 'disable', 'auto-disable-for-azurewl', 'resume', 'undelete', 'update-for-vm']:
        with self.argument_context('backup protection ' + command) as c:
            c.argument('container_name', container_name_type)
            c.argument('item_name', item_name_type)
            c.argument('backup_management_type', backup_management_type)
            c.argument('workload_type', workload_type)
            c.argument('enable_compression', arg_type=get_three_state_flag(), help='Option to enable compression')
            c.argument('backup_type', help=backup_type_help, options_list=['--backup-type'])

    with self.argument_context('backup protection backup-now') as c:
        c.argument('retain_until', type=datetime_type, help=retain_until_help)

    with self.argument_context('backup protection disable') as c:
        c.argument('delete_backup_data', arg_type=get_three_state_flag(), help='Option to delete existing backed up data in the Recovery services vault.')
        c.argument('backup_management_type', backup_management_type)
        c.argument('workload_type', workload_type)

    with self.argument_context('backup protection check-vm') as c:
        c.argument('vm_id', help='ID of the virtual machine to be checked for protection.')

    with self.argument_context('backup protection enable-for-vm') as c:
        c.argument('diskslist', diskslist_type)
        c.argument('disk_list_setting', arg_type=get_enum_type(['include', 'exclude']), options_list=['--disk-list-setting'], help=disk_list_setting_help)

    with self.argument_context('backup protection update-for-vm') as c:
        c.argument('diskslist', diskslist_type)
        c.argument('disk_list_setting', arg_type=get_enum_type(['include', 'exclude', 'resetexclusionsettings']), options_list=['--disk-list-setting'], help=disk_list_setting_help)

    with self.argument_context('backup protection enable-for-azurefileshare') as c:
        c.argument('azure_file_share', options_list=['--azure-file-share'], help='Name of the Azure FileShare.')
        c.argument('storage_account', options_list=['--storage-account'], help='Name of the Storage Account of the FileShare.')

    for command in ["enable-for-azurewl", "auto-enable-for-azurewl"]:
        with self.argument_context('backup protection ' + command) as c:
            c.argument('protectable_item_type', protectable_item_type)
            c.argument('protectable_item_name', protectable_item_name_type)
            c.argument('server_name', options_list=['--server-name'], help='Parent Server name of the item.')
            c.argument('workload_type', workload_type)

    # Protectable-item
    with self.argument_context('backup protectable-item') as c:
        c.argument('vault_name', vault_name_type)
        c.argument('workload_type', workload_type)
        c.argument('container_name', container_name_type)

    with self.argument_context('backup protectable-item show') as c:
        c.argument('name', options_list=['--name'], help='Name of the protectable item.')
        c.argument('server_name', options_list=['--server-name'], help='Parent Server name of the item.')
        c.argument('protectable_item_type', protectable_item_type)

    # Restore
    # TODO: Need to use recovery_point.id once https://github.com/Azure/msrestazure-for-python/issues/80 is fixed.
    with self.argument_context('backup restore') as c:
        c.argument('vault_name', vault_name_type, id_part='name')
        c.argument('container_name', container_name_type)
        c.argument('item_name', item_name_type)
        c.argument('rp_name', rp_name_type)

    with self.argument_context('backup restore restore-disks') as c:
        c.argument('storage_account', help='Name or ID of the staging storage account. The VM configuration will be restored to this storage account. See the help for --restore-to-staging-storage-account parameter for more info.')
        c.argument('restore_to_staging_storage_account', arg_type=get_three_state_flag(), help='Use this flag when you want disks to be restored to the staging storage account using the --storage-account parameter. When not specified, disks will be restored to their original storage accounts. Default: false.')
        c.argument('target_resource_group', options_list=['--target-resource-group', '-t'], help='Use this to specify the target resource group in which the restored disks will be saved')
        c.argument('diskslist', diskslist_type)
        c.argument('restore_only_osdisk', arg_type=get_three_state_flag(), help='Use this flag to restore only OS disks of a backed up VM.')

    with self.argument_context('backup restore restore-azurefileshare') as c:
        c.argument('resolve_conflict', resolve_conflict_type)
        c.argument('restore_mode', restore_mode_type)
        c.argument('target_file_share', options_list=['--target-file-share'], help='Destination file share to which content will be restored')
        c.argument('target_folder', options_list=['--target-folder'], help='Destination folder to which content will be restored. To restore content to root , leave the folder name empty')
        c.argument('target_storage_account', options_list=['--target-storage-account'], help='Destination storage account to which content will be restored')

    with self.argument_context('backup restore restore-azurefiles') as c:
        c.argument('resolve_conflict', resolve_conflict_type)
        c.argument('restore_mode', restore_mode_type)
        c.argument('target_file_share', options_list=['--target-file-share'], help='Destination file share to which content will be restored')
        c.argument('target_folder', options_list=['--target-folder'], help='Destination folder to which content will be restored. To restore content to root , leave the folder name empty')
        c.argument('target_storage_account', options_list=['--target-storage-account'], help='Destination storage account to which content will be restored')
        c.argument('source_file_type', arg_type=get_enum_type(['File', 'Directory']), options_list=['--source-file-type'], help='Specify the source file type to be selected')
        c.argument('source_file_path', options_list=['--source-file-path'], help="""The absolute path of the file, to be restored within the file share, as a string. This path is the same path used in the 'az storage file download' or 'az storage file show' CLI commands.""")

    with self.argument_context('backup restore restore-azurewl') as c:
        c.argument('recovery_config', options_list=['--recovery-config'], help="""Specify the recovery configuration of a backed up item. The configuration object can be obtained from 'backup recoveryconfig show' command.""")

    # Recoveryconfig
    with self.argument_context('backup recoveryconfig show') as c:
        c.argument('container_name', container_name_type)
        c.argument('item_name', item_name_type)
        c.argument('restore_mode', restore_mode_workload_type)
        c.argument('vault_name', vault_name_type)
        c.argument('log_point_in_time', options_list=['--log-point-in-time'], help="""Specify the point-in-time which will be restored.""")
        c.argument('rp_name', rp_name_type)
        c.argument('target_item_name', options_list=['--target-item-name'], help="""Specify the target item name for the restore operation.""")
        c.argument('target_server_type', target_server_type)
        c.argument('target_server_name', options_list=['--target-server-name'], help="""Specify the parent server name of the target item.""")
        c.argument('workload_type', workload_type)
        c.argument('target_container_name', target_container_name_type)
        c.argument('from_full_rp_name', from_full_rp_type)
        c.argument('filepath', filepath_type)
        c.argument('backup_management_type', backup_management_type)

    # Job
    with self.argument_context('backup job') as c:
        c.argument('vault_name', vault_name_type, id_part='name')

    # TODO: Need to use job.id once https://github.com/Azure/msrestazure-for-python/issues/80 is fixed.
    for command in ['show', 'stop', 'wait']:
        with self.argument_context('backup job ' + command) as c:
            c.argument('name', job_name_type, help='Name of the job. You can use the backup job list command to get the name of a job.')

    with self.argument_context('backup job list') as c:
        c.argument('vault_name', vault_name_type, id_part=None)
        c.argument('status', arg_type=get_enum_type(['Cancelled', 'Completed', 'CompletedWithWarnings', 'Failed', 'InProgress']), help='Status of the Job.')
        c.argument('operation', arg_type=get_enum_type(['Backup', 'ConfigureBackup', 'DeleteBackupData', 'DisableBackup', 'Restore']), help='User initiated operation.')
        c.argument('start_date', type=datetime_type, help='The start date of the range in UTC (d-m-Y).')
        c.argument('end_date', type=datetime_type, help='The end date of the range in UTC (d-m-Y).')

    with self.argument_context('backup job wait') as c:
        c.argument('timeout', type=int, help='Maximum time, in seconds, to wait before aborting.')
Beispiel #7
0
    def _get_arg_parser(self, doc_parser=False):
        description = textwrap.dedent(__doc__)

        examples = textwrap.dedent('''
            mdt-create-mask data.nii.gz data.prtcl
            mdt-create-mask data.nii.gz data.prtcl -o data_mask.nii.gz
            mdt-create-mask data.nii.gz data.prtcl -o data_mask.nii.gz --median-radius 2
        ''')
        epilog = self._format_examples(doc_parser, examples)

        parser = argparse.ArgumentParser(
            description=description,
            epilog=epilog,
            formatter_class=argparse.RawTextHelpFormatter)
        parser.add_argument(
            'dwi',
            action=mdt.lib.shell_utils.get_argparse_extension_checker(
                ['.nii', '.nii.gz', '.hdr', '.img']),
            help='the diffusion weighted image').completer = FilesCompleter(
                ['nii', 'gz', 'hdr', 'img'], directories=False)
        parser.add_argument('protocol',
                            action=mdt.lib.shell_utils.get_argparse_extension_checker(['.prtcl']),
                            help='the protocol file, see mdt-create-protocol').\
            completer = FilesCompleter(['prtcl'], directories=False)
        parser.add_argument('-o', '--output-name',
                            action=mdt.lib.shell_utils.get_argparse_extension_checker(['.nii', '.nii.gz', '.hdr', '.img']),
                            help='the filename of the output file. Default is <dwi_name>_mask.nii.gz').completer = \
            FilesCompleter(['nii', 'gz', 'hdr', 'img'], directories=False)

        parser.add_argument(
            '--median-radius',
            type=int,
            default=4,
            help="Radius (in voxels) of the applied median filter (default 4)."
        )

        parser.add_argument(
            '--mask-threshold',
            type=float,
            default=0,
            help=
            "Everything below this b-value threshold is masked away (value in s/m^2, default 0)"
        )

        parser.add_argument(
            '--numpass',
            type=int,
            default=4,
            help="Number of pass of the median filter (default 4).")

        parser.add_argument(
            '--dilate',
            type=int,
            default=1,
            help="Number of iterations for binary dilation (default 1).")

        parser.add_argument(
            '--cl-device-ind',
            type=int,
            nargs='*',
            choices=self.available_devices.keys(),
            help=
            "The index of the device we would like to use. This follows the indices "
            "in mdt-list-devices and defaults to the first GPU.")

        return parser
Beispiel #8
0
def load_arguments(self, _):  # pylint: disable=too-many-locals, too-many-statements
    from argcomplete.completers import FilesCompleter
    from six import u as unicode_string

    from knack.arguments import ignore_type, CLIArgumentType

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('storage account network-rule') as c:
        from ._validators import validate_subnet
        c.argument('storage_account_name', acct_name_type, id_part=None)
        c.argument('ip_address', help='IPv4 address or CIDR range.')
        c.argument(
            'subnet',
            help=
            'Name or ID of subnet. If name is supplied, `--vnet-name` must be supplied.'
        )
        c.argument('vnet_name',
                   help='Name of a virtual network.',
                   validator=validate_subnet)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        c.register_source_uri_arguments(validator=validate_source_uri)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        c.register_path_argument()
        c.register_sas_arguments()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        c.register_source_uri_arguments(validator=validate_source_uri)

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

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

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

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

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

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

        c.register_sas_arguments()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('storage entity query') as c:
        c.argument(
            'accept',
            default='minimal',
            validator=validate_table_payload_format,
            arg_type=get_enum_type(['none', 'minimal', 'full']),
            help=
            'Specifies how much metadata to include in the response payload.')
Beispiel #9
0
    def _get_arg_parser(self, doc_parser=False):
        description = textwrap.dedent(__doc__)

        examples = textwrap.dedent('''
            mdt-math-img fiso.nii ficvf.nii '(1-input[0]) * i[1]' -o Wic.w.nii.gz
            mdt-math-img fiso.nii ficvf.nii '(1-a) * b' -o Wic.w.nii.gz
            mdt-math-img *.nii.gz 'np.mean(np.concatenate(i, axis=3), axis=3)' -o output.nii.gz
            mdt-math-img FA.nii.gz 'np.mean(a)'
            mdt-math-img FA.nii white_matter_mask.nii 'np.mean(mdt.create_roi(a, b))'
            mdt-math-img images*.nii.gz mask.nii 'list(map(lambda f: np.mean(mdt.create_roi(f, i[-1])), i[0:-1]))'
            mdt-math-img FA.nii.gz
            mdt-math-img timeseries.nii '[a[..., ind] for ind in range(a.shape[-1])]' -o split.nii
           ''')
        epilog = self._format_examples(doc_parser, examples)

        parser = argparse.ArgumentParser(
            description=description,
            epilog=epilog,
            formatter_class=argparse.RawTextHelpFormatter)

        parser.add_argument('input_files',
                            metavar='input_files',
                            nargs="+",
                            type=str,
                            help="The input images to use")

        parser.add_argument('expr',
                            metavar='expr',
                            type=str,
                            help="The expression/statement to evaluate.")

        parser.add_argument(
            '-e',
            '--as-expression',
            dest='as_expression',
            action='store_true',
            help="Evaluates the given string as an expression (default).")
        parser.add_argument('-s',
                            '--as-statement',
                            dest='as_expression',
                            action='store_false',
                            help="Evaluates the given string as an statement.")
        parser.set_defaults(as_expression=True)

        parser.add_argument('-o', '--output-file',
                            help='the output file, if not set nothing is written').completer = \
            FilesCompleter(['nii', 'gz', 'hdr', 'img'], directories=False)

        parser.add_argument(
            '-4d',
            '--input-4d',
            action='store_true',
            help=
            'Add a singleton dimension to all input 3d maps to make them 4d, this prevents '
            'some broadcast issues.')

        parser.add_argument('--verbose',
                            '-v',
                            action='store_true',
                            help="Verbose, prints runtime information")

        return parser
Beispiel #10
0
def load_arguments(self, _):
    (JsonWebKeyOperation, KeyAttributes, JsonWebKeyType, JsonWebKeyCurveName, SasTokenType,
     SasDefinitionAttributes, SecretAttributes, CertificateAttributes, StorageAccountAttributes) = self.get_models(
         'JsonWebKeyOperation', 'KeyAttributes', 'JsonWebKeyType', 'JsonWebKeyCurveName', 'SasTokenType',
         'SasDefinitionAttributes', 'SecretAttributes', 'CertificateAttributes', 'StorageAccountAttributes',
         resource_type=ResourceType.DATA_KEYVAULT)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # endregion

    # region KeyVault Storage Account

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    for scope in ['list', 'list-deleted', 'list-versions']:
        with self.argument_context('keyvault certificate {}'.format(scope)) as c:
            c.argument('maxresults', options_list=['--maxresults'], type=int)
Beispiel #11
0
def parse_cmdline_args():
    """
    Parse the user's command-lines, with support for tab-completion.
    """
    prog_name = sys.argv[0]
    if prog_name[0] not in (".", "/"):
        prog_name = "./" + prog_name

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        "-l",
        "--list",
        action="store_true",
        help="List the recipe names in the specs file",
    )
    specs_path_arg = parser.add_argument(
        "recipe_specs_path", help="Path to a recipe specs YAML file")
    selection_arg = parser.add_argument(
        "selected_recipes",
        nargs="*",
        help="Which recipes to process (Default: process all)",
    )
    parser.add_argument(
        "--start-from",
        default=os.environ.get("PUBLISH_START_FROM", ""),
        help="Recipe name to start from building recipe specs in YAML file.",
    )
    parser.add_argument(
        "--label",
        action="append",
        default=[],
        help=
        "Use label(s) when uploading package. Can be added multiple times.",
    )
    parser.add_argument("--token",
                        default="",
                        help="Token used for anaconda upload.")
    parser.add_argument(
        "--logfile",
        "-o",
        default="",
        help=("Specify custom output path of the log/summary yaml file, "
              "or a directory in which to store it with an auto-chosen name."),
    )

    if ENABLE_TAB_COMPLETION:

        def complete_recipe_selection(prefix, action, parser, parsed_args):
            specs_file_contents = yaml.load(
                open(parsed_args.recipe_specs_path, "r"))
            recipe_specs = specs_file_contents["recipe-specs"]
            names = (spec["name"] for spec in recipe_specs)
            return filter(lambda name: name.startswith(prefix), names)

        specs_path_arg.completer = FilesCompleter((".yml", ".yaml"),
                                                  directories=False)
        selection_arg.completer = complete_recipe_selection
        argcomplete.autocomplete(parser)

    args = parser.parse_args()
    return args
Beispiel #12
0
def load_arguments(self, _):

    acr_arg_type = CLIArgumentType(metavar='ACR_NAME_OR_RESOURCE_ID')

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

    with self.argument_context('aks create') as c:
        c.argument('name', validator=validate_linux_host_name)
        c.argument('kubernetes_version',
                   completer=get_k8s_versions_completion_list)
        c.argument('admin_username',
                   options_list=['--admin-username', '-u'],
                   default='azureuser')
        c.argument('windows_admin_username',
                   options_list=['--windows-admin-username'])
        c.argument('windows_admin_password',
                   options_list=['--windows-admin-password'])
        c.argument('enable_ahub', options_list=['--enable-ahub'])
        c.argument('dns_name_prefix', options_list=['--dns-name-prefix', '-p'])
        c.argument('generate_ssh_keys',
                   action='store_true',
                   validator=validate_create_parameters)
        c.argument('node_vm_size',
                   options_list=['--node-vm-size', '-s'],
                   completer=get_vm_size_completion_list)
        c.argument('nodepool_name',
                   type=str,
                   default='nodepool1',
                   help='Node pool name, upto 12 alphanumeric characters',
                   validator=validate_nodepool_name)
        c.argument(
            'nodepool_tags',
            nargs='*',
            validator=validate_nodepool_tags,
            help=
            'space-separated tags: key[=value] [key[=value] ...]. Use "" to clear existing tags.'
        )
        c.argument(
            'nodepool_labels',
            nargs='*',
            validator=validate_nodepool_labels,
            help=
            'space-separated labels: key[=value] [key[=value] ...]. You can not change the node labels through CLI after creation. See https://aka.ms/node-labels for syntax of labels.'
        )
        c.argument('ssh_key_value',
                   required=False,
                   type=file_type,
                   default=os.path.join('~', '.ssh', 'id_rsa.pub'),
                   completer=FilesCompleter(),
                   validator=validate_ssh_key)
        c.argument('aad_client_app_id')
        c.argument('aad_server_app_id')
        c.argument('aad_server_app_secret')
        c.argument('aad_tenant_id')
        c.argument('dns_service_ip')
        c.argument('docker_bridge_address')
        c.argument('load_balancer_sku',
                   type=str,
                   validator=validate_load_balancer_sku)
        c.argument('load_balancer_managed_outbound_ip_count', type=int)
        c.argument('load_balancer_outbound_ips',
                   type=str,
                   validator=validate_load_balancer_outbound_ips)
        c.argument('load_balancer_outbound_ip_prefixes',
                   type=str,
                   validator=validate_load_balancer_outbound_ip_prefixes)
        c.argument('load_balancer_outbound_ports',
                   type=int,
                   validator=validate_load_balancer_outbound_ports)
        c.argument('load_balancer_idle_timeout',
                   type=int,
                   validator=validate_load_balancer_idle_timeout)
        c.argument('outbound_type',
                   arg_type=get_enum_type([
                       CONST_OUTBOUND_TYPE_LOAD_BALANCER,
                       CONST_OUTBOUND_TYPE_USER_DEFINED_ROUTING
                   ]))
        c.argument('enable_addons',
                   options_list=['--enable-addons', '-a'],
                   validator=validate_addons)
        c.argument('disable_rbac', action='store_true')
        c.argument('enable_rbac',
                   action='store_true',
                   options_list=['--enable-rbac', '-r'],
                   deprecate_info=c.deprecate(redirect="--disable-rbac",
                                              hide="2.0.45"))
        c.argument('max_pods', type=int, options_list=['--max-pods', '-m'])
        c.argument('network_plugin',
                   arg_type=get_enum_type(['azure', 'kubenet']))
        c.argument('network_policy')
        c.argument('no_ssh_key', options_list=['--no-ssh-key', '-x'])
        c.argument('pod_cidr')
        c.argument('service_cidr')
        c.argument('vnet_subnet_id',
                   type=str,
                   validator=validate_vnet_subnet_id)
        c.argument('pod_subnet_id', type=str, validator=validate_pod_subnet_id)
        c.argument('ppg')
        c.argument('workspace_resource_id')
        c.argument('skip_subnet_role_assignment', action='store_true')
        c.argument('enable_fips_image', action='store_true', is_preview=True)
        c.argument('enable_cluster_autoscaler', action='store_true')
        c.argument('uptime_sla', action='store_true')
        c.argument('cluster_autoscaler_profile',
                   nargs='+',
                   validator=validate_cluster_autoscaler_profile)
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('enable_vmss',
                   action='store_true',
                   help='To be deprecated. Use vm_set_type instead.')
        c.argument('vm_set_type', type=str, validator=validate_vm_set_type)
        c.argument(
            'node_zones',
            zones_type,
            options_list=['--node-zones', '--zones', '-z'],
            help=
            '(--node-zones will be deprecated, use --zones) Space-separated list of availability zones where agent nodes will be placed.'
        )
        c.argument('enable_node_public_ip', action='store_true')
        c.argument('node_public_ip_prefix_id', type=str)
        c.argument('enable_pod_security_policy', action='store_true')
        c.argument('node_resource_group')
        c.argument('attach_acr', acr_arg_type)
        c.argument('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)
        c.argument('enable_ahub', options_list=['--enable-ahub'])
        c.argument('disable_ahub', options_list=['--disable-ahub'])
        c.argument('aks_custom_headers')
        c.argument('enable_private_cluster', action='store_true')
        c.argument('private_dns_zone')
        c.argument('fqdn_subdomain')
        c.argument('enable_managed_identity', action='store_true')
        c.argument('assign_identity',
                   type=str,
                   validator=validate_assign_identity)
        c.argument('enable_sgxquotehelper', action='store_true')
        c.argument('auto_upgrade_channel',
                   arg_type=get_enum_type([
                       CONST_RAPID_UPGRADE_CHANNEL,
                       CONST_STABLE_UPGRADE_CHANNEL,
                       CONST_PATCH_UPGRADE_CHANNEL,
                       CONST_NODE_IMAGE_UPGRADE_CHANNEL,
                       CONST_NONE_UPGRADE_CHANNEL
                   ]))
        c.argument('kubelet_config', type=str)
        c.argument('linux_os_config', type=str)
        c.argument('enable_pod_identity', action='store_true')
        c.argument('appgw_name',
                   options_list=['--appgw-name'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_prefix',
                   options_list=['--appgw-subnet-prefix'],
                   arg_group='Application Gateway',
                   deprecate_info=c.deprecate(redirect='--appgw-subnet-cidr',
                                              hide=True))
        c.argument('appgw_subnet_cidr',
                   options_list=['--appgw-subnet-cidr'],
                   arg_group='Application Gateway')
        c.argument('appgw_id',
                   options_list=['--appgw-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_id',
                   options_list=['--appgw-subnet-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_watch_namespace',
                   options_list=['--appgw-watch-namespace'],
                   arg_group='Application Gateway')
        c.argument('aci_subnet_name', type=str)
        c.argument('enable_encryption_at_host',
                   arg_type=get_three_state_flag(),
                   help='Enable EncryptionAtHost.')
        c.argument('enable_secret_rotation', action='store_true')
        c.argument('assign_kubelet_identity',
                   type=str,
                   validator=validate_assign_kubelet_identity)
        c.argument('disable_local_accounts', action='store_true')
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.',
                   action='store_true')

    with self.argument_context('aks update') as c:
        c.argument('enable_cluster_autoscaler',
                   options_list=["--enable-cluster-autoscaler", "-e"],
                   action='store_true')
        c.argument('disable_cluster_autoscaler',
                   options_list=["--disable-cluster-autoscaler", "-d"],
                   action='store_true')
        c.argument('update_cluster_autoscaler',
                   options_list=["--update-cluster-autoscaler", "-u"],
                   action='store_true')
        c.argument('cluster_autoscaler_profile',
                   nargs='+',
                   validator=validate_cluster_autoscaler_profile)
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('uptime_sla', action='store_true')
        c.argument('no_uptime_sla', action='store_true')
        c.argument('load_balancer_managed_outbound_ip_count', type=int)
        c.argument('load_balancer_outbound_ips',
                   type=str,
                   validator=validate_load_balancer_outbound_ips)
        c.argument('load_balancer_outbound_ip_prefixes',
                   type=str,
                   validator=validate_load_balancer_outbound_ip_prefixes)
        c.argument('load_balancer_outbound_ports',
                   type=int,
                   validator=validate_load_balancer_outbound_ports)
        c.argument('load_balancer_idle_timeout',
                   type=int,
                   validator=validate_load_balancer_idle_timeout)
        c.argument('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)
        c.argument('enable_pod_security_policy', action='store_true')
        c.argument('disable_pod_security_policy', action='store_true')
        c.argument('attach_acr', acr_arg_type, validator=validate_acr)
        c.argument('detach_acr', acr_arg_type, validator=validate_acr)
        c.argument('aks_custom_headers')
        c.argument('auto_upgrade_channel',
                   arg_type=get_enum_type([
                       CONST_RAPID_UPGRADE_CHANNEL,
                       CONST_STABLE_UPGRADE_CHANNEL,
                       CONST_PATCH_UPGRADE_CHANNEL,
                       CONST_NODE_IMAGE_UPGRADE_CHANNEL,
                       CONST_NONE_UPGRADE_CHANNEL
                   ]))
        c.argument('enable_managed_identity', action='store_true')
        c.argument('assign_identity',
                   type=str,
                   validator=validate_assign_identity)
        c.argument('enable_pod_identity', action='store_true')
        c.argument('disable_pod_identity', action='store_true')
        c.argument('enable_secret_rotation', action='store_true')
        c.argument('disable_secret_rotation', action='store_true')
        c.argument('windows_admin_password',
                   options_list=['--windows-admin-password'])
        c.argument('disable_local_accounts', action='store_true')
        c.argument('enable_local_accounts', action='store_true')
        c.argument('yes',
                   options_list=['--yes', '-y'],
                   help='Do not prompt for confirmation.',
                   action='store_true')

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

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

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

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

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

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

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

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

    for scope in ['aks nodepool add']:
        with self.argument_context(scope) as c:
            c.argument('nodepool_name',
                       type=str,
                       options_list=['--name', '-n'],
                       validator=validate_nodepool_name,
                       help='The node pool name.')
            c.argument('tags', tags_type)
            c.argument(
                'node_zones',
                zones_type,
                options_list=['--node-zones', '--zones', '-z'],
                help=
                '(--node-zones will be deprecated) Space-separated list of availability zones where agent nodes will be placed.'
            )
            c.argument('enable_node_public_ip', action='store_true')
            c.argument('node_public_ip_prefix_id', type=str)
            c.argument('node_vm_size',
                       options_list=['--node-vm-size', '-s'],
                       completer=get_vm_size_completion_list)
            c.argument('max_pods', type=int, options_list=['--max-pods', '-m'])
            c.argument('os_type', type=str)
            c.argument('enable_fips_image',
                       action='store_true',
                       is_preview=True)
            c.argument('enable_cluster_autoscaler',
                       options_list=["--enable-cluster-autoscaler", "-e"],
                       action='store_true')
            c.argument('node_taints', type=str, validator=validate_taints)
            c.argument('priority',
                       arg_type=get_enum_type([
                           CONST_SCALE_SET_PRIORITY_REGULAR,
                           CONST_SCALE_SET_PRIORITY_SPOT
                       ]),
                       validator=validate_priority)
            c.argument('eviction_policy',
                       arg_type=get_enum_type([
                           CONST_SPOT_EVICTION_POLICY_DELETE,
                           CONST_SPOT_EVICTION_POLICY_DEALLOCATE
                       ]),
                       validator=validate_eviction_policy)
            c.argument('spot_max_price',
                       type=float,
                       validator=validate_spot_max_price)
            c.argument('labels', nargs='*', validator=validate_nodepool_labels)
            c.argument('mode',
                       arg_type=get_enum_type([
                           CONST_NODEPOOL_MODE_SYSTEM, CONST_NODEPOOL_MODE_USER
                       ]))
            c.argument('aks_custom_headers')
            c.argument('ppg')
            c.argument('max_surge', type=str, validator=validate_max_surge)
            c.argument('node_os_disk_type',
                       arg_type=get_enum_type([
                           CONST_OS_DISK_TYPE_MANAGED,
                           CONST_OS_DISK_TYPE_EPHEMERAL
                       ]))
            c.argument('vnet_subnet_id',
                       type=str,
                       validator=validate_vnet_subnet_id)
            c.argument('pod_subnet_id',
                       type=str,
                       validator=validate_pod_subnet_id)
            c.argument('kubelet_config', type=str)
            c.argument('linux_os_config', type=str)
            c.argument('enable_encryption_at_host',
                       options_list=['--enable-encryption-at-host'],
                       action='store_true')

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

    with self.argument_context('aks nodepool upgrade') as c:
        c.argument('max_surge', type=str, validator=validate_max_surge)

    with self.argument_context('aks nodepool update') as c:
        c.argument('enable_cluster_autoscaler',
                   options_list=["--enable-cluster-autoscaler", "-e"],
                   action='store_true')
        c.argument('disable_cluster_autoscaler',
                   options_list=["--disable-cluster-autoscaler", "-d"],
                   action='store_true')
        c.argument('update_cluster_autoscaler',
                   options_list=["--update-cluster-autoscaler", "-u"],
                   action='store_true')
        c.argument('tags', tags_type)
        c.argument('mode',
                   arg_type=get_enum_type(
                       [CONST_NODEPOOL_MODE_SYSTEM, CONST_NODEPOOL_MODE_USER]))
        c.argument('max_surge', type=str, validator=validate_max_surge)

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

    with self.argument_context('aks enable-addons') as c:
        c.argument('addons',
                   options_list=['--addons', '-a'],
                   validator=validate_addons)
        c.argument('subnet_name', options_list=['--subnet-name', '-s'])
        c.argument('enable_sgxquotehelper', action='store_true')
        c.argument('osm_mesh_name', options_list=['--osm-mesh-name'])
        c.argument('appgw_name',
                   options_list=['--appgw-name'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_prefix',
                   options_list=['--appgw-subnet-prefix'],
                   arg_group='Application Gateway',
                   deprecate_info=c.deprecate(redirect='--appgw-subnet-cidr',
                                              hide=True))
        c.argument('appgw_subnet_cidr',
                   options_list=['--appgw-subnet-cidr'],
                   arg_group='Application Gateway')
        c.argument('appgw_id',
                   options_list=['--appgw-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_subnet_id',
                   options_list=['--appgw-subnet-id'],
                   arg_group='Application Gateway')
        c.argument('appgw_watch_namespace',
                   options_list=['--appgw-watch-namespace'],
                   arg_group='Application Gateway')
        c.argument('enable_secret_rotation', action='store_true')

    with self.argument_context('aks get-credentials') as c:
        c.argument('admin', options_list=['--admin', '-a'], default=False)
        c.argument('context_name',
                   options_list=['--context'],
                   help='If specified, overwrite the default context name.')
        c.argument('user',
                   options_list=['--user', '-u'],
                   default='clusterUser',
                   validator=validate_user)
        c.argument('path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   default=os.path.join(os.path.expanduser('~'), '.kube',
                                        'config'))

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

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

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

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

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

    with self.argument_context('aks pod-identity exception update') as c:
        c.argument('exc_name',
                   type=str,
                   options_list=['--name', '-n'],
                   required=True,
                   help='The pod identity exception name to remove.',
                   validator=validate_pod_identity_resource_name(
                       'exc_name', required=True))
        c.argument('exc_namespace',
                   type=str,
                   options_list=['--namespace'],
                   required=True,
                   help='The pod identity exception namespace to remove.',
                   validator=validate_pod_identity_resource_namespace)
        c.argument('pod_labels',
                   nargs='*',
                   required=True,
                   help='pod labels in key=value [key=value ...].',
                   validator=validate_pod_identity_pod_labels)
Beispiel #13
0
register_cli_argument('vmss extension', 'extension_name', name_arg_type, help='Name of the extension.')
register_cli_argument('vmss extension', 'vmss_name', id_part=None)
register_cli_argument('vmss diagnostics', 'vmss_name', id_part=None, help='Scale set name')

register_cli_argument('vmss extension image', 'publisher_name', options_list=('--publisher', '-p'), help='Image publisher name')
register_cli_argument('vmss extension image', 'type', options_list=('--name', '-n'), help='Extension name')
register_cli_argument('vmss extension image', 'latest', action='store_true')
register_cli_argument('vmss extension image', 'image_name', help='Image name')
register_cli_argument('vmss extension image', 'orderby', help='The sort to apply on the operation')
register_cli_argument('vmss extension image', 'top', help='Return top number of records')
register_cli_argument('vmss extension image', 'version', help='Extension version')

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

for scope in ['vm', 'vmss']:
    register_cli_argument(scope, '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.')
    register_cli_argument('{} create'.format(scope), 'generate_ssh_keys', action='store_true', help='Generate SSH public and private key files if missing', arg_group='Authentication')


register_cli_argument('vm image list', 'image_location', location_type)
register_cli_argument('vm image', 'publisher_name', options_list=('--publisher', '-p'))
register_cli_argument('vm image', 'offer', options_list=('--offer', '-f'))
register_cli_argument('vm image', 'sku', options_list=('--sku', '-s'))
# overriding skus from the sdk operation to be a single sku
register_cli_argument('vm image show', 'skus', options_list=('--sku', '-s'))

register_cli_argument('vm open-port', 'vm_name', name_arg_type, help='The name of the virtual machine to open inbound traffic on.')
Beispiel #14
0
def load_arguments(self, _):
    from argcomplete.completers import FilesCompleter

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

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

    from knack.arguments import ignore_type, CLIArgumentType

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

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

    # BASIC PARAMETER CONFIGURATION

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('rest') as c:
        c.argument(
            'method',
            options_list=['--method', '-m'],
            arg_type=get_enum_type(
                ['head', 'get', 'put', 'post', 'delete', 'options', 'patch'],
                default='get'),
            help='HTTP request method')
        c.argument(
            'uri',
            options_list=['--url', '--uri', '-u'],
            help='Request URL. If it doesn\'t start with a host, '
            'CLI assumes it as an Azure resource ID and prefixes it with the ARM endpoint of the current '
            'cloud shown by `az cloud show --query endpoints.resourceManager`. Common token {subscriptionId} '
            'will be replaced with the current subscription ID specified by `az account set`'
        )
        c.argument(
            'headers',
            nargs='+',
            help=
            "Space-separated headers in KEY=VALUE format or JSON string. Use @{file} to load from a file"
        )
        c.argument(
            'uri_parameters',
            nargs='+',
            help=
            'Space-separated queries in KEY=VALUE format or JSON string. Use @{file} to load from a file'
        )
        c.argument('skip_authorization_header',
                   action='store_true',
                   help='Do not auto-append Authorization header')
        c.argument(
            'body',
            options_list=['--body', '-b'],
            help=
            'Request body. Use @{file} to load from a file. For quoting issues in different terminals, see https://github.com/Azure/azure-cli/blob/dev/doc/use_cli_effectively.md#quoting-issues'
        )
        c.argument('output_file', help='save response payload to a file')
        c.argument(
            'resource',
            help=
            'Resource url for which CLI should acquire a token from AAD in order to access '
            'the service. The token will be placed in the Authorization header. By default, '
            'CLI can figure this out based on --url argument, unless you use ones not in the list '
            'of "az cloud show --query endpoints"')
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 export') as c:
        c.argument('blueprint_name', options_list=['--name', '-n'], help='Name of the blueprint definition to export.')
        c.argument('output_path', type=file_type, help='The directory path for json definitions of the blueprint and artifacts. The blueprint definition file will be named blueprint.json. Artifacts json files will be in a subdirectory named artifacts.', completer=FilesCompleter())
        c.argument('skip_confirmation', action='store_true', options_list=['--yes', '-y'], help='Skip user confirmation. When set, if directory does not exist, it will be created. If the directory exists and has contents, they will be overwritten. If not set, user will be prompted for permission to proceed')

    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. Use '--depends-on' with no values to remove dependencies.")
        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. Use '--depends-on' with no values to remove dependencies.")
        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. Use '--depends-on' with no values to remove dependencies.")
        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. Use '--depends-on' with no values to remove dependencies.")
        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.')
Beispiel #16
0
 def _populate_matches(self, prefix):
     from argcomplete.completers import FilesCompleter
     completer = FilesCompleter()
     self.matches = completer(prefix)
Beispiel #17
0
disk_list_setting_help = """option to decide whether to include or exclude the disk or reset any previous settings to default behavior"""
target_container_name_help = """The target container to which the DB recovery point should be downloaded as files."""

vault_name_type = CLIArgumentType(help='Name of the Recovery services vault.', options_list=['--vault-name', '-v'], completer=get_resource_name_completion_list('Microsoft.RecoveryServices/vaults'))
container_name_type = CLIArgumentType(help=container_name_help, options_list=['--container-name', '-c'])
item_name_type = CLIArgumentType(help='Name of the backed up item.', options_list=['--item-name', '-i'])
policy_name_type = CLIArgumentType(help='Name of the backup policy.', options_list=['--policy-name', '-p'])
job_name_type = CLIArgumentType(help='Name of the job.', options_list=['--name', '-n'])
rp_name_type = CLIArgumentType(help='Name of the recovery point.', options_list=['--rp-name', '-r'])
backup_management_type = CLIArgumentType(help=backup_management_type_help, arg_type=get_enum_type(allowed_backup_management_types), options_list=['--backup-management-type'])
workload_type = CLIArgumentType(help=workload_type_help, arg_type=get_enum_type(allowed_workload_types), options_list=['--workload-type'])
restore_mode_type = CLIArgumentType(help=restore_mode_help, arg_type=get_enum_type(['OriginalLocation', 'AlternateLocation']), options_list=['--restore-mode'])
restore_mode_workload_type = CLIArgumentType(help=restore_mode_help, arg_type=get_enum_type(['AlternateWorkloadRestore', 'OriginalWorkloadRestore', 'RestoreAsFiles']), options_list=['--restore-mode'])
resolve_conflict_type = CLIArgumentType(help=resolve_conflict_help, arg_type=get_enum_type(['Overwrite', 'Skip']), options_list=['--resolve-conflict'])
resource_id_type = CLIArgumentType(help=resource_id_help, options_list=['--resource-id'])
policy_type = CLIArgumentType(help=policy_help, options_list=['--policy'], completer=FilesCompleter(), type=file_type)
protectable_item_type = CLIArgumentType(help=workload_type_help, options_list=['--protectable-item-type'], arg_type=get_enum_type(allowed_protectable_item_type))
target_server_type = CLIArgumentType(help=target_server_type_help, options_list=['--target-server-type'], arg_type=get_enum_type(allowed_protectable_item_type))
protectable_item_name_type = CLIArgumentType(help=protectable_item_name_type_help, options_list=['--protectable-item-name'])
diskslist_type = CLIArgumentType(nargs='+', help=diskslist_help)
target_container_name_type = CLIArgumentType(options_list=['--target-container-name'], help=target_container_name_help)
filepath_type = CLIArgumentType(options_list=['--filepath'], help="The path to which the DB should be restored as files.")
from_full_rp_type = CLIArgumentType(options_list=['--from-full-rp-name'], help="Name of the starting Recovery point.")


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

    with self.argument_context('backup') as c:
        c.argument('force', action='store_true', help='Force completion of the requested action.')
Beispiel #18
0
 def _load_transformed_arguments(self, handler):
     """Load all the command line arguments from the request parameters.
     :param func handler: The operation function.
     """
     from azure.cli.core.commands.parameters import file_type
     from argcomplete.completers import FilesCompleter, DirectoriesCompleter
     self.parser = BatchArgumentTree(self.validator)
     self._load_options_model(handler)
     args = []
     for arg in extract_args_from_signature(
             handler, excluded_params=EXCLUDED_PARAMS):
         arg_type = find_param_type(handler, arg[0])
         if arg[0] == self._options_param:
             for option_arg in self._process_options():
                 args.append(option_arg)
         elif arg_type.startswith("str or"):
             docstring = find_param_help(handler, arg[0])
             choices = []
             values_index = docstring.find(' Possible values include')
             if values_index >= 0:
                 choices = docstring[values_index + 25:].split(', ')
                 choices = [
                     enum_value(c) for c in choices
                     if enum_value(c) != "'unmapped'"
                 ]
                 docstring = docstring[0:values_index]
             args.append(
                 ((arg[0],
                   CLICommandArgument(arg[0],
                                      options_list=[arg_name(arg[0])],
                                      required=False,
                                      default=None,
                                      choices=choices,
                                      help=docstring))))
         elif arg_type.startswith(
                 "~"):  # TODO: could add handling for enums
             param_type = class_name(arg_type)
             self.parser.set_request_param(arg[0], param_type)
             param_model = _load_model(param_type)
             self._flatten_object(arg[0], param_model)
             for flattened_arg in self.parser.compile_args():
                 args.append(flattened_arg)
             param = 'json_file'
             docstring = "A file containing the {} specification in JSON " \
                         "(formatted to match the respective REST API body). " \
                         "If this parameter is specified, all '{} Arguments'" \
                         " are ignored.".format(arg[0].replace('_', ' '), group_title(arg[0]))
             args.append((param,
                          CLICommandArgument(param,
                                             options_list=[arg_name(param)],
                                             required=False,
                                             default=None,
                                             type=file_type,
                                             completer=FilesCompleter(),
                                             help=docstring)))
         elif arg[0] not in pformat.IGNORE_PARAMETERS:
             args.append(arg)
     return_type = find_return_type(handler)
     if return_type and return_type.startswith('Generator'):
         param = 'destination'
         docstring = "The path to the destination file or directory."
         args.append((param,
                      CLICommandArgument(
                          param,
                          options_list=[arg_name(param)],
                          required=True,
                          default=None,
                          completer=DirectoriesCompleter(),
                          type=file_type,
                          validator=validators.validate_file_destination,
                          help=docstring)))
     if return_type == 'None' and handler.__name__.startswith('get'):
         self._head_cmd = True
     if self.confirmation:
         param = CONFIRM_PARAM_NAME
         docstring = 'Do not prompt for confirmation.'
         args.append((param,
                      CLICommandArgument(param,
                                         options_list=['--yes', '-y'],
                                         required=False,
                                         action='store_true',
                                         help=docstring)))
     auth_group_name = 'Batch Account'
     args.append(('cmd', CLICommandArgument('cmd', action=IgnoreAction)))
     args.append((
         'account_name',
         CLICommandArgument(
             'account_name',
             options_list=['--account-name'],
             required=False,
             default=None,
             validator=validators.validate_client_parameters,
             arg_group=auth_group_name,
             help=
             'Batch account name. Alternatively, set by environment variable: AZURE_BATCH_ACCOUNT'
         )))
     args.append((
         'account_key',
         CLICommandArgument(
             'account_key',
             options_list=['--account-key'],
             required=False,
             default=None,
             arg_group=auth_group_name,
             help=
             'Batch account key. Alternatively, set by environment variable: AZURE_BATCH_ACCESS_KEY'
         )))
     args.append((
         'account_endpoint',
         CLICommandArgument(
             'account_endpoint',
             options_list=['--account-endpoint'],
             required=False,
             default=None,
             arg_group=auth_group_name,
             help=
             'Batch service endpoint. Alternatively, set by environment variable: AZURE_BATCH_ENDPOINT'
         )))
     return args
def load_arguments(self, _):

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

    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'],
                   help='Https proxy URL to be used.')
        c.argument('http_proxy',
                   options_list=['--proxy-http'],
                   help='Http proxy URL to be used.')
        c.argument(
            'no_proxy',
            options_list=['--proxy-skip-range'],
            help='List of URLs/CIDRs for which proxy should not to be used.')
        c.argument('proxy_cert',
                   options_list=['--proxy-cert'],
                   type=file_type,
                   completer=FilesCompleter(),
                   help='Path to the certificate file for proxy')

    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'],
                   help='Https proxy URL to be used.')
        c.argument('http_proxy',
                   options_list=['--proxy-http'],
                   help='Http proxy URL to be used.')
        c.argument(
            'no_proxy',
            options_list=['--proxy-skip-range'],
            help='List of URLs/CIDRs for which proxy should not to be used.')
        c.argument('proxy_cert',
                   options_list=['--proxy-cert'],
                   type=file_type,
                   completer=FilesCompleter(),
                   help='Path to the certificate file for proxy')

    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.')
Beispiel #20
0
def load_arguments(self, _):  # pylint: disable=too-many-statements
    SkuName, PasswordName, DefaultAction, PolicyStatus, WebhookAction, WebhookStatus, TaskStatus, \
        BaseImageTriggerType, RunStatus, SourceRegistryLoginMode, UpdateTriggerPayloadType, TokenStatus = self.get_models(
            'SkuName', 'PasswordName', 'DefaultAction', 'PolicyStatus', 'WebhookAction', 'WebhookStatus',
            'TaskStatus', 'BaseImageTriggerType', 'RunStatus', 'SourceRegistryLoginMode', 'UpdateTriggerPayloadType',
            'TokenStatus')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    for scope in ['acr replication create', 'acr replication update']:
        help_str = "Allow routing to this replication. Requests will not be routed to a disabled replication." \
                   " Data syncing will continue regardless of the region endpoint status."
        help_str += ' Default: true.' if 'create' in scope else ''  # suffix help with default if command is for create

        with self.argument_context(scope) as c:
            c.argument('region_endpoint_enabled',
                       arg_type=get_three_state_flag(),
                       help=help_str,
                       is_preview=True)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with self.argument_context('acr encryption') as c:
        c.argument('key_encryption_key', help="key vault key uri")
        c.argument(
            'identity',
            help=
            "client id of managed identity, resource name or id of user assigned identity. Use '[system]' to refer to the system assigned identity"
        )
Beispiel #21
0
    register_cli_argument('storage blob copy', '{}_if_modified_since'.format(source), arg_group='Pre-condition')
    register_cli_argument('storage blob copy', '{}_if_unmodified_since'.format(source), arg_group='Pre-condition')
    register_cli_argument('storage blob copy', '{}_if_match'.format(source), arg_group='Pre-condition')
    register_cli_argument('storage blob copy', '{}_if_none_match'.format(source), arg_group='Pre-condition')
register_cli_argument('storage blob copy', 'container_name', container_name_type, options_list=('--destination-container', '-c'))
register_cli_argument('storage blob copy', 'blob_name', blob_name_type, options_list=('--destination-blob', '-b'), help='Name of the destination blob. If the exists, it will be overwritten.')
register_cli_argument('storage blob copy', 'source_lease_id', arg_group='Copy Source')

register_cli_argument('storage blob delete', 'delete_snapshots', choices=list(delete_snapshot_types.keys()), type=str.lower)

register_cli_argument('storage blob exists', 'blob_name', required=True)

register_cli_argument('storage blob list', 'include', help='Specifies additional datasets to include: (c)opy-info, (m)etadata, (s)napshots. Can be combined.', validator=validate_included_datasets)

for item in ['download', 'upload']:
    register_cli_argument('storage blob {}'.format(item), 'file_path', options_list=('--file', '-f'), completer=FilesCompleter())
    register_cli_argument('storage blob {}'.format(item), 'max_connections', type=int)
    register_cli_argument('storage blob {}'.format(item), 'validate_content', action='store_true')

for item in ['update', 'upload']:
    register_content_settings_argument('storage blob {}'.format(item), BlobContentSettings, item == 'update')

register_cli_argument('storage blob upload', 'blob_type', help="Defaults to 'page' for *.vhd files, or 'block' otherwise.", options_list=('--type', '-t'), choices=list(blob_types.keys()), type=str.lower, validator=validate_blob_type)
register_cli_argument('storage blob upload', 'maxsize_condition', help='The max length in bytes permitted for an append blob.')
register_cli_argument('storage blob upload', 'validate_content', help='Specifies that an MD5 hash shall be calculated for each chunk of the blob and verified by the service when the chunk has arrived.')

for item in ['file', 'blob']:
    register_cli_argument('storage {} url'.format(item), 'protocol', help='Protocol to use.', choices=['http', 'https'], default='https', type=str.lower)
    register_source_uri_arguments('storage {} copy start'.format(item))

register_cli_argument('storage container', 'container_name', container_name_type, options_list=('--name', '-n'))
Beispiel #22
0
                          type=str.lower)
    register_cli_argument('keyvault key {}'.format(item), 'disabled', action='store_true',
                          help='Create key in disabled state.')
    register_cli_argument('keyvault key {}'.format(item), 'key_size', options_list=('--size',),
                          type=int)
    register_cli_argument('keyvault key {}'.format(item), 'expires', default=None,
                          help='Expiration UTC datetime  (Y-m-d\'T\'H:M:S\'Z\').',
                          type=datetime_type)
    register_cli_argument('keyvault key {}'.format(item), 'not_before', default=None,
                          help='Key not usable before the provided UTC datetime  '
                               '(Y-m-d\'T\'H:M:S\'Z\').',
                          type=datetime_type)

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

register_cli_argument('keyvault key backup', 'file_path', options_list=('--file', '-f'),
                      type=file_type, completer=FilesCompleter(),
                      help='Local file path in which to store key backup.')

register_cli_argument('keyvault key restore', 'file_path', options_list=('--file', '-f'),
                      type=file_type, completer=FilesCompleter(),
                      help='Local key backup from which to restore key.')
Beispiel #23
0
def create_argparse_transcode(parser, subparsers):
    subparse = subparsers.add_parser(
        "t",  # aliases=("transcode",),
        help="Transcode a given file",
    )
    subparse.add_argument(
        dest="path",
        type=str,
        help="Path to file to transcode",
    ).completer = FilesCompleter(directories=False)
    subparse.add_argument('assetname',
                          help='The subname of the asset to transcoder'
                          ).completer = assetname_completer
    subparse.add_argument(
        'mimetype',
        help='The destination mimetype').completer = target_mimetype_completer
    subparse.add_argument(
        "-fd",
        "--file-description",
        dest="fd",
        type=str,
        help="Path to the cached FileDescription",
    ).completer = FilesCompleter(directories=False)
    subparse.add_argument(
        "-o",
        "--output",
        dest="output",
        type=str,
        help="The output directory to write the transcoded files to",
    ).completer = FilesCompleter(['ignore'])

    try:
        args, options_args = parser.parse_known_args()
        #TODO
        if args.assetname and args.mimetype:
            from .transcoder import Transcoder
            t = Transcoder('/tmp/transcoded/')
            asset_subname, asset_mimetype = split_assetname(args.assetname)
            target_mimetype = t.get_target_mimetype(asset_mimetype,
                                                    args.mimetype)
            for option in target_mimetype.options:
                subparse.add_argument("--" + option.name,
                                      dest=option.name,
                                      default=option.default_value,
                                      help='%s (%s) [default: %s] (%s)' %
                                      (option.description, option.constraint,
                                       option.default_value, option.type))
    except:
        pass

    def transcode(args):
        LOG.info('Transcoding...')
        from .transcoder import Transcoder
        t = Transcoder('/tmp/transcoded/')
        asset_subname, asset_mimetype = split_assetname(args.assetname)
        target_mimetype = t.get_target_mimetype(asset_mimetype, args.mimetype)
        if target_mimetype is None:
            parser.print_help()
        # TODO
        LOG.info("Options:\n%s" % "\n".join(map(str, target_mimetype.options)))

        options = t.parse_options(asset_mimetype, target_mimetype,
                                  **vars(args))

        if not args.fd:
            from .analyzer import Analyzer
            analyzer = Analyzer()
            descr = analyzer.analyze_file(args.path)

        from .utilities import find_asset_id_in_file_descr
        asset_id = find_asset_id_in_file_descr(descr, asset_subname,
                                               asset_mimetype)
        if asset_id is None:
            parser.print_help()
        print((t.transcode(descr, asset_id, target_mimetype, **options)))

    subparse.set_defaults(func=lambda args: transcode(args), )
Beispiel #24
0
def load_arguments(self, _):
    from argcomplete.completers import FilesCompleter

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

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

    from knack.arguments import ignore_type, CLIArgumentType

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

    # BASIC PARAMETER CONFIGURATION

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    acr_arg_type = CLIArgumentType(metavar='ACR_NAME_OR_RESOURCE_ID')

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

    with self.argument_context('aks create') as c:
        c.argument('name', validator=validate_linux_host_name)
        c.argument('kubernetes_version',
                   completer=get_k8s_versions_completion_list)
        c.argument('admin_username',
                   options_list=['--admin-username', '-u'],
                   default='azureuser')
        c.argument('windows_admin_username',
                   options_list=['--windows-admin-username'])
        c.argument('windows_admin_password',
                   options_list=['--windows-admin-password'])
        c.argument('dns_name_prefix', options_list=['--dns-name-prefix', '-p'])
        c.argument('generate_ssh_keys',
                   action='store_true',
                   validator=validate_create_parameters)
        c.argument('node_vm_size',
                   options_list=['--node-vm-size', '-s'],
                   completer=get_vm_size_completion_list)
        c.argument('nodepool_name',
                   type=str,
                   default='nodepool1',
                   help='Node pool name, upto 12 alphanumeric characters',
                   validator=validate_nodepool_name)
        c.argument('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('enable_addons', options_list=['--enable-addons', '-a'])
        c.argument('disable_rbac', action='store_true')
        c.argument('enable_rbac',
                   action='store_true',
                   options_list=['--enable-rbac', '-r'],
                   deprecate_info=c.deprecate(redirect="--disable-rbac",
                                              hide="2.0.45"))
        c.argument('max_pods',
                   type=int,
                   options_list=['--max-pods', '-m'],
                   validator=validate_max_pods)
        c.argument('network_plugin')
        c.argument('network_policy')
        c.argument('no_ssh_key', options_list=['--no-ssh-key', '-x'])
        c.argument('pod_cidr')
        c.argument('service_cidr')
        c.argument('vnet_subnet_id')
        c.argument('workspace_resource_id')
        c.argument('skip_subnet_role_assignment', action='store_true')
        c.argument('enable_cluster_autoscaler', action='store_true')
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('enable_vmss',
                   action='store_true',
                   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',
            help=
            '(PREVIEW) Space-separated list of availability zones where agent nodes will be placed.'
        )
        c.argument('enable_pod_security_policy', action='store_true')
        c.argument('node_resource_group')
        c.argument('attach_acr', acr_arg_type)
        c.argument('enable_private_cluster', action='store_true')
        c.argument('enable_managed_identity', action='store_true')

    with self.argument_context('aks update') as c:
        c.argument('enable_cluster_autoscaler',
                   options_list=["--enable-cluster-autoscaler", "-e"],
                   action='store_true')
        c.argument('disable_cluster_autoscaler',
                   options_list=["--disable-cluster-autoscaler", "-d"],
                   action='store_true')
        c.argument('update_cluster_autoscaler',
                   options_list=["--update-cluster-autoscaler", "-u"],
                   action='store_true')
        c.argument('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('api_server_authorized_ip_ranges',
                   type=str,
                   validator=validate_ip_ranges)
        c.argument('enable_pod_security_policy', action='store_true')
        c.argument('disable_pod_security_policy', action='store_true')
        c.argument('attach_acr', acr_arg_type)
        c.argument('detach_acr', acr_arg_type)

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

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

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

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

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

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

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

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

    with self.argument_context('aks get-credentials') as c:
        c.argument('admin', options_list=['--admin', '-a'], default=False)
        c.argument('path',
                   options_list=['--file', '-f'],
                   type=file_type,
                   completer=FilesCompleter(),
                   default=os.path.join(os.path.expanduser('~'), '.kube',
                                        'config'))
Beispiel #26
0
def load_arguments(self, _):
    from ._completers import subnet_completion_list, cluster_admin_account_completion_list, \
        cluster_user_group_completion_list, get_resource_name_completion_list_under_subscription
    from knack.arguments import CLIArgumentType
    from azure.mgmt.hdinsight.models import Tier, JsonWebKeyEncryptionAlgorithm, ResourceProviderConnection
    from argcomplete.completers import FilesCompleter
    node_size_type = CLIArgumentType(arg_group='Node',
                                     help='The size of the node. See also: https://docs.microsoft.com/azure/'
                                          'hdinsight/hdinsight-hadoop-provision-linux-clusters#configure-cluster-size')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        with self.argument_context('hdinsight autoscale condition delete') as c:
            c.argument('index', nargs='+', type=int,
                       help='The Space-separated list of condition indices which starts with 0 to delete.')
def load_arguments(self, _):

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

    with self.argument_context('aks create') as c:
        c.argument('name', validator=validate_linux_host_name)
        c.argument('kubernetes_version',
                   completer=get_k8s_versions_completion_list)
        c.argument('admin_username',
                   options_list=['--admin-username', '-u'],
                   default='azureuser')
        c.argument('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)
        c.argument('aad_client_app_id')
        c.argument('aad_server_app_id')
        c.argument('aad_server_app_secret')
        c.argument('aad_tenant_id')
        c.argument('dns_service_ip')
        c.argument('docker_bridge_address')
        c.argument('enable_addons', options_list=['--enable-addons', '-a'])
        c.argument('disable_rbac', action='store_true')
        c.argument('enable_rbac',
                   action='store_true',
                   options_list=['--enable-rbac', '-r'],
                   deprecate_info=c.deprecate(redirect="--disable-rbac",
                                              hide="2.0.45"))
        c.argument('max_pods',
                   type=int,
                   options_list=['--max-pods', '-m'],
                   validator=validate_max_pods)
        c.argument('network_plugin')
        c.argument('no_ssh_key', options_list=['--no-ssh-key', '-x'])
        c.argument('pod_cidr')
        c.argument('service_cidr')
        c.argument('vnet_subnet_id')
        c.argument('workspace_resource_id')
        c.argument('skip_subnet_role_assignment', action='store_true')
        c.argument('enable_cluster_autoscaler', action='store_true')
        c.argument('min_count', type=int, validator=validate_nodes_count)
        c.argument('max_count', type=int, validator=validate_nodes_count)
        c.argument('enable_vmss', action='store_true')

    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)

    with self.argument_context('aks upgrade') as c:
        c.argument('kubernetes_version',
                   completer=get_k8s_upgrades_completion_list)
from argcomplete.completers import FilesCompleter

from ._validators import blueprint_validator, blueprint_assignment_validator

from .vendored_sdks.blueprint.models._blueprint_management_client_enums import (
    BlueprintTargetScope,
    ManagedServiceIdentityType,
    AssignmentLockMode
)


parameter_type = CLIArgumentType(
    type=validate_file_or_dict,
    options_list=['--parameters', '-p'],
    help='Parameters in JSON string or path to JSON file.',
    completer=FilesCompleter()
)

template_type = CLIArgumentType(
    type=validate_file_or_dict,
    options_list=['--template', '-t'],
    help='ARM template in JSON string or path to JSON file.',
    completer=FilesCompleter()
)

subscription_type = CLIArgumentType(
    arg_group='Scope',
    options_list=['--subscription', '-s'],
    help='Use subscription for the scope of the blueprint. If --management-group is not specified, --subscription value or the default subscription will be used as the scope.'
)
Beispiel #29
0
def load_arguments(self, _):
    from knack.arguments import CLIArgumentType
    from azure.mgmt.cosmosdb.models import KeyKind, DefaultConsistencyLevel, DatabaseAccountKind, TriggerType, TriggerOperation, ServerVersion

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

    with self.argument_context('cosmosdb create') as c:
        c.argument('account_name', completer=None)
        c.argument('key_uri', help="The URI of the key vault", is_preview=True)
        c.argument('enable_free_tier', arg_type=get_three_state_flag(), help="If enabled the account is free-tier.", is_preview=True)
        c.argument('server_version', arg_type=get_enum_type(ServerVersion), help="Valid only for MongoDB accounts.", is_preview=True)

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

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

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

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

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

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

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

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

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

    account_name_type = CLIArgumentType(options_list=['--account-name', '-a'], help="Cosmosdb account name.")
    database_name_type = CLIArgumentType(options_list=['--database-name', '-d'], help='Database name.')
    container_name_type = CLIArgumentType(options_list=['--container-name', '-c'], help='Container name.')
    max_throughput_type = CLIArgumentType(options_list=['--max-throughput'], help='The maximum throughput resource can scale to (RU/s). Provided when the resource is autoscale enabled. The minimum value can be 4000 (RU/s)')
    throughput_type = CLIArgumentType(options_list=['--throughput-type', '-t'], arg_type=get_enum_type(ThroughputTypes), help='The type of throughput to migrate to.')

    with self.argument_context('cosmosdb private-endpoint-connection') as c:
        c.argument('private_endpoint_connection_name', options_list=['--name', '-n'], required=False,
                   help='The name of the private endpoint connection associated with Azure Cosmos DB. '
                        'Required if --connection-id is not specified')
        c.argument('account_name', account_name_type, required=False,
                   help='Name of the Cosmos DB database account. Required if --connection-id is not specified')
        c.argument('resource_group_name', required=False,
                   help='The resource group name of specified Cosmos DB account. Required if --connection-id is not specified')

    for item in ['approve', 'reject', 'delete', 'show']:
        with self.argument_context('cosmosdb private-endpoint-connection {}'.format(item)) as c:
            c.extra('connection_id', options_list=['--id'], required=False,
                    help='The ID of the private endpoint connection associated with Azure Cosmos DB. '
                         'If specified --account-name --resource-group/-g and --name/-n, this should be omitted.')
            c.argument('description', options_list=['--description'], required=False, help='Comments for the {} operation.'.format(item))

    with self.argument_context('cosmosdb private-link-resource') as c:
        c.argument('account_name', account_name_type, required=True, help="Cosmosdb account name", id_part=None)

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

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

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

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

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

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

    with self.argument_context('cosmosdb mongodb collection') as c:
        c.argument('account_name', account_name_type, id_part=None)
        c.argument('database_name', database_name_type)
        c.argument('collection_name', options_list=['--name', '-n'], help="Collection name")
        c.argument('shard_key_path', options_list=['--shard'], help="Sharding key path.")
        c.argument('indexes', options_list=['--idx'], type=shell_safe_json_parse, completer=FilesCompleter(), help='Indexes, you can enter it as a string or as a file, e.g., --idx @indexes-file.json or ' + MONGODB_INDEXES_EXAMPLE)
        c.argument('max_throughput', max_throughput_type)
        c.argument('analytical_storage_ttl', type=int, help='Analytical TTL, when analytical storage is enabled.')
        c.argument('throughput', help='The throughput of MongoDB collection (RU/s). Default value is 400. Omit this parameter if the database has shared throughput unless the collection should have dedicated throughput.')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    for scope in ['sql database throughput migrate', 'sql container throughput migrate',
                  'gremlin database throughput migrate', 'gremlin graph throughput migrate',
                  'cassandra table throughput migrate', 'cassandra keyspace throughput migrate',
                  'mongodb collection throughput migrate', 'mongodb database throughput migrate',
                  'table throughput migrate']:
        with self.argument_context('cosmosdb {}'.format(scope)) as c:
            c.argument('throughput_type', throughput_type)
Beispiel #30
0
register_cli_argument('provider', 'top', ignore_type)
register_cli_argument('provider', 'resource_provider_namespace', options_list=('--namespace', '-n'), completer=get_providers_completion_list,
                      help=_PROVIDER_HELP_TEXT)
register_cli_argument('provider operation', 'api_version', help="The api version of the 'Microsoft.Authorization/providerOperations' resource (omit for latest)")


register_cli_argument('feature', 'resource_provider_namespace', options_list=('--namespace',), required=True, help=_PROVIDER_HELP_TEXT)
register_cli_argument('feature list', 'resource_provider_namespace', options_list=('--namespace',), required=False, help=_PROVIDER_HELP_TEXT)
register_cli_argument('feature', 'feature_name', options_list=('--name', '-n'), help='the feature name')

existing_policy_definition_name_type = CliArgumentType(options_list=('--name', '-n'), completer=get_policy_completion_list, help='The policy definition name')
register_cli_argument('policy', 'resource_group_name', arg_type=resource_group_name_type, help='the resource group where the policy will be applied')
register_cli_argument('policy definition', 'policy_definition_name', arg_type=existing_policy_definition_name_type)
register_cli_argument('policy definition create', 'name', options_list=('--name', '-n'), help='name of the new policy definition')
register_cli_argument('policy definition', 'rules', help='JSON formatted string or a path to a file with such content', type=file_type, completer=FilesCompleter())
register_cli_argument('policy definition', 'display_name', help='display name of policy definition')
register_cli_argument('policy definition', 'description', help='description of policy definition')
register_cli_argument('policy assignment', 'name', options_list=('--name', '-n'), completer=get_policy_assignment_completion_list, help='name of the assignment')
register_cli_argument('policy assignment create', 'name', options_list=('--name', '-n'), help='name of the new assignment')
register_cli_argument('policy assignment', 'scope', help='scope at which this policy assignment applies to, e.g., /subscriptions/0b1f6471-1bf0-4dda-aec3-111122223333, /subscriptions/0b1f6471-1bf0-4dda-aec3-111122223333/resourceGroups/myGroup, or /subscriptions/0b1f6471-1bf0-4dda-aec3-111122223333/resourceGroups/myGroup/providers/Microsoft.Compute/virtualMachines/myVM')
register_cli_argument('policy assignment', 'disable_scope_strict_match', action='store_true', help='include assignment either inhertied from parent scope or at child scope')
register_cli_argument('policy assignment', 'display_name', help='display name of the assignment')
register_cli_argument('policy assignment', 'policy', help='policy name or fully qualified id', completer=get_policy_completion_list)

register_cli_argument('group', 'tag', tag_type)
register_cli_argument('group', 'tags', tags_type)
register_cli_argument('group', 'resource_group_name', resource_group_name_type, options_list=('--name', '-n'))
register_cli_argument('group deployment', 'resource_group_name', arg_type=resource_group_name_type, completer=get_resource_group_completion_list)
register_cli_argument('group deployment', 'deployment_name', options_list=('--name', '-n'), required=True, help='The deployment name.')
register_cli_argument('group deployment', 'parameters', action='append', completer=FilesCompleter(), help="provide deployment parameter values, either json string, or use `@<file path>` to load from a file. Can be repeated. If a the same parameter is present in multiple arguments, the last value wins.")