def test_generic_update_errors(self):
        my_obj = {
            'prop': 'val',
            'list': [
                'a',
                'b',
                ['c', {'d': 'e'}]
                ]
            }

        def my_get(a1, a2): #pylint: disable=unused-argument
            return my_obj

        def my_set(**kwargs): #pylint:disable=unused-argument
            return my_obj

        config = Configuration([])
        app = Application(config)

        register_generic_update('gencommand', my_get, my_set)

        def _execute_with_error(command, error, message):
            try:
                app.execute(command.split())
            except CLIError as err:
                self.assertEqual(error in str(err), True, message)
            else:
                raise AssertionError('exception not thrown')

        missing_remove_message = """Couldn't find "doesntExist" in "".""" + \
                                 """  Available options: ['list', 'prop']"""
        _execute_with_error('gencommand --a1 1 --a2 2 --remove doesnt_exist',
                            missing_remove_message,
                            'remove non-existent property by name')
        _execute_with_error('gencommand --a1 1 --a2 2 --remove doesntExist 2',
                            missing_remove_message,
                            'remove non-existent property by index')

        remove_prop_message = """Couldn't find "doesntExist" in "list.doesntExist".""" + \
                              """  Available options: [['c', {'d': 'e'}], 'a', 'b']"""
        _execute_with_error('gencommand --a1 1 --a2 2 --remove list.doesnt_exist.missing 2',
                            remove_prop_message,
                            'remove non-existent sub-property by index')

        _execute_with_error('gencommand --a1 1 --a2 2 --remove list 20',
                            "index 20 doesn't exist on list",
                            'remove out-of-range index')

        set_on_list_message = """Couldn't find "doesntExist" in "list".""" + \
                              """  Available options: [['c', {'d': 'e'}], 'a', 'b']"""
        _execute_with_error('gencommand --a1 1 --a2 2 --set list.doesnt_exist=foo',
                            set_on_list_message,
                            'set shouldn\'t work on a list')
        _execute_with_error('gencommand --a1 1 --a2 2 --set list.doesnt_exist.doesnt_exist2=foo',
                            set_on_list_message,
                            'set shouldn\'t work on a list')

        _execute_with_error('gencommand --a1 1 --a2 2 --set list[2][3].doesnt_exist=foo',
                            "index 3 doesn't exist on [2]",
                            'index out of range in path')
    def test_generic_update_ids(self):
        my_objs = [
            {
                'prop': 'val',
                'list': [
                    'a',
                    'b',
                    ['c', {'d': 'e'}]
                    ]
            },
            {
                'prop': 'val',
                'list': [
                    'a',
                    'b',
                    ['c', {'d': 'e'}]
                    ]
            }]

        def my_get(name, resource_group): #pylint:disable=unused-argument
            # name is None when tests are run in a batch on Python <=2.7.9
            if sys.version_info < (2, 7, 10):
                return my_objs[0]
            return my_objs[int(name)]

        def my_set(**kwargs): #pylint:disable=unused-argument
            return my_objs

        register_cli_argument('gencommand', 'name', CliArgumentType(options_list=('--name', '-n'),
                                                                    metavar='NAME', id_part='name'))
        register_generic_update('gencommand', my_get, my_set)

        config = Configuration([])
        APPLICATION.initialize(config)

        id_str = ('/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/rg/'
                  'providers/Microsoft.Compute/virtualMachines/')

        APPLICATION.execute('gencommand --ids {0}0 {0}1 --resource-group bar --set prop=newval'
                            .format(id_str).split())
        self.assertEqual(my_objs[0]['prop'], 'newval', 'first object updated')
        # name is None when tests are run in a batch on Python <=2.7.9
        if not sys.version_info < (2, 7, 10):
            self.assertEqual(my_objs[1]['prop'], 'newval', 'second object updated')
    def test_generic_update_empty_nodes(self):
        my_obj = {
            'prop': None,
            'list': [],
            'dict': {
                'dict2': None
                },
            'dict3': {}
            }

        def my_get():
            return my_obj

        def my_set(**kwargs): #pylint:disable=unused-argument
            return my_obj

        config = Configuration([])
        app = Application(config)

        register_generic_update('gencommand', my_get, my_set)

        # add to prop
        app.execute('gencommand --add prop a=b'.split())
        self.assertEqual(my_obj['prop'][0]['a'], 'b', 'verify object added to null list')
        self.assertEqual(len(my_obj['prop'][0]), 1, 'verify only one object added to null list')

        #add to list
        app.execute('gencommand --add list c=d'.split())
        self.assertEqual(my_obj['list'][0]['c'], 'd', 'verify object added to empty list')
        self.assertEqual(len(my_obj['list']), 1, 'verify only one object added to empty list')

        # set dict2
        app.execute('gencommand --set dict.dict2.e=f'.split())
        self.assertEqual(my_obj['dict']['dict2']['e'], 'f', 'verify object added to null dict')
        self.assertEqual(len(my_obj['dict']['dict2']), 1,
                         'verify only one object added to null dict')

        #set dict3
        app.execute('gencommand --set dict3.g=h'.split())
        self.assertEqual(my_obj['dict3']['g'], 'h', 'verify object added to empty dict')
        self.assertEqual(len(my_obj['dict3']), 1, 'verify only one object added to empty dict')
