def validate_client_parameters(namespace): """ Retrieves storage connection parameters from environment variables and parses out connection string into account name and key """ n = namespace if not n.connection_string: n.connection_string = os.environ.get('AZURE_STORAGE_CONNECTION_STRING') # if connection string supplied or in environment variables, extract account key and name if n.connection_string: conn_dict = validate_key_value_pairs(n.connection_string) n.account_name = conn_dict['AccountName'] n.account_key = conn_dict['AccountKey'] # otherwise, simply try to retrieve the remaining variables from environment variables if not n.account_name: n.account_name = os.environ.get('AZURE_STORAGE_ACCOUNT') if not n.account_key: n.account_key = os.environ.get('AZURE_STORAGE_KEY') if not n.sas_token: n.sas_token = os.environ.get('AZURE_SAS_TOKEN') # if account name is specified but no key, attempt to query if n.account_name and not n.account_key: scf = get_mgmt_service_client(StorageManagementClient) acc_id = next((x for x in scf.storage_accounts.list() if x.name == n.account_name), None).id if acc_id: from azure.cli.commands.arm import parse_resource_id rg = parse_resource_id(acc_id)['resource_group'] n.account_key = \ scf.storage_accounts.list_keys(rg, n.account_name).keys[0].value #pylint: disable=no-member
def get_resources_in_resource_group(resource_group_name, resource_type=None): rcf = get_mgmt_service_client(ResourceManagementClient) filter_str = "resourceType eq '{}'".format( resource_type) if resource_type else None return list( rcf.resource_groups.list_resources(resource_group_name, filter=filter_str))
def resource_exists(resource_group, name, namespace, type, **_): # pylint: disable=redefined-builtin '''Checks if the given resource exists. ''' odata_filter = "resourceGroup eq '{}' and name eq '{}'" \ " and resourceType eq '{}/{}'".format(resource_group, name, namespace, type) client = get_mgmt_service_client(ResourceManagementClient).resources existing = len(list(client.list(filter=odata_filter))) == 1 return existing
def list_ip_addresses(resource_group_name=None, vm_name=None): ''' Get IP addresses from one or more Virtual Machines :param str resource_group_name:Name of resource group. :param str vm_name:Name of virtual machine. ''' from azure.mgmt.network import NetworkManagementClient # We start by getting NICs as they are the smack in the middle of all data that we # want to collect for a VM (as long as we don't need any info on the VM than what # is available in the Id, we don't need to make any calls to the compute RP) # # Since there is no guarantee that a NIC is in the same resource group as a given # Virtual Machine, we can't constrain the lookup to only a single group... network_client = get_mgmt_service_client(NetworkManagementClient) nics = network_client.network_interfaces.list_all() public_ip_addresses = network_client.public_ip_addresses.list_all() ip_address_lookup = {pip.id: pip for pip in list(public_ip_addresses)} result = [] for nic in [n for n in list(nics) if n.virtual_machine]: nic_resource_group, nic_vm_name = _parse_rg_name(nic.virtual_machine.id) # If provided, make sure that resource group name and vm name match the NIC we are # looking at before adding it to the result... if ((resource_group_name is None or resource_group_name.lower() == nic_resource_group.lower()) and #pylint: disable=line-too-long (vm_name is None or vm_name.lower() == nic_vm_name.lower())): network_info = { 'privateIpAddresses': [], 'publicIpAddresses': [] } for ip_configuration in nic.ip_configurations: network_info['privateIpAddresses'].append(ip_configuration.private_ip_address) if ip_configuration.public_ip_address: public_ip_address = ip_address_lookup[ip_configuration.public_ip_address.id] network_info['publicIpAddresses'].append({ 'id': public_ip_address.id, 'name': public_ip_address.name, 'ipAddress': public_ip_address.ip_address, 'ipAllocationMethod': public_ip_address.public_ip_allocation_method }) result.append({ 'virtualMachine': { 'resourceGroup': nic_resource_group, 'name': nic_vm_name, 'network': network_info } }) return result
def _find_default_storage_account(namespace): if not namespace.storage_account and not namespace.storage_account_type: from azure.mgmt.storage import StorageManagementClient from azure.cli.commands.client_factory import get_mgmt_service_client client = get_mgmt_service_client(StorageManagementClient).storage_accounts sku_tier = 'Premium' if 'Premium' in namespace.storage_type else 'Standard' account = next((a for a in client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier), None) if account: namespace.storage_account = account.name namespace.storage_account_type = 'existingName'
def _find_default_storage_account(namespace): if not namespace.storage_account and not namespace.storage_account_type: from azure.mgmt.storage import StorageManagementClient from azure.cli.commands.client_factory import get_mgmt_service_client client = get_mgmt_service_client( StorageManagementClient).storage_accounts sku_tier = 'Premium' if 'Premium' in namespace.storage_type else 'Standard' account = next((a for a in client.list_by_resource_group( namespace.resource_group_name) if a.sku.tier.value == sku_tier), None) if account: namespace.storage_account = account.name namespace.storage_account_type = 'existingName'
def _build_nic_list(resource_group_name, nic_ids, nic_names): from azure.mgmt.network import NetworkManagementClient from azure.mgmt.compute.models import NetworkInterfaceReference nics = [] if nic_names or nic_ids: #pylint: disable=no-member network_client = get_mgmt_service_client(NetworkManagementClient) for n in nic_names: nic = network_client.network_interfaces.get(resource_group_name, n) nics.append(NetworkInterfaceReference(nic.id, False)) for n in nic_ids: rg, name = _parse_rg_name(n) nic = network_client.network_interfaces.get(rg, name) nics.append(NetworkInterfaceReference(nic.id, False)) return nics
def _find_default_vnet(namespace): if not namespace.virtual_network and not namespace.virtual_network_type: from azure.mgmt.network import NetworkManagementClient from azure.cli.commands.client_factory import get_mgmt_service_client client = get_mgmt_service_client(NetworkManagementClient).virtual_networks vnet = next((v for v in client.list(namespace.resource_group_name)), None) if vnet: try: namespace.subnet_name = vnet.subnets[0].name namespace.virtual_network = vnet.name namespace.virtual_network_type = 'existingName' except KeyError: pass
def _find_default_vnet(namespace): if not namespace.virtual_network and not namespace.virtual_network_type: from azure.mgmt.network import NetworkManagementClient from azure.cli.commands.client_factory import get_mgmt_service_client client = get_mgmt_service_client( NetworkManagementClient).virtual_networks vnet = next((v for v in client.list(namespace.resource_group_name)), None) if vnet: try: namespace.subnet_name = vnet.subnets[0].name namespace.virtual_network = vnet.name namespace.virtual_network_type = 'existingName' except KeyError: pass
def _deploy_arm_template_core(resource_group_name, deployment_name, template_file_path, parameters_file_path=None, mode='incremental', validate_only=False): from azure.mgmt.resource.resources.models import DeploymentProperties parameters = None if parameters_file_path: parameters = get_file_json(parameters_file_path) if parameters: parameters = parameters.get('parameters', parameters) template = get_file_json(template_file_path) properties = DeploymentProperties(template=template, parameters=parameters, mode=mode) smc = get_mgmt_service_client(ResourceManagementClient) if validate_only: return smc.deployments.validate(resource_group_name, deployment_name, properties) else: return smc.deployments.create_or_update(resource_group_name, deployment_name, properties)
def storage_client_factory(**_): return get_mgmt_service_client(StorageManagementClient)
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. #--------------------------------------------------------------------------------------------- #pylint: disable=unused-import from azure.mgmt.web.operations import SitesOperations from azure.cli.commands import LongRunningOperation, cli_command from azure.cli.commands.client_factory import get_mgmt_service_client from azure.cli.command_modules.webapp._params import _web_client_factory from azure.cli.command_modules.webapp.mgmt_webapp.lib \ import (WebappCreationClient as WebAppClient) from azure.cli.command_modules.webapp.mgmt_webapp.lib.operations import WebappOperations class DeploymentOutputLongRunningOperation(LongRunningOperation): #pylint: disable=too-few-public-methods def __call__(self, poller): result = super(DeploymentOutputLongRunningOperation, self).__call__(poller) return result.properties.outputs factory = lambda _: _web_client_factory() cli_command('webapp get-sites', SitesOperations.get_sites, factory) factory = lambda _: get_mgmt_service_client(WebAppClient).webapp cli_command('webapp create', WebappOperations.create_or_update, factory, transform=DeploymentOutputLongRunningOperation('Creating webapp'))
def _redis_client_factory(**_): return get_mgmt_service_client(RedisManagementClient)
def get_resources_in_subscription(resource_type=None): rcf = get_mgmt_service_client(ResourceManagementClient) filter_str = "resourceType eq '{}'".format( resource_type) if resource_type else None return list(rcf.resources.list(filter=filter_str))
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' } for subresource, alias in property_map.items(): cli_command('network application-gateway {} list'.format(alias), list_network_resource_property('application_gateways', subresource), simple_output_query="[*].{Name:name} | sort_by(@, &Name)")
def get_resources_in_resource_group(resource_group_name, resource_type=None): rcf = get_mgmt_service_client(ResourceManagementClient) filter_str = "resourceType eq '{}'".format(resource_type) if resource_type else None return list(rcf.resource_groups.list_resources(resource_group_name, filter=filter_str))
#pylint: disable=unused-import from azure.mgmt.web.operations import SitesOperations from azure.cli.commands import LongRunningOperation, cli_command from azure.cli.commands.client_factory import get_mgmt_service_client from azure.cli.command_modules.webapp._params import _web_client_factory from azure.cli.command_modules.webapp.mgmt_webapp.lib \ import (WebappCreationClient as WebAppClient) from azure.cli.command_modules.webapp.mgmt_webapp.lib.operations import WebappOperations class DeploymentOutputLongRunningOperation(LongRunningOperation): #pylint: disable=too-few-public-methods def __call__(self, poller): result = super(DeploymentOutputLongRunningOperation, self).__call__(poller) return result.properties.outputs factory = lambda _: _web_client_factory() cli_command('webapp get-sites', SitesOperations.get_sites, factory) factory = lambda _: get_mgmt_service_client(WebAppClient).webapp cli_command('webapp create', WebappOperations.create_or_update, factory, transform=DeploymentOutputLongRunningOperation('Creating webapp'))
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', ExpressRouteCircuitAuthorizationsOperations.get, factory) cli_command('network express-route circuit-auth list', ExpressRouteCircuitAuthorizationsOperations.list, factory)
def _network_client_factory(**_): return get_mgmt_service_client(NetworkManagementClient)
def _resource_client_factory(**_): return get_mgmt_service_client(ResourceManagementClient)
list_load_balancer_property, get_load_balancer_property_entry, delete_load_balancer_property_entry) 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', ApplicationGatewaysOperations.list, factory) cli_command('network application-gateway list-all', ApplicationGatewaysOperations.list_all, factory) cli_command('network application-gateway start', ApplicationGatewaysOperations.start, factory) cli_command('network application-gateway stop', ApplicationGatewaysOperations.stop, 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', ExpressRouteCircuitAuthorizationsOperations.get, factory) cli_command('network express-route circuit-auth list', ExpressRouteCircuitAuthorizationsOperations.list, factory) # ExpressRouteCircuitPeeringsOperations factory = lambda _: _network_client_factory().express_route_circuit_peerings cli_command('network express-route circuit-peering delete', ExpressRouteCircuitPeeringsOperations.delete, factory) cli_command('network express-route circuit-peering show', ExpressRouteCircuitPeeringsOperations.get, factory) cli_command('network express-route circuit-peering list', ExpressRouteCircuitPeeringsOperations.list, factory) # ExpressRouteCircuitsOperations
def _keyvault_client_factory(**_): return get_mgmt_service_client(KeyVaultManagementClient)
def export_deployment_as_template(resource_group_name, deployment_name): smc = get_mgmt_service_client(ResourceManagementClient) result = smc.deployments.export_template(resource_group_name, deployment_name) print(json.dumps(result.template, indent=2))#pylint: disable=no-member
def _resource_policy_client_factory(**_): return get_mgmt_service_client(PolicyClient)
def _web_client_factory(**_): return get_mgmt_service_client(WebSiteManagementClient)
def get_resources_in_subscription(resource_type=None): rcf = get_mgmt_service_client(ResourceManagementClient) filter_str = "resourceType eq '{}'".format(resource_type) if resource_type else None return list(rcf.resources.list(filter=filter_str))
def _auth_client_factory(**_): return get_mgmt_service_client(AuthorizationManagementClient)
vm_update_nics, vm_delete_nics, vm_add_nics, vm_open_port, reset_windows_admin, set_linux_user, delete_linux_user, disable_boot_diagnostics, enable_boot_diagnostics, get_boot_log, list_extensions, set_extension, set_diagnostics_extension, show_default_diagnostics_configuration, vmss_start, vmss_restart, vmss_delete_instances, vmss_deallocate, vmss_get_instance_view, vmss_stop, vmss_reimage, vmss_scale, vmss_update_instances, vmss_show, vmss_list ) from ._factory import _compute_client_factory # pylint: disable=line-too-long # VM factory = lambda _: get_mgmt_service_client(VMClient).vm cli_command('vm create', VmOperations.create_or_update, factory, transform=DeploymentOutputLongRunningOperation('Starting vm create')) factory = lambda _: _compute_client_factory().virtual_machines cli_command('vm delete', VirtualMachinesOperations.delete, factory) cli_command('vm deallocate', VirtualMachinesOperations.deallocate, factory) 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)")
def get_resource_groups(): rcf = get_mgmt_service_client(ResourceManagementClient) return list(rcf.resource_groups.list())
def _compute_client_factory(**_): return get_mgmt_service_client(ComputeManagementClient)
def vm_open_port(resource_group_name, vm_name, network_security_group_name=None, apply_to_subnet=False): """ Opens a VM to all inbound traffic and protocols by adding a security rule to the network security group (NSG) that is attached to the VM's network interface (NIC) or subnet. The existing NSG will be used or a new one will be created. The rule name is 'open-port-cmd' and will overwrite an existing rule with this name. For multi-NIC VMs, or for more fine grained control, use the appropriate network commands directly (nsg rule create, etc). """ from azure.mgmt.network import NetworkManagementClient network = get_mgmt_service_client(NetworkManagementClient) vm = _vm_get(resource_group_name, vm_name) location = vm.location nic_ids = list(vm.network_profile.network_interfaces) if len(nic_ids) > 1: raise CLIError('Multiple NICs is not supported for this command. Create rules on the NSG ' 'directly.') elif not nic_ids: raise CLIError("No NIC associated with VM '{}'".format(vm_name)) # get existing NSG or create a new one nic = network.network_interfaces.get(resource_group_name, os.path.split(nic_ids[0].id)[1]) if not apply_to_subnet: nsg = nic.network_security_group else: from azure.cli.commands.arm import parse_resource_id subnet_id = parse_resource_id(nic.ip_configurations[0].subnet.id) subnet = network.subnets.get(resource_group_name, subnet_id['name'], subnet_id['child_name']) nsg = subnet.network_security_group if not nsg: from azure.mgmt.network.models import NetworkSecurityGroup nsg = LongRunningOperation('Creating network security group')( network.network_security_groups.create_or_update( resource_group_name=resource_group_name, network_security_group_name=network_security_group_name, parameters=NetworkSecurityGroup(location=location) ) ) # update the NSG with the new rule to allow inbound traffic from azure.mgmt.network.models import SecurityRule rule = SecurityRule(protocol='*', access='allow', direction='inbound', name='open-port-cmd', source_port_range='*', destination_port_range='*', priority=900, source_address_prefix='*', destination_address_prefix='*') nsg_name = nsg.name or os.path.split(nsg.id)[1] LongRunningOperation('Adding security rule')( network.security_rules.create_or_update( resource_group_name, nsg_name, 'open-port-cmd', rule) ) # update the NIC or subnet if not apply_to_subnet: nic.network_security_group = nsg return LongRunningOperation('Updating NIC')( network.network_interfaces.create_or_update( resource_group_name, nic.name, nic) ) else: from azure.mgmt.network.models import Subnet subnet.network_security_group = nsg return LongRunningOperation('Updating subnet')( network.subnets.create_or_update( resource_group_name=resource_group_name, virtual_network_name=subnet_id['name'], subnet_name=subnet_id['child_name'], subnet_parameters=subnet ) )
def _get_storage_management_client(): from azure.mgmt.storage import StorageManagementClient return get_mgmt_service_client(StorageManagementClient)
list_vm, resize_vm, list_vm_images, list_vm_extension_images, list_ip_addresses, attach_new_disk, attach_existing_disk, detach_disk, list_disks, capture_vm, vm_update_nics, vm_delete_nics, vm_add_nics, vm_open_port, reset_windows_admin, set_linux_user, delete_linux_user, disable_boot_diagnostics, enable_boot_diagnostics, get_boot_log, list_extensions, set_extension, set_diagnostics_extension, show_default_diagnostics_configuration, vmss_start, vmss_restart, vmss_delete_instances, vmss_deallocate, vmss_get_instance_view, vmss_stop, vmss_reimage, vmss_scale, vmss_update_instances, vmss_show, vmss_list) from ._factory import _compute_client_factory # pylint: disable=line-too-long # VM factory = lambda _: get_mgmt_service_client(VMClient).vm cli_command( 'vm create', VmOperations.create_or_update, factory, transform=DeploymentOutputLongRunningOperation('Starting vm create')) factory = lambda _: _compute_client_factory().virtual_machines cli_command('vm delete', VirtualMachinesOperations.delete, factory) cli_command('vm deallocate', VirtualMachinesOperations.deallocate, factory) cli_command('vm generalize', VirtualMachinesOperations.generalize, factory) cli_command( 'vm show', VirtualMachinesOperations.get, factory,
def _resource_feature_client_factory(**_): return get_mgmt_service_client(FeatureClient)