Python azure.mgmt.network.NetworkManagementClient() Examples

The following are 26 code examples of azure.mgmt.network.NetworkManagementClient(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module azure.mgmt.network , or try the search function .
Example #1
Source File: infra.py    From whoville with Apache License 2.0 8 votes vote down vote up
def create_azure_session(token, service):
    assert service in ['compute', 'network', 'security', 'storage', 'resource']
    assert isinstance(token, ServicePrincipalCredentials)
    platform = config.profile.get('platform')
    if 'subscription' in platform and platform['subscription']:
        sub_id = platform['subscription']
    else:
        raise ValueError("Subscription ID not in Azure Platform Definition")
    if service == 'compute':
        from azure.mgmt.compute import ComputeManagementClient
        return ComputeManagementClient(token, sub_id)
    if service == 'network':
        from azure.mgmt.network import NetworkManagementClient
        return NetworkManagementClient(token, sub_id)
    if service == 'storage':
        from azure.mgmt.storage import StorageManagementClient
        return StorageManagementClient(token, sub_id)
    if service == 'resource':
        from azure.mgmt.resource import ResourceManagementClient
        return ResourceManagementClient(token, sub_id) 
Example #2
Source File: azure_rm.py    From Ansible-2-Cloud-Automation-Cookbook with MIT License 5 votes vote down vote up
def network_client(self):
        self.log('Getting network client')
        if not self._network_client:
            self._network_client = NetworkManagementClient(
                self.azure_credentials,
                self.subscription_id,
                base_url=self._cloud_environment.endpoints.resource_manager,
                api_version='2017-06-01'
            )
            self._register('Microsoft.Network')
        return self._network_client 
Example #3
Source File: sync.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def discover_resources(**kwargs):
    discovered_virtual_nets = []
    for handler in AzureARMHandler.objects.all():
        set_progress(
            "Connecting to Azure networks \
        for handler: {}".format(
                handler
            )
        )
        credentials = ServicePrincipalCredentials(
            client_id=handler.client_id, secret=handler.secret, tenant=handler.tenant_id
        )
        network_client = NetworkManagementClient(credentials, handler.serviceaccount)

        azure_resources_client = resources.ResourceManagementClient(
            credentials, handler.serviceaccount
        )

        for resource_group in azure_resources_client.resource_groups.list():
            try:
                for security_group in network_client.network_security_groups.list(
                    resource_group_name=resource_group.name
                ):
                    discovered_virtual_nets.append(
                        {
                            "name": "Azure NSG - " + security_group.as_dict()["name"],
                            "azure_network_security_group": security_group.as_dict()[
                                "name"
                            ],
                            "azure_location": security_group.as_dict()["location"],
                            "azure_rh_id": handler.id,
                            "resource_group_name": resource_group.name,
                        }
                    )
            except CloudError as e:
                set_progress("Azure Clouderror: {}".format(e))
                continue

    return discovered_virtual_nets 
Example #4
Source File: delete.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def run(job, **kwargs):
    resource = kwargs.pop("resources").first()

    azure_network_security_group = resource.attributes.get(
        field__name="azure_network_security_group"
    ).value
    resource_group = resource.attributes.get(field__name="resource_group_name").value
    rh_id = resource.attributes.get(field__name="azure_rh_id").value
    rh = AzureARMHandler.objects.get(id=rh_id)

    set_progress("Connecting To Azure networking...")
    credentials = ServicePrincipalCredentials(
        client_id=rh.client_id, secret=rh.secret, tenant=rh.tenant_id
    )

    network_client = NetworkManagementClient(credentials, rh.serviceaccount)
    set_progress("Connection to Azure networking established")

    set_progress(
        "Deleting network security group %s..." % (azure_network_security_group)
    )

    try:
        network_client.network_security_groups.delete(
            resource_group_name=resource_group,
            network_security_group_name=azure_network_security_group,
        )
    except CloudError as e:
        set_progress("Azure Clouderror: {}".format(e))
        return "FAILURE", "Network security group could not be deleted", ""

    return "SUCCESS", "The network security group has been succesfully deleted", "" 
Example #5
Source File: monitor.py    From pan-fca with Apache License 2.0 5 votes vote down vote up
def __init__(self, cred, subs_id, my_storage_rg, vmss_rg_name, vmss_name, storage, pan_handle, logger=None):
        self.credentials = cred
        self.subscription_id = subs_id
        self.logger = logger
        self.hub_name = vmss_rg_name
        self.storage_name = storage
        self.panorama_handler = pan_handle
        self.vmss_table_name = re.sub(self.ALPHANUM, '', vmss_name + 'vmsstable')
        self.vmss_rg_name = vmss_rg_name

        try:
            self.resource_client = ResourceManagementClient(cred, subs_id)
            self.compute_client = ComputeManagementClient(cred, subs_id)
            self.network_client = NetworkManagementClient(cred, subs_id)
            self.store_client = StorageManagementClient(cred, subs_id)
            store_keys = self.store_client.storage_accounts.list_keys(my_storage_rg, storage).keys[0].value
            self.table_service = TableService(account_name=storage,
                                              account_key=store_keys)
        except Exception as e:
            self.logger.error("Getting Azure Infra handlers failed %s" % str(e))
            raise e


        rg_list = self.resource_client.resource_groups.list()
        self.managed_spokes = []
        self.managed_spokes.append(vmss_rg_name)
        self.new_spokes = [] 
Example #6
Source File: azure.py    From parsl with Apache License 2.0 5 votes vote down vote up
def get_clients(self):
        """
        Set up access to Azure API clients
        """
        credentials, subscription_id = self.get_credentials()
        self.resource_client = ResourceManagementClient(
            credentials, subscription_id)
        self.compute_client = ComputeManagementClient(credentials,
                                                      subscription_id)
        self.network_client = NetworkManagementClient(credentials,
                                                      subscription_id) 
Example #7
Source File: arm.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def __init__(self, location: str, subscription_id: str, client_id: str, client_secret: str, tenant_id: str):
        self.credentials = ServicePrincipalCredentials(
            client_id=client_id,
            secret=client_secret,
            tenant=tenant_id)
        self.rmc = ResourceManagementClient(self.credentials, subscription_id)
        self.nmc = NetworkManagementClient(self.credentials, subscription_id)
        self.mc = MonitorClient(self.credentials, subscription_id)
        # location is included to keep a similar model as dcos_launch.platforms.aws.BotoWrapper
        self.location = location 
Example #8
Source File: arm.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def __init__(self, location: str, subscription_id: str, client_id: str, client_secret: str, tenant_id: str):
        self.credentials = ServicePrincipalCredentials(
            client_id=client_id,
            secret=client_secret,
            tenant=tenant_id)
        self.rmc = ResourceManagementClient(self.credentials, subscription_id)
        self.nmc = NetworkManagementClient(self.credentials, subscription_id)
        self.mc = MonitorClient(self.credentials, subscription_id)
        # location is included to keep a similar model as dcos_launch.platforms.aws.BotoWrapper
        self.location = location 
Example #9
Source File: azure_vm.py    From SnowAlert with Apache License 2.0 5 votes vote down vote up
def get_nics(options):
    cli = get_client_from_json_dict(NetworkManagementClient, options)
    return [nic.as_dict() for nic in cli.network_interfaces.list_all()] 
Example #10
Source File: node_provider.py    From ray with Apache License 2.0 5 votes vote down vote up
def __init__(self, provider_config, cluster_name):
        NodeProvider.__init__(self, provider_config, cluster_name)
        kwargs = {}
        if "subscription_id" in provider_config:
            kwargs["subscription_id"] = provider_config["subscription_id"]
        try:
            self.compute_client = get_client_from_cli_profile(
                client_class=ComputeManagementClient, **kwargs)
            self.network_client = get_client_from_cli_profile(
                client_class=NetworkManagementClient, **kwargs)
            self.resource_client = get_client_from_cli_profile(
                client_class=ResourceManagementClient, **kwargs)
        except CLIError as e:
            if str(e) != "Please run 'az login' to setup account.":
                raise
            else:
                logger.info("CLI profile authentication failed. Trying MSI")

                credentials = MSIAuthentication()
                self.compute_client = ComputeManagementClient(
                    credentials=credentials, **kwargs)
                self.network_client = NetworkManagementClient(
                    credentials=credentials, **kwargs)
                self.resource_client = ResourceManagementClient(
                    credentials=credentials, **kwargs)

        self.lock = RLock()

        # cache node objects
        self.cached_nodes = {} 
Example #11
Source File: azure_rm.py    From Learning_DevOps with MIT License 5 votes vote down vote up
def network_client(self):
        self.log('Getting network client')
        if not self._network_client:
            self._network_client = self.get_mgmt_svc_client(NetworkManagementClient,
                                                            self._cloud_environment.endpoints.resource_manager,
                                                            '2017-06-01')
            self._register('Microsoft.Network')
        return self._network_client 
Example #12
Source File: azure_rm.py    From f5-azure-saca with MIT License 5 votes vote down vote up
def network_client(self):
        self.log('Getting network client')
        if not self._network_client:
            self._network_client = NetworkManagementClient(
                self.azure_credentials,
                self.subscription_id,
                base_url=self._cloud_environment.endpoints.resource_manager,
                api_version='2017-06-01'
            )
            self._register('Microsoft.Network')
        return self._network_client 
Example #13
Source File: arm.py    From dcos-launch with Apache License 2.0 5 votes vote down vote up
def __init__(self, location: str, subscription_id: str, client_id: str, client_secret: str, tenant_id: str):
        self.credentials = ServicePrincipalCredentials(
            client_id=client_id,
            secret=client_secret,
            tenant=tenant_id)
        self.rmc = ResourceManagementClient(self.credentials, subscription_id)
        self.nmc = NetworkManagementClient(self.credentials, subscription_id)
        self.mc = MonitorClient(self.credentials, subscription_id)
        # location is included to keep a similar model as dcos_launch.platforms.aws.BotoWrapper
        self.location = location 
Example #14
Source File: azure_driver.py    From powerfulseal with Apache License 2.0 5 votes vote down vote up
def create_connection_from_config():
    """ Creates a new Azure api connection """
    resource_client = None
    compute_client = None
    network_client = None
    try:
        os.environ['AZURE_AUTH_LOCATION']
    except KeyError:
        try:
            subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
            credentials = ServicePrincipalCredentials(
                client_id=os.environ['AZURE_CLIENT_ID'],
                secret=os.environ['AZURE_CLIENT_SECRET'],
                tenant=os.environ['AZURE_TENANT_ID']
            )
        except KeyError:
            sys.exit("No Azure Connection Defined")
        else:
           resource_client = ResourceManagementClient(credentials, subscription_id)
           compute_client = ComputeManagementClient(credentials, subscription_id)
           network_client = NetworkManagementClient(credentials, subscription_id)
    else:
        resource_client = get_client_from_auth_file(ResourceManagementClient)
        compute_client = get_client_from_auth_file(ComputeManagementClient)
        network_client = get_client_from_auth_file(NetworkManagementClient)

    return resource_client, compute_client, network_client 
Example #15
Source File: msazure.py    From wrapanapi with MIT License 5 votes vote down vote up
def network_client(self):
        return NetworkManagementClient(self.credentials, self.subscription_id) 
Example #16
Source File: azure_resource.py    From Particle-Cloud-Framework with Apache License 2.0 5 votes vote down vote up
def network_client(self):
        """
        Uses client from cli so that users can use az login to get their credentials

        Returns:
             Network Client
        """
        if not self.client:
            self.client = get_client_from_cli_profile(NetworkManagementClient)
        return self.client 
Example #17
Source File: azure_client.py    From cloudbridge with MIT License 5 votes vote down vote up
def network_management_client(self):
        if not self._network_management_client:
            self._network_management_client = NetworkManagementClient(
                self._credentials, self.subscription_id)
        return self._network_management_client 
Example #18
Source File: azure_rm.py    From ansible-hortonworks with Apache License 2.0 5 votes vote down vote up
def network_client(self):
        self.log('Getting network client')
        if not self._network_client:
            self._network_client = self.get_mgmt_svc_client(NetworkManagementClient,
                                                            self._cloud_environment.endpoints.resource_manager,
                                                            '2017-06-01')
            self._register('Microsoft.Network')
        return self._network_client 
Example #19
Source File: meta_lib.py    From incubator-dlab with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        os.environ['AZURE_AUTH_LOCATION'] = '/root/azure_auth.json'
        self.compute_client = get_client_from_auth_file(ComputeManagementClient)
        self.resource_client = get_client_from_auth_file(ResourceManagementClient)
        self.network_client = get_client_from_auth_file(NetworkManagementClient)
        self.storage_client = get_client_from_auth_file(StorageManagementClient)
        self.datalake_client = get_client_from_auth_file(DataLakeStoreAccountManagementClient)
        self.authorization_client = get_client_from_auth_file(AuthorizationManagementClient)
        self.sp_creds = json.loads(open(os.environ['AZURE_AUTH_LOCATION']).read())
        self.dl_filesystem_creds = lib.auth(tenant_id=json.dumps(self.sp_creds['tenantId']).replace('"', ''),
                                            client_secret=json.dumps(self.sp_creds['clientSecret']).replace('"', ''),
                                            client_id=json.dumps(self.sp_creds['clientId']).replace('"', ''),
                                            resource='https://datalake.azure.net/') 
Example #20
Source File: actions_lib.py    From incubator-dlab with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        os.environ['AZURE_AUTH_LOCATION'] = '/root/azure_auth.json'
        self.compute_client = get_client_from_auth_file(ComputeManagementClient)
        self.resource_client = get_client_from_auth_file(ResourceManagementClient)
        self.network_client = get_client_from_auth_file(NetworkManagementClient)
        self.storage_client = get_client_from_auth_file(StorageManagementClient)
        self.datalake_client = get_client_from_auth_file(DataLakeStoreAccountManagementClient)
        self.authorization_client = get_client_from_auth_file(AuthorizationManagementClient)
        self.sp_creds = json.loads(open(os.environ['AZURE_AUTH_LOCATION']).read())
        self.dl_filesystem_creds = lib.auth(tenant_id=json.dumps(self.sp_creds['tenantId']).replace('"', ''),
                                            client_secret=json.dumps(self.sp_creds['clientSecret']).replace('"', ''),
                                            client_id=json.dumps(self.sp_creds['clientId']).replace('"', ''),
                                            resource='https://datalake.azure.net/') 
Example #21
Source File: azure_data.py    From msticpy with MIT License 5 votes vote down vote up
def __init__(self, connect: bool = False):
        """Initialize connector for Azure Python SDK."""
        self.connected = False
        self.credentials: Optional[ServicePrincipalCredentials] = None
        self.sub_client: Optional[SubscriptionClient] = None
        self.resource_client: Optional[ResourceManagementClient] = None
        self.network_client: Optional[NetworkManagementClient] = None
        self.monitoring_client: Optional[MonitorManagementClient] = None
        self.compute_client: Optional[ComputeManagementClient] = None
        if connect is True:
            self.connect() 
Example #22
Source File: network.py    From ScoutSuite with GNU General Public License v2.0 5 votes vote down vote up
def get_client(self, subscription_id: str):
        return NetworkManagementClient(self.credentials.get_credentials('arm'),
                                       subscription_id=subscription_id) 
Example #23
Source File: Azure.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def setIPs(vm, network_profile, credentials, subscription_id):
        """
        Set the information about the IPs of the VM
        """

        private_ips = []
        public_ips = []

        network_client = NetworkManagementClient(credentials, subscription_id)

        for ni in network_profile.network_interfaces:
            name = " ".join(ni.id.split('/')[-1:])
            sub = "".join(ni.id.split('/')[4])

            ip_conf = network_client.network_interfaces.get(sub, name).ip_configurations

            for ip in ip_conf:
                if ip.private_ip_address:
                    private_ips.append(ip.private_ip_address)
                if ip.public_ip_address:
                    name = " ".join(ip.public_ip_address.id.split('/')[-1:])
                    sub = "".join(ip.public_ip_address.id.split('/')[4])
                    public_ip_info = network_client.public_ip_addresses.get(sub, name)
                    public_ips.append(public_ip_info.ip_address)

        vm.setIps(public_ips, private_ips) 
Example #24
Source File: Azure.py    From im with GNU General Public License v3.0 4 votes vote down vote up
def create_nets(self, radl, credentials, subscription_id, group_name, inf):
        network_client = NetworkManagementClient(credentials, subscription_id)
        location = self.DEFAULT_LOCATION
        if radl.systems[0].getValue('availability_zone'):
            location = radl.systems[0].getValue('availability_zone')
        # check if the vnet exists
        vnet = None
        try:
            vnet = network_client.virtual_networks.get(group_name, "privates")
        except Exception:
            pass

        if not vnet:
            vnet_cird = self.get_nets_common_cird(radl)
            # Create VNet in the RG of the Inf
            async_vnet_creation = network_client.virtual_networks.create_or_update(
                group_name,
                "privates",
                {
                    'location': location,
                    'address_space': {
                        'address_prefixes': [vnet_cird]
                    }
                }
            )
            async_vnet_creation.wait()

            subnets = {}
            used_cidrs = []
            for net in radl.networks:
                subnet_name = net.id
                net_cidr = self.get_free_cidr(net.getValue('cidr'), used_cidrs, inf)
                used_cidrs.append(net_cidr)

                # Create Subnet in the RG of the Inf
                async_subnet_creation = network_client.subnets.create_or_update(
                    group_name,
                    "privates",
                    subnet_name,
                    {'address_prefix': net_cidr}
                )
                subnets[net.id] = async_subnet_creation.result()
                net.setValue('cidr', net_cidr)
                # Set also the cidr in the inf RADL
                inf.radl.get_network_by_id(net.id).setValue('cidr', net_cidr)
        else:
            subnets = {}
            for i, net in enumerate(radl.networks):
                subnets[net.id] = network_client.subnets.get(group_name, "privates", net.id)

        return subnets 
Example #25
Source File: account_setup.py    From aztk with MIT License 4 votes vote down vote up
def create_vnet(credentials, subscription_id, **kwargs):
    """
        Create a Batch account
        :param credentials: msrestazure.azure_active_directory.AdalAuthentication
        :param subscription_id: str
        :param **resource_group: str
        :param **virtual_network_name: str
        :param **subnet_name: str
        :param **region: str
    """
    network_client = NetworkManagementClient(credentials, subscription_id)
    resource_group_name = kwargs.get("resource_group", DefaultSettings.resource_group)
    virtual_network_name = kwargs.get("virtual_network_name", DefaultSettings.virtual_network_name)
    subnet_name = kwargs.get("subnet_name", DefaultSettings.subnet_name)
    # get vnet, and subnet if they exist
    virtual_network = subnet = None
    try:
        virtual_network = network_client.virtual_networks.get(
            resource_group_name=resource_group_name,
            virtual_network_name=virtual_network_name,
        )
    except CloudError as e:
        pass

    if virtual_network:
        confirmation_prompt = "A virtual network with the same name ({}) was found. \n"\
                             "Please note that the existing address space and subnets may be changed or destroyed. \n"\
                             "Do you want to use this virtual network? (y/n): ".format(virtual_network_name)
        deny_error = AccountSetupError("Virtual network already exists, not recreating.")
        unrecognized_input_error = AccountSetupError("Input not recognized.")
        prompt_for_confirmation(confirmation_prompt, deny_error, unrecognized_input_error)

    virtual_network = network_client.virtual_networks.create_or_update(
        resource_group_name=resource_group_name,
        virtual_network_name=kwargs.get("virtual_network_name", DefaultSettings.virtual_network_name),
        parameters=VirtualNetwork(
            location=kwargs.get("region", DefaultSettings.region), address_space=AddressSpace(["10.0.0.0/24"])))
    virtual_network = virtual_network.result()
    subnet = network_client.subnets.create_or_update(
        resource_group_name=resource_group_name,
        virtual_network_name=virtual_network_name,
        subnet_name=subnet_name,
        subnet_parameters=Subnet(address_prefix='10.0.0.0/24'))
    return subnet.result().id 
Example #26
Source File: create.py    From cloudbolt-forge with Apache License 2.0 3 votes vote down vote up
def run(job, **kwargs):
    resource = kwargs.get("resource")

    env_id = "{{ env_id }}"
    env = Environment.objects.get(id=env_id)
    rh = env.resource_handler.cast()
    location = env.node_location
    set_progress("Location: %s" % location)

    resource_group = "{{ resource_group }}"
    network_security_group_name = "{{ network_security_group_name }}"

    create_custom_fields_as_needed()

    set_progress("Connecting To Azure Network Service...")

    credentials = ServicePrincipalCredentials(
        client_id=rh.client_id, secret=rh.secret, tenant=rh.tenant_id,
    )
    network_client = NetworkManagementClient(credentials, rh.serviceaccount)
    set_progress("Connection to Azure networks established")

    set_progress("Creating the network security group...")
    security_rule_parameters = {
        "location": location,
    }
    try:
        async_vnet_creation = network_client.network_security_groups.create_or_update(
            resource_group, network_security_group_name, security_rule_parameters
        )
        nsg_info = async_vnet_creation.result()
    except CloudError as e:
        set_progress("Azure Clouderror: {}".format(e))

    assert nsg_info.name == network_security_group_name

    resource.name = "Azure NSG - " + network_security_group_name
    resource.azure_network_security_group = network_security_group_name
    resource.resource_group_name = resource_group
    resource.azure_location = location
    resource.azure_rh_id = rh.id
    resource.save()

    return (
        "SUCCESS",
        "Network security group {} has been created in Location {}.".format(
            network_security_group_name, location
        ),
        "",
    )