Пример #4
0
cli_command('vm start', VirtualMachinesOperations.start, factory)
cli_command('vm redeploy', VirtualMachinesOperations.redeploy, factory)
cli_command('vm list-ip-addresses', list_ip_addresses)
cli_command(
    'vm list',
    list_vm,
    simple_output_query=
    "[*].{Name: name, ResourceGroup: resourceGroup, Location: location, VmSize: hardwareProfile.vmSize, Urn: join(':', [storageProfile.imageReference.publisher, storageProfile.imageReference.offer, storageProfile.imageReference.sku, storageProfile.imageReference.version])} | sort_by(@, &Name)"
)
cli_command('vm resize', resize_vm)
cli_command('vm capture', capture_vm)
cli_command('vm nic add', vm_add_nics)
cli_command('vm nic delete', vm_delete_nics)
cli_command('vm nic update', vm_update_nics)
cli_command('vm open-port', vm_open_port)
register_generic_update('vm update', VirtualMachinesOperations.get,
                        VirtualMachinesOperations.create_or_update, factory)

# VM Access
cli_command('vm access set-linux-user', set_linux_user)
cli_command('vm access delete-linux-user', delete_linux_user)
cli_command('vm access reset-windows-admin', reset_windows_admin)

# VM Availability Set
factory = lambda _: get_mgmt_service_client(AvailSetClient).avail_set
cli_command('vm availability-set create', AvailSetOperations.create_or_update,
            factory)

factory = lambda _: _compute_client_factory().availability_sets
cli_command('vm availability-set delete', AvailabilitySetsOperations.delete,
            factory)
cli_command('vm availability-set show', AvailabilitySetsOperations.get,
    def test_generic_update(self):
        my_obj = {
            'prop': 'val',
            'list': [
                'a',
                'b',
                ['c', {'d': 'e'}]
                ]
            }

        def my_get():
            return my_obj

        def my_set(**kwargs): #pylint:disable=unused-argument
            return my_obj

        config = Configuration([])
        app = Application(config)

        register_generic_update('gencommand', my_get, my_set)

        app.execute('gencommand --set prop=val2'.split())
        self.assertEqual(my_obj['prop'], 'val2', 'set simple property')

        app.execute('gencommand --set prop=val3'.split())
        self.assertEqual(my_obj['prop'], 'val3', 'set simple property again')

        app.execute('gencommand --set list[0]=f'.split())
        self.assertEqual(my_obj['list'][0], 'f', 'set simple list element')

        app.execute('gencommand --set list[2][0]=g'.split())
        self.assertEqual(my_obj['list'][2][0], 'g', 'set nested list element')

        app.execute('gencommand --set list[2][1].d=h'.split())
        self.assertEqual(my_obj['list'][2][1]['d'], 'h', 'set nested dict element')

        app.execute('gencommand --set list[0]={} list[0].foo=bar'.split())
        self.assertEqual(my_obj['list'][0]['foo'], 'bar', 'replace nested scalar with new dict')

        app.execute('gencommand --set list[1]=[] --add list[1] key1=value1'
                    ' --set list[1][0].key2=value2'.split())
        self.assertEqual(my_obj['list'][1][0]['key1'], 'value1',
                         'replace nested scalar with new list with one value')
        self.assertEqual(my_obj['list'][1][0]['key2'], 'value2',
                         'add a second value to the new list')

        app.execute('gencommand --add list i=j k=l'.split())
        self.assertEqual(my_obj['list'][-1]['k'], 'l',
                         'add multiple values to a list at once (verify last element)')
        self.assertEqual(my_obj['list'][-1]['i'], 'j',
                         'add multiple values to a list at once (verify first element)')

        app.execute('gencommand --add list[-2] prop2=val2'.split())
        self.assertEqual(my_obj['list'][-2][-1]['prop2'], 'val2', 'add to list')
        app.execute('gencommand --add list[-2] prop3=val3'.split())
        self.assertEqual(my_obj['list'][-2][-1]['prop3'], 'val3',
                         'add to list again, should make seperate list elements')

        self.assertEqual(len(my_obj['list']), 4, 'pre-verify length of list')
        app.execute('gencommand --remove list -2'.split())
        self.assertEqual(len(my_obj['list']), 3, 'verify one item removed')
        app.execute('gencommand --remove list -1'.split())
        self.assertEqual(len(my_obj['list']), 2, 'verify another item removed')

        self.assertEqual('key1' in my_obj['list'][1][0], True, 'verify dict item')
        app.execute('gencommand --remove list[1][0].key1'.split())
        self.assertEqual('key1' not in my_obj['list'][1][0], True,
                         'verify dict item can be removed')
Пример #6
0
     list_network_resource_property, get_network_resource_property_entry,
     delete_network_resource_property_entry,
     list_application_gateways, list_express_route_circuits, list_lbs, list_nics, list_nsgs,
     list_public_ips, list_route_tables, list_vnet
    )
from ._factory import _network_client_factory

# pylint: disable=line-too-long
# Application gateways
factory = lambda _: _network_client_factory().application_gateways
cli_command('network application-gateway delete', ApplicationGatewaysOperations.delete, factory)
cli_command('network application-gateway show', ApplicationGatewaysOperations.get, factory)
cli_command('network application-gateway list', list_application_gateways, simple_output_query="[*].{Name:name, ResourceGroup:resourceGroup, Location:location, State:provisioningState} | sort_by(@, &Name)")
cli_command('network application-gateway start', ApplicationGatewaysOperations.start, factory)
cli_command('network application-gateway stop', ApplicationGatewaysOperations.stop, factory)
register_generic_update('network application-gateway update', ApplicationGatewaysOperations.get, ApplicationGatewaysOperations.create_or_update, factory)

factory = lambda _: get_mgmt_service_client(AppGatewayClient).app_gateway
cli_command('network application-gateway create', AppGatewayOperations.create_or_update, factory, transform=DeploymentOutputLongRunningOperation('Starting network application-gateway create'))

property_map = {
    'ssl_certificates': 'ssl-cert',
    'frontend_ip_configurations': 'frontend-ip',
    'frontend_ports': 'frontend-port',
    'backend_address_pools': 'address-pool',
    'backend_http_settings_collection': 'http-settings',
    'http_listeners': 'http-listener',
    'request_routing_rules': 'rule',
    'probes': 'probe',
    'url_path_maps': 'url-path-map'
}
Пример #7
0
cli_command('vm generalize', VirtualMachinesOperations.generalize, factory)
cli_command('vm show', VirtualMachinesOperations.get, factory, simple_output_query="{Name:name, ResourceGroup:resourceGroup, Location:location, VmSize:hardwareProfile.vmSize, OsType: storageProfile.osDisk.osType, Urn: join(':', [storageProfile.imageReference.publisher, storageProfile.imageReference.offer, storageProfile.imageReference.sku, storageProfile.imageReference.version])}")
cli_command('vm list-vm-resize-options', VirtualMachinesOperations.list_available_sizes, factory)
cli_command('vm stop', VirtualMachinesOperations.power_off, factory)
cli_command('vm restart', VirtualMachinesOperations.restart, factory)
cli_command('vm start', VirtualMachinesOperations.start, factory)
cli_command('vm redeploy', VirtualMachinesOperations.redeploy, factory)
cli_command('vm list-ip-addresses', list_ip_addresses)
cli_command('vm list', list_vm, simple_output_query="[*].{Name: name, ResourceGroup: resourceGroup, Location: location, VmSize: hardwareProfile.vmSize, Urn: join(':', [storageProfile.imageReference.publisher, storageProfile.imageReference.offer, storageProfile.imageReference.sku, storageProfile.imageReference.version])} | sort_by(@, &Name)")
cli_command('vm resize', resize_vm)
cli_command('vm capture', capture_vm)
cli_command('vm nic add', vm_add_nics)
cli_command('vm nic delete', vm_delete_nics)
cli_command('vm nic update', vm_update_nics)
cli_command('vm open-port', vm_open_port)
register_generic_update('vm update', VirtualMachinesOperations.get, VirtualMachinesOperations.create_or_update, factory)

# VM Access
cli_command('vm access set-linux-user', set_linux_user)
cli_command('vm access delete-linux-user', delete_linux_user)
cli_command('vm access reset-windows-admin', reset_windows_admin)

# VM Availability Set
factory = lambda _: get_mgmt_service_client(AvailSetClient).avail_set
cli_command('vm availability-set create', AvailSetOperations.create_or_update, factory)

factory = lambda _: _compute_client_factory().availability_sets
cli_command('vm availability-set delete', AvailabilitySetsOperations.delete, factory)
cli_command('vm availability-set show', AvailabilitySetsOperations.get, factory)
cli_command('vm availability-set list', AvailabilitySetsOperations.list, factory)
cli_command('vm availability-set list-sizes', AvailabilitySetsOperations.list_available_sizes, factory)
Пример #8
0
factory = lambda args: _keyvault_client_factory(**args).vaults

keyvault_show_query = "{Name:name, ResourceGroup:resourceGroup, Location:location, "\
                      "SkuFamily:properties.sku.family, SkuName:properties.sku.name, "\
                      "VaultUri:properties.vaultUri}"

cli_command('keyvault create', create_keyvault, factory, simple_output_query=keyvault_show_query)
cli_command('keyvault list', list_keyvault, factory,
            simple_output_query="[*].{Name:name, ResourceGroup:resourceGroup, Location:location} |"\
            " sort_by(@, &Name)")
cli_command('keyvault show', VaultsOperations.get, factory, simple_output_query=keyvault_show_query)
cli_command('keyvault delete', VaultsOperations.delete, factory)

cli_command('keyvault set-policy', set_policy, factory, simple_output_query=keyvault_show_query)
cli_command('keyvault delete-policy', delete_policy, factory,
            simple_output_query=keyvault_show_query)

def keyvault_update_setter(client, resource_group_name, vault_name, parameters):
    from azure.mgmt.keyvault.models import VaultCreateOrUpdateParameters
    return client.create_or_update(resource_group_name=resource_group_name,
                                   vault_name=vault_name,
                                   parameters=VaultCreateOrUpdateParameters(
                                       location=parameters.location,
                                       properties=parameters.properties))

register_generic_update('keyvault update',
                        VaultsOperations.get,
                        keyvault_update_setter,
                        lambda: _keyvault_client_factory().vaults,
                        simple_output_query=keyvault_show_query)
Пример #9
0
from .custom import (create_role_assignment, list_role_assignments, delete_role_assignments,
                     list_role_definitions, delete_role_definition, create_role_definition,
                     list_sps, list_users, create_user, list_groups, list_apps,
                     create_application, update_application, delete_application, show_application,
                     create_service_principal, show_service_principal, delete_service_principal,
                     create_service_principal_for_rbac, reset_service_principal_credential,
                     _auth_client_factory, _graph_client_factory)

factory = lambda _: _auth_client_factory().role_definitions
simple_output_query = '[*].{Name:properties.roleName, Id:name, Type:properties.type}'
cli_command('role list', list_role_definitions, simple_output_query=simple_output_query)
cli_command('role delete', delete_role_definition)
cli_command('role create', create_role_definition, simple_output_query=simple_output_query)
register_generic_update('role update',
                        RoleDefinitionsOperations.get,
                        RoleDefinitionsOperations.create_or_update,
                        factory)

simple_output_query = '[*].{Name:name, PrincipalName:properties.principalName, Role:properties.roleDefinitionName, Scope:properties.scope}'
factory = lambda _: _auth_client_factory().role_assignments
cli_command('role assignment delete', delete_role_assignments)
cli_command('role assignment list', list_role_assignments,
            simple_output_query='[*].{Name:name, PrincipalName:properties.principalName, Role:properties.roleDefinitionName, Scope:properties.scope}')
cli_command('role assignment create', create_role_assignment,
            simple_output_query="{Name:name, PrincipalId:properties.principalId, Scope:properties.scope}")

factory = lambda _: _graph_client_factory().applications
#for table ouput, display the 1st identifier and replyurl, so all can fit in a row
single_app_table_query = '{DisplayName:displayName, IdentifierUri:identifierUris[0], ObjectId:objectId, ReplyUrl:replyUrls[0]}'
cli_command('ad app create', create_application, factory, simple_output_query=single_app_table_query)
cli_command('ad app delete', delete_application, factory)
Пример #10
0
from ._factory import _network_client_factory

# pylint: disable=line-too-long
# Application gateways
factory = lambda _: _network_client_factory().application_gateways
cli_command('network application-gateway delete',
            ApplicationGatewaysOperations.delete, factory)
cli_command('network application-gateway show',
            ApplicationGatewaysOperations.get, factory)
cli_command('network application-gateway list', list_application_gateways)
cli_command('network application-gateway start',
            ApplicationGatewaysOperations.start, factory)
cli_command('network application-gateway stop',
            ApplicationGatewaysOperations.stop, factory)
register_generic_update('network application-gateway update',
                        ApplicationGatewaysOperations.get,
                        ApplicationGatewaysOperations.create_or_update,
                        factory)

factory = lambda _: get_mgmt_service_client(AppGatewayClient).app_gateway
cli_command('network application-gateway create',
            AppGatewayOperations.create_or_update,
            factory,
            transform=DeploymentOutputLongRunningOperation(
                'Starting network application-gateway create'))

# ExpressRouteCircuitAuthorizationsOperations
factory = lambda _: _network_client_factory(
).express_route_circuit_authorizations
cli_command('network express-route circuit-auth delete',
            ExpressRouteCircuitAuthorizationsOperations.delete, factory)
cli_command('network express-route circuit-auth show',
Пример #11
0
factory = lambda _: _resource_client_factory().tags
cli_command('tag list', TagsOperations.list, factory)
cli_command('tag create', TagsOperations.create_or_update, factory)
cli_command('tag delete', TagsOperations.delete, factory)
cli_command('tag add-value', TagsOperations.create_or_update_value, factory)
cli_command('tag remove-value', TagsOperations.delete_value, factory)

# Resource group deployment commands
factory = lambda _: _resource_client_factory().deployments
cli_command('resource group deployment create', deploy_arm_template)
cli_command('resource group deployment list', DeploymentsOperations.list, factory)
cli_command('resource group deployment show', DeploymentsOperations.get, factory)
cli_command('resource group deployment validate', validate_arm_template)
cli_command('resource group deployment exists', DeploymentsOperations.check_existence, factory)
cli_command('resource group deployment export', export_deployment_as_template)

# Resource group deployment operations commands
factory = lambda _: _resource_client_factory().deployment_operations
cli_command('resource group deployment operation list', DeploymentOperationsOperations.list, factory)
cli_command('resource group deployment operation show', DeploymentOperationsOperations.get, factory)

register_generic_update('resource update',
                        ResourcesOperations.get,
                        ResourcesOperations.create_or_update,
                        lambda: _resource_client_factory().resources)

register_generic_update('resource group update',
                        ResourceGroupsOperations.get,
                        ResourceGroupsOperations.create_or_update,
                        lambda: _resource_client_factory().resource_groups)
Пример #12
0
from azure.graphrbac.operations import (ApplicationsOperations,
                                        ServicePrincipalsOperations,
                                        UsersOperations, GroupsOperations)
from azure.cli.commands import cli_command
from azure.cli.commands.arm import register_generic_update

from .custom import (create_role_assignment, list_sps, list_users, create_user,
                     list_groups, list_apps, _auth_client_factory,
                     _graph_client_factory)

factory = lambda _: _auth_client_factory().role_definitions
cli_command('role list', RoleDefinitionsOperations.list, factory)
cli_command('role delete', RoleDefinitionsOperations.delete, factory)
cli_command('role show', RoleDefinitionsOperations.get, factory)
cli_command('role show-by-id', RoleDefinitionsOperations.get_by_id, factory)
register_generic_update('role update', RoleDefinitionsOperations.get,
                        RoleDefinitionsOperations.create_or_update, factory)

factory = lambda _: _auth_client_factory().role_assignments
cli_command('role assignment delete', RoleAssignmentsOperations.delete,
            factory)
cli_command('role assignment delete-by-id',
            RoleAssignmentsOperations.delete_by_id, factory)
cli_command('role assignment show', RoleAssignmentsOperations.get, factory)
cli_command('role assignment show-by-id', RoleAssignmentsOperations.get_by_id,
            factory)
cli_command('role assignment list', RoleAssignmentsOperations.list, factory)
cli_command('role assignment list-for-resource',
            RoleAssignmentsOperations.list_for_resource, factory)
cli_command('role assignment list-for-resource-group',
            RoleAssignmentsOperations.list_for_resource_group, factory)
cli_command('role assignment list-for-scope',
Пример #13
0
                                                         vm_scale_set_name,
                                                         instance_ids=instance_ids)

def vmss_start(resource_group_name, vm_scale_set_name, instance_ids=None):
    '''start virtual machines in a virtual machine scale set.'''
    client = _compute_client_factory()
    if instance_ids and len(instance_ids) == 1:
        return client.virtual_machine_scale_set_vms.start(resource_group_name,
                                                          vm_scale_set_name,
                                                          instance_ids[0])
    else:
        return client.virtual_machine_scale_sets.start(resource_group_name,
                                                       vm_scale_set_name,
                                                       instance_ids=instance_ids)

def availset_get(resource_group_name, name):
    return _compute_client_factory().availability_sets.get(resource_group_name, name)

def availset_set(**kwargs):
    return _compute_client_factory().availability_sets.create_or_update(**kwargs)

register_generic_update('vm availability-set update', availset_get, availset_set)

def vmss_get(resource_group_name, name):
    return _compute_client_factory().virtual_machine_scale_sets.get(resource_group_name, name)

def vmss_set(**kwargs):
    return _compute_client_factory().virtual_machine_scale_sets.create_or_update(**kwargs)

register_generic_update('vmss update', vmss_get, vmss_set)
Пример #14
0
cli_command('tag delete', TagsOperations.delete, factory)
cli_command('tag add-value', TagsOperations.create_or_update_value, factory)
cli_command('tag remove-value', TagsOperations.delete_value, factory)

# Resource group deployment commands
factory = lambda _: _resource_client_factory().deployments
cli_command('resource group deployment create', deploy_arm_template)
cli_command('resource group deployment list', DeploymentsOperations.list,
            factory)
cli_command('resource group deployment show', DeploymentsOperations.get,
            factory)
cli_command('resource group deployment validate', validate_arm_template)
cli_command('resource group deployment exists',
            DeploymentsOperations.check_existence, factory)
cli_command('resource group deployment export', export_deployment_as_template)

# Resource group deployment operations commands
factory = lambda _: _resource_client_factory().deployment_operations
cli_command('resource group deployment operation list',
            DeploymentOperationsOperations.list, factory)
cli_command('resource group deployment operation show',
            DeploymentOperationsOperations.get, factory)

register_generic_update('resource update', ResourcesOperations.get,
                        ResourcesOperations.create_or_update,
                        lambda: _resource_client_factory().resources)

register_generic_update('resource group update', ResourceGroupsOperations.get,
                        ResourceGroupsOperations.create_or_update,
                        lambda: _resource_client_factory().resource_groups)