Пример #1
0
    def __init__(self):
        subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
        credentials = ClientSecretCredential(
            tenant_id=os.environ['AZURE_TENANT_ID'],
            client_id=os.environ['AZURE_CLIENT_ID'],
            client_secret=os.environ['AZURE_CLIENT_SECRET'])

        self.resource_client = ResourceManagementClient(
            credentials, subscription_id)
        self.compute_client = ComputeManagementClient(credentials,
                                                      subscription_id)
        self.network_client = NetworkManagementClient(credentials,
                                                      subscription_id)
Пример #2
0
 def network_client(self):
     self.log('Getting network client')
     if not self._network_client:
         self.check_client_version(
             'network', network_client_version,
             AZURE_EXPECTED_VERSIONS['network_client_version'])
         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
Пример #3
0
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),
        "",
    )
def create_nic(request, ressource_id):
    print(ressource_id)
    form = NicForm(request.POST or None, request.FILES or None)
    ressource = get_object_or_404(Ressources, pk=ressource_id)
    if form.is_valid():
        ressource_nic = ressource.nic_set.all()
        for s in ressource_nic:
            if s.nic_name == form.cleaned_data.get("nic_name"):
                context = {
                    'ressource': ressource,
                    'form': form,
                    'error_message': 'You already added that nic',
                }
                return render(request, 'ressource/create_nic.html', context)
        nic = form.save(commit=False)
        nic.ressource = ressource

        userCloud = get_object_or_404(UserCloud, user=(request.user))
        subscription_id = userCloud.subscription_id  # your Azure Subscription Id
        credentials = ServicePrincipalCredentials(
            client_id=userCloud.client_id,
            secret=userCloud.secret,
            tenant=userCloud.tenant)
        network_client = NetworkManagementClient(credentials, subscription_id)

        subnet_infos = network_client.subnets.get(nic.ressource.groupe_name,
                                                  nic.vnet.vnet_name,
                                                  nic.subnet.subnet_name)

        async_nic_creation = network_client.network_interfaces.create_or_update(
            nic.ressource.groupe_name, form.cleaned_data['nic_name'], {
                'location':
                nic.ressource.location,
                'ip_configurations': [{
                    'name':
                    form.cleaned_data['ip_configuration_name'],
                    'subnet': {
                        'id': subnet_infos.id
                    }
                }]
            })
        print(nic.ressource.groupe_name)
        async_nic_creation.wait()
        nic.save()
        return render(request, 'ressource/detail_ressource.html',
                      {'ressource': ressource})
    context = {
        'ressource': ressource,
        'form': form,
    }
    return render(request, 'ressource/create_nic.html', context)
Пример #5
0
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
Пример #6
0
def configure():
    subscription_id, tenant_id = get_credentials()
    credentials = authenticate_device_code(tenant_id)
    resource_client = ResourceManagementClient(credentials, subscription_id)
    network_client = NetworkManagementClient(credentials, subscription_id)
    storage_client = StorageManagementClient(credentials, subscription_id)
    rg = choose(list(resource_client.resource_groups.list()), "resource group", lambda x: x.name)

    storage_accounts = {}

    print("Configuring flow logs for all network security groups in resource group " + rg.name)
    nsgs = list(network_client.network_security_groups.list(rg.name))
    for nsg in nsgs:
        nw_name = "NetworkWatcher_" + nsg.location
        if nsg.location not in storage_accounts:
            network_client.network_watchers.create_or_update("NetworkWatcherRG", nw_name, {
                "enabled": "true",
                "location": nsg.location
            })
            sleep(3)  # waiting for resource to be truly created
            print("enabled default network watcher for " + nsg.location + " location")

            available_storage_accounts = [sa for sa in storage_client.storage_accounts.list_by_resource_group(rg.name)
                                          if sa.location == nsg.location]
            storage_accounts[nsg.location] = choose(available_storage_accounts,
                                                    "storage account for " + nsg.location + " location",
                                                    lambda x: x.name,
                                                    "It is highly recommended to have a dedicated storage account for Flow-Logs, "
                                                    "if you dont have any, please configure one in the Azure Portal and re-run the script to choose it")
        network_client.network_watchers.set_flow_log_configuration(
            "NetworkWatcherRG", nw_name, {
                "enabled": "true",
                "target_resource_id": nsg.id,
                "storage_id": storage_accounts[nsg.location].id,
                "format": {
                    "type": "JSON",
                    "version": "2"
                }
            })
        print("enabled flow-logs for nsg " + nsg.name)
    return {
        "subscription_id": subscription_id,
        "resource_group": rg.name,
        "storage_accounts": [{
            "name": sa.name,
            "key": next(filter(lambda x: x.key_name == STORAGE_ACCOUNTS_KEY,
                               storage_client.storage_accounts.list_keys(rg.name, sa.name).keys)).value,
            "network_security_groups": [nsg.name for nsg in nsgs if nsg.location == sa.location]
        } for sa in storage_accounts.values()]
    }
Пример #7
0
 def _reload_connection(self):
     """
     Sets connections to work with Azure service APIs
     :return:
     """
     self.logger.debug('Reloading API Connection')
     try:
         self.conn = ResourceManagementClient(self.credentials, self.subscription_id)
         self.conn_compute = ComputeManagementClient(self.credentials, self.subscription_id)
         self.conn_vnet = NetworkManagementClient(self.credentials, self.subscription_id)
         self._check_or_create_resource_group()
         self._check_or_create_vnet()
     except Exception as e:
         self.format_vimconn_exception(e)            
Пример #8
0
def vpn_site_connection_get(siteName, credentials=None):
    """Get AVW gateway site connection status to AVW Hub."""
    # setup Azure Login Credentials from Environmental Variables
    if not credentials:
        credentials = get_credentials()
    # Connect to Azure APIs and get session details
    network_client = NetworkManagementClient(
        credentials, os.environ.get('ARM_SUBSCRIPTION_ID'))
    # Show VPN Site Connection Status to VPNG
    return network_client.vpn_connections.get(os.environ.get('GROUP_NAME'),
                                              os.environ.get('VPNG_NAME'),
                                              'CONNECTION_' + siteName,
                                              custom_headers=None,
                                              raw=False)
Пример #9
0
def get_public_ip(vm_obj):
    credential = AzureCliCredential()
    subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
    network_client = NetworkManagementClient(credential ,subscription_id)
    interface = vm_obj.network_profile.network_interfaces[0]
    name=" ".join(interface.id.split('/')[-1:])
    sub="".join(interface.id.split('/')[4])
    ip_config=network_client.network_interfaces.get(sub, name).ip_configurations
    ip_reference = ip_config[0].public_ip_address
    ip_reference = ip_reference.id.split('/')
    ip_group = ip_reference[4]
    ip_name = ip_reference[8]
    public_ip = network_client.public_ip_addresses.get(ip_group, ip_name)
    return public_ip.ip_address
Пример #10
0
def wujianhua_NetworkInt(AzureServicePrincipalcredentials=AzureServicePrincipalcredentials, subscription_id=wujianhua_subscription_id, resource_group=wujianhua_resource_group, location=wujianhua_location, vm_subnet_id=None):
    # provision a network interface for VM.
    print("Beginning the provisioing of the network interface - {}\n\n".format(wujianhua_resource_group))
    network_client = NetworkManagementClient(
        AzureServicePrincipalcredentials,
        subscription_id
    )

    public_ip_address_name = "wujianhuaPubIPAddress"  # the name of public IP address

    async_public_ip_address = network_client.public_ip_addresses.create_or_update(
        resource_group,
        public_ip_address_name,
        {
            "location": location,
            "sku": {
                "name": "Basic"
            },
            "public_ip_allocation_method": "Dynamic",
            "public_ip_address_version": "IPv4"

        }
    )

    async_public_ip_address.wait()

    publicIPAddress = network_client.public_ip_addresses.get(
        resource_group,
        public_ip_address_name,
    )

    async_network_interface = network_client.network_interfaces.create_or_update(
        resource_group,
        'wujianhuaint',
        {
            "location": location,
            "ip_configurations": [{
                "name": "wujianhua",
                "subnet": {
                    "id": vm_subnet_id
                },
                "public_ip_address": publicIPAddress
            }]
        }
    )

    async_network_interface.wait()

    network_int_id = async_network_interface.result().id
    return network_int_id
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    PUBLIC_IP_PREFIX = "public_ip_prefixxxyyzz"

    # Create client
    # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    network_client = NetworkManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # Create public ip prefix
    public_ip_prefix = network_client.public_ip_prefixes.begin_create_or_update(
        GROUP_NAME, PUBLIC_IP_PREFIX, {
            "location": "westus",
            "prefix_length": "30",
            "sku": {
                "name": "Standard"
            }
        }).result()
    print("Create public ip prefix:\n{}".format(public_ip_prefix))

    # Get public ip prefix
    public_ip_prefix = network_client.public_ip_prefixes.get(
        GROUP_NAME, PUBLIC_IP_PREFIX)
    print("Get public ip prefix:\n{}".format(public_ip_prefix))

    # Update public ip prefix
    public_ip_prefix = network_client.public_ip_prefixes.update_tags(
        GROUP_NAME, PUBLIC_IP_PREFIX,
        {"tags": {
            "tag1": "value1",
            "tag2": "value2"
        }})
    print("Update public ip prefix:\n{}".format(public_ip_prefix))

    # Delete public ip prefix
    public_ip_prefix = network_client.public_ip_prefixes.begin_delete(
        GROUP_NAME, PUBLIC_IP_PREFIX).result()
    print("Delete public ip prefix.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    VIRTUAL_WAN = "virtual_wanxxyyzz"

    # Create client
    # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    network_client = NetworkManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # Create virtual wan
    virtual_wan = network_client.virtual_wans.begin_create_or_update(
        GROUP_NAME, VIRTUAL_WAN, {
            "location": "West US",
            "tags": {
                "key1": "value1"
            },
            "disable_vpn_encryption": False,
            "type": "Basic"
        }).result()
    print("Create virtual wan:\n{}".format(virtual_wan))

    # Get virtual wan
    virtual_wan = network_client.virtual_wans.get(GROUP_NAME, VIRTUAL_WAN)
    print("Get virtual wan:\n{}".format(virtual_wan))

    # Update virtual wan
    virtual_wan = network_client.virtual_wans.update_tags(
        GROUP_NAME, VIRTUAL_WAN,
        {"tags": {
            "tag1": "value1",
            "tag2": "value2"
        }})
    print("Update virtual wan:\n{}".format(virtual_wan))

    # Delete virtual wan
    virtual_wan = network_client.virtual_wans.begin_delete(
        GROUP_NAME, VIRTUAL_WAN).result()
    print("Delete virtual wan.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
Пример #13
0
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):
                    for security_rule in network_client.security_rules.list(
                            resource_group_name=resource_group.name,
                            network_security_group_name=security_group.as_dict(
                            )['name']):
                        discovered_virtual_nets.append({
                            'name':
                            'Azure Security rule - ' +
                            security_group.as_dict()['name'] + " " +
                            security_rule.as_dict()['direction'],
                            'azure_network_security_group_name':
                            security_group.as_dict()['name'],
                            'azure_location':
                            security_group.as_dict()['location'],
                            'azure_rh_id':
                            handler.id,
                            'resource_group_name':
                            resource_group.name,
                            'azure_security_rule_protocol':
                            security_rule.as_dict()['protocol'],
                            'azure_security_rule_access':
                            security_rule.as_dict()['access'],
                            'azure_security_rule_direction':
                            security_rule.as_dict()['direction'],
                            'azure_security_rule_name':
                            security_rule.as_dict()['name'],
                        })
            except CloudError as e:
                set_progress('Azure Clouderror: {}'.format(e))
                continue

    return discovered_virtual_nets
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    LOCAL_NETWORK_GATEWAY = "local_network_gatewayxxyyzz"

    # Create client
    # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    network_client = NetworkManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # Create local network gateway
    local_network_gateway = network_client.local_network_gateways.begin_create_or_update(
        GROUP_NAME, LOCAL_NETWORK_GATEWAY, {
            "local_network_address_space": {
                "address_prefixes": ["10.1.0.0/16"]
            },
            "gateway_ip_address": "11.12.13.14",
            "location": "eastus"
        }).result()
    print("Create local network gateway:\n{}".format(local_network_gateway))

    # Get local network gateway
    local_network_gateway = network_client.local_network_gateways.get(
        GROUP_NAME, LOCAL_NETWORK_GATEWAY)
    print("Get local network gateway:\n{}".format(local_network_gateway))

    # Update local network gateway
    local_network_gateway = network_client.local_network_gateways.update_tags(
        GROUP_NAME, LOCAL_NETWORK_GATEWAY,
        {"tags": {
            "tag1": "value1",
            "tag2": "value2"
        }})
    print("Update local network gateway:\n{}".format(local_network_gateway))

    # Delete local network gateway
    local_network_gateway = network_client.local_network_gateways.begin_delete(
        GROUP_NAME, LOCAL_NETWORK_GATEWAY).result()
    print("Delete local network gateway.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
Пример #15
0
    def run(self):

        #----
        """Resource Group management example."""
        #
        # Create all clients with an Application (service principal) token provider
        #
        subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID',
                                         'ef80a466-7372-49e9-b247-57b95886881c'
                                         )  # your Azure Subscription Id
        credentials = ServicePrincipalCredentials(
            client_id='445a1911-819a-41e8-a093-adfd66ca5ccd',
            secret='rJ--cHsg@=fucrddh3svx1VUe91q2h1N',
            tenant='8ee0f3e4-b788-4efa-bd84-e6bfe7fe9943')
        resource_client = ResourceManagementClient(credentials,
                                                   subscription_id)
        compute_client = ComputeManagementClient(credentials, subscription_id)
        storage_client = StorageManagementClient(credentials, subscription_id)
        network_client = NetworkManagementClient(credentials, subscription_id)

        ###########
        # Prepare #
        ###########

        # Create Resource group
        print('\nCreate Resource Group')
        resource_client.resource_groups.create_or_update(
            GROUP_NAME, {'location': LOCATION})

        # Create a storage account
        print('\nCreate a storage account')
        storage_async_operation = storage_client.storage_accounts.create(
            GROUP_NAME, STORAGE_ACCOUNT_NAME, {
                'sku': {
                    'name': 'standard_lrs'
                },
                'kind': 'storage',
                'location': LOCATION
            })
        storage_async_operation.wait()
        # List VM in resource group
        print('\nList VMs in resource group')

        # Delete VM
        # print('\nDelete VM')
        # async_vm_delete = compute_client.virtual_machines.delete(
        #     GROUP_NAME, VM_NAME)
        # async_vm_delete.wait()
        return
Пример #16
0
def main():
    template = get_resource_group_details(subscription_id, creds, res_name)
    network_client = NetworkManagementClient(creds, subscription_id)
    for vm in template.vms:
        ni_reference = vm.network_profile.network_interfaces[0]
        ni_reference = ni_reference.id.split('/')
        ni_group = ni_reference[4]
        ni_name = ni_reference[8]

        net_interface = network_client.network_interfaces.get(
            ni_group, ni_name)
        import pdb
        pdb.set_trace()
        private_ip = net_interface.ip_configurations[0].private_ip_address
        vmname = vm.name
Пример #17
0
def delete_azurevnetpeering(rg1, rg2, vnet1, vnet2, peering1, peering2, module,
                            result):
    credentialvars = get_azurecredentials(module, result)
    credentials = ServicePrincipalCredentials(client_id=(credentialvars[1]),
                                              secret=credentialvars[2],
                                              tenant=credentialvars[3])
    network_client = NetworkManagementClient(credentials, credentialvars[0])

    try:
        network_client.virtual_network_peerings.delete(rg1, vnet1, peering1)
        network_client.virtual_network_peerings.delete(rg2, vnet2, peering2)
    except Exception as e:
        module.fail_json(msg="Error: Failed to delete Azure Vnet Peering: " +
                         e.message,
                         **result)
Пример #18
0
def azure_connect_service(service, credentials, region_name=None):
    try:
        if service == 'storageaccounts':
            return StorageManagementClient(credentials.credentials,
                                           credentials.subscription_id)
        elif service == 'sqldatabase':
            return SqlManagementClient(credentials.credentials,
                                       credentials.subscription_id)
        elif service == 'keyvault':
            return KeyVaultManagementClient(credentials.credentials,
                                            credentials.subscription_id)
        elif service == 'appgateway':
            return NetworkManagementClient(credentials.credentials,
                                           credentials.subscription_id)
        elif service == 'network':
            return NetworkManagementClient(credentials.credentials,
                                           credentials.subscription_id)
        elif service == 'rediscache':
            return RedisManagementClient(credentials.credentials,
                                         credentials.subscription_id)
        elif service == 'securitycenter':
            return SecurityCenter(credentials.credentials,
                                  credentials.subscription_id, '')
        elif service == 'appservice':
            return WebSiteManagementClient(credentials.credentials,
                                           credentials.subscription_id)
        elif service == 'loadbalancer':
            return NetworkManagementClient(credentials.credentials,
                                           credentials.subscription_id)
        else:
            print_exception('Service %s not supported' % service)
            return None

    except Exception as e:
        print_exception(e)
        return None
Пример #19
0
    def __init__(self, credentials, subscription_id):
        self.subscription_id = subscription_id

        # Generate user service principal credentials
        self.credentials = credentials

        # Create ARM resource client
        self.resource_group_client = ResourceManagementClient(
            self.credentials, self.subscription_id)
        self.network_client = NetworkManagementClient(self.credentials,
                                                      self.subscription_id)
        self.compute_client = ComputeManagementClient(self.credentials,
                                                      self.subscription_id)

        self.workers_list = []
Пример #20
0
def get_azure_network_client(config):
    from azure.mgmt.network import NetworkManagementClient

    cloud_environment = get_azure_cloud_environment(config)
    credentials = get_azure_credentials(config)

    if cloud_environment:
        try:
            network_client = NetworkManagementClient(
                credentials,
                config.SubscriptionId,
                base_url=cloud_environment.endpoints.resource_manager,
                credential_scopes=[
                    cloud_environment.endpoints.resource_manager + "/.default"
                ])
        except TypeError:
            network_client = NetworkManagementClient(
                credentials,
                config.SubscriptionId,
                base_url=cloud_environment.endpoints.resource_manager)
    else:
        network_client = NetworkManagementClient(credentials,
                                                 config.SubscriptionId)
    return network_client
Пример #21
0
def run_main():
    
    subscription_id = os.environ.get(
        AZURE_SUBSCRIPTION_ID,
        '1111111122222222333333334444444455') # your Azure Subscription Id
    credentials = ServicePrincipalCredentials(
        client_id = AZURE_CLIENT_ID,
        secret = AZURE_CLIENT_SECRET,
        tenant = AZURE_TENANT_ID
    )
    resource_client = ResourceManagementClient(credentials, subscription_id)
    compute_client = ComputeManagementClient(credentials, subscription_id)
    storage_client = StorageManagementClient(credentials, subscription_id)
    network_client = NetworkManagementClient(credentials, subscription_id)

    # Create Resource group
    print('\nCreate Resource Group')
    resource_client.resource_groups.create_or_update(GROUP_NAME, {'location':LOCATION})


    # Create a storage account
    print('\nCreate a storage account')
    storage_async_operation = storage_client.storage_accounts.create(
        GROUP_NAME,
        STORAGE_ACCOUNT_NAME,
        {
            'sku': {'name': 'standard_lrs'},
            'kind': 'storage',
            'location': LOCATION
        }
    )

    storage_async_operation.wait()

     # Create a NIC
    nic = create_nic(network_client)

    # Create Linux VM
    print('\nCreating Red Hat Enterprise Linux Virtual Machine')
    vm_parameters = create_vm_parameters(nic.id, VM_REFERENCE)
    async_vm_creation = compute_client.virtual_machines.create_or_update(
        GROUP_NAME, VM_NAME, vm_parameters)
    async_vm_creation.wait()

    # Start the VM
    print('\nStart VM')
    async_vm_start = compute_client.virtual_machines.start(GROUP_NAME, VM_NAME)
    async_vm_start.wait()
    def __init__(
        self,
        azure_subscription_id,
        azure_tenant_id,
        azure_application_id,
        azure_application_key,
        logger,
    ):
        """Init command.

        :param str azure_subscription_id:
        :param str azure_tenant_id:
        :param str azure_application_id:
        :param str azure_application_key:
        :param str azure_application_key:
        :param logging.Logger logger:
        """
        self._azure_subscription_id = azure_subscription_id
        self._azure_tenant_id = azure_tenant_id
        self._azure_application_id = azure_application_id
        self._azure_application_key = azure_application_key
        self._logger = logger
        self._cached_storage_account_keys = {}

        self._credentials = ServicePrincipalCredentials(
            client_id=azure_application_id,
            secret=azure_application_key,
            tenant=azure_tenant_id,
        )

        self._subscription_client = SubscriptionClient(
            credentials=self._credentials)

        self._resource_client = ResourceManagementClient(
            credentials=self._credentials,
            subscription_id=self._azure_subscription_id)

        self._compute_client = ComputeManagementClient(
            credentials=self._credentials,
            subscription_id=self._azure_subscription_id)

        self._storage_client = StorageManagementClient(
            credentials=self._credentials,
            subscription_id=self._azure_subscription_id)

        self._network_client = NetworkManagementClient(
            credentials=self._credentials,
            subscription_id=self._azure_subscription_id)
Пример #23
0
def main(req: func.HttpRequest) -> func.HttpResponse:
  logging.info('Python HTTP trigger function processed a request')
  tag = "quarantine"

  try:
    req_body = req.get_json()
    tenant = req_body.get('tenant')
    client_id = req_body.get('client_id')
    secret = req_body.get('secret')
    sub_id = req_body.get('subscription_id')
    ip = req_body.get('ip')
    group_name = req_body.get('group_name')
    location = req_body.get('location')
    tag = req_body.get('tag')


  except ValueError:
    logging.info(req.get_body())
    return func.HttpResponse(
      "Wrong body format. Usage:\n{\n" +
        "\ttenant: {{tenant_id}}\n" +
        "\tclient_id: {{client_id}}\n" +
        "\tsecret: {{secret}}\n" +
        "\tsub_id: {{sub_id}}\n" +
        "\tgroup_name: {{group_name}}\n" +
        "\tlocation: francecentral\n" +
        "\ttag: {{tag}}\n" +
        "\tip: 1.1.1.1\n" +
      "}",
      status_code=400
    )

  try:
    credentials = ServicePrincipalCredentials(client_id=client_id, secret=secret, tenant=tenant)

    network_client = NetworkManagementClient(credentials, sub_id)
    compute_client = ComputeManagementClient(credentials, sub_id)

    if(tag_compromised_vm(compute_client, network_client, group_name, location, ip, tag)):
      return func.HttpResponse("Tag added")

  except Exception as e:
    logging.debug(str(e))
    return func.HttpResponse(str(e), status_code=500)

  res = "IP address " + ip + " not found in " + group_name
  logging.info(res)
  return func.HttpResponse(res, status_code=409)
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    VIRTUAL_NETWORK_NAME = "virtualnetwork"

    # Create client
    # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    network_client = NetworkManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # Create virtual network
    network = network_client.virtual_networks.begin_create_or_update(
        GROUP_NAME, VIRTUAL_NETWORK_NAME, {
            "address_space": {
                "address_prefixes": ["10.0.0.0/16"]
            },
            "location": "eastus"
        }).result()
    print("Create virtual network:\n{}".format(network))

    # Get virtual network
    network = network_client.virtual_networks.get(GROUP_NAME,
                                                  VIRTUAL_NETWORK_NAME)
    print("Get virtual network:\n{}".format(network))

    # Update virtual network tags
    network = network_client.virtual_networks.update_tags(
        GROUP_NAME, VIRTUAL_NETWORK_NAME,
        {"tags": {
            "tag1": "value1",
            "tag2": "value2"
        }})
    print("Update virtual network tags:\n{}".format(network))

    # Delete virtual network
    network_client.virtual_networks.begin_delete(
        GROUP_NAME, VIRTUAL_NETWORK_NAME).result()
    print("Delete virtual network.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
Пример #25
0
    def create_nets(self, radl, credentials, subscription_id, group_name):
        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 = {}
            for i, net in enumerate(radl.networks):
                subnet_name = net.id
                net_cidr = net.getValue('cidr')
                if not net_cidr:
                    net_cidr = '10.0.%d.0/24' % i
                # 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)
        else:
            subnets = {}
            for i, net in enumerate(radl.networks):
                subnets[net.id] = network_client.subnets.get(group_name, "privates", net.id)

        return subnets
def delete_nic(request, ressource_id, nic_id):
    ressource = get_object_or_404(Ressources, pk=ressource_id)
    nic = Nic.objects.get(pk=nic_id)

    userCloud = get_object_or_404(UserCloud, user=(request.user))
    subscription_id = userCloud.subscription_id  # your Azure Subscription Id
    credentials = ServicePrincipalCredentials(client_id=userCloud.client_id,
                                              secret=userCloud.secret,
                                              tenant=userCloud.tenant)
    network_client = NetworkManagementClient(credentials, subscription_id)

    async_nic_delete = network_client.network_interfaces.delete(
        nic.ressource.groupe_name, nic.nic_name)
    nic.delete()
    return render(request, 'ressource/detail_ressource.html',
                  {'ressource': ressource})
Пример #27
0
    def __init__(self, provider_config, cluster_name):
        NodeProvider.__init__(self, provider_config, cluster_name)
        subscription_id = provider_config["subscription_id"]
        credential = DefaultAzureCredential(
            exclude_shared_token_cache_credential=True)
        self.compute_client = ComputeManagementClient(credential,
                                                      subscription_id)
        self.network_client = NetworkManagementClient(credential,
                                                      subscription_id)
        self.resource_client = ResourceManagementClient(
            credential, subscription_id)

        self.lock = RLock()

        # cache node objects
        self.cached_nodes = {}
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    SUBNET = "subnetxxyyzz"
    VIRTUAL_NETWORK_NAME = "virtualnetworkxxxyyzz"

    # Create client
    # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    network_client = NetworkManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # Create virtual network
    network_client.virtual_networks.begin_create_or_update(
        GROUP_NAME, VIRTUAL_NETWORK_NAME, {
            "address_space": {
                "address_prefixes": ["10.0.0.0/16"]
            },
            "location": "eastus"
        }).result()

    # Create subnet
    subnet = network_client.subnets.begin_create_or_update(
        GROUP_NAME, VIRTUAL_NETWORK_NAME, SUBNET, {
            "address_prefix": "10.0.0.0/24"
        }).result()
    print("Create subnet:\n{}".format(subnet))

    # Get subnet
    subnet = network_client.subnets.get(GROUP_NAME, VIRTUAL_NETWORK_NAME,
                                        SUBNET)
    print("Get subnet:\n{}".format(subnet))

    # Delete subnet
    subnet = network_client.subnets.begin_delete(GROUP_NAME,
                                                 VIRTUAL_NETWORK_NAME,
                                                 SUBNET).result()
    print("Delete subnet.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def run_action(credentials, rule, entity, params):
    storage_account_name, sa_resource_group_name, network_watcher_name, retention_days, flow_log_name = params
    logging.info(f'{__file__} - run_action started')
    subscription_id = entity.get('accountNumber')
    region = entity.get('region')
    nsg_name = entity.get('name')

    logging.info(
        f'{__file__} - subscription_id : {subscription_id} - nsg_name : {nsg_name}'
    )

    target_resource_path = entity.get('id')
    storage_account_path = '/subscriptions/' + subscription_id + '/resourceGroups/' + sa_resource_group_name + '/providers/Microsoft.Storage/storageAccounts/' + storage_account_name
    if not subscription_id or not credentials:
        msg = 'Error! Subscription id or Resource group name are missing.'
        logging.info(f'{__file__} - {msg}')
        return f'{msg}'

    network_client = NetworkManagementClient(credentials, subscription_id)

    flow_log_parameters = {
        'location': region,
        'target_resource_id': target_resource_path,
        'storage_id': storage_account_path,
        'enabled': True,
        'retention_policy': {
            'days': retention_days,
            'enabled': True
        },
        'format': {
            'type': 'JSON',
            'version': 2
        }
    }

    try:
        network_client.flow_logs.begin_create_or_update(
            nw_resource_group_name, network_watcher_name, flow_log_name,
            flow_log_parameters)
        msg = f'Network Security group flow logs have been enabled on: {nsg_name}'
        logging.info(f'{__file__} - {msg}')
        return f'{msg}'
    except HttpResponseError as e:
        msg = f'unexpected error : {e.message}'
        logging.info(f'{__file__} - {msg}')
        return f'{msg}'
Пример #30
0
def discover_resources(**kwargs):

    discovered_virtual_nets = []

    # 1. Loop through all Azure RHs
    for handler in AzureARMHandler.objects.all():
        set_progress('Connecting to Azure virtual networks \
        for handler: {}'.format(handler))
        credentials = ServicePrincipalCredentials(
            client_id=handler.client_id,
            secret=handler.secret,
            tenant=handler.azure_tenant_id,
        )
        network_client = NetworkManagementClient(credentials,
                                                 handler.serviceaccount)

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

        # 2. Now get all VNets for the current RH
        for resource_group in azure_resources_client.resource_groups.list():
            try:
                for virtual_net in network_client.virtual_networks.list(
                        resource_group_name=resource_group.name):
                    discovered_virtual_nets.append({
                        'name':
                        virtual_net.as_dict()['name'] + " - " +
                        resource_group.name,
                        'azure_virtual_net_name':
                        virtual_net.as_dict()['name'] + " - " +
                        resource_group.name,
                        'vpn_adress_prefixes':
                        ','.join(virtual_net.as_dict()['address_space']
                                 ['address_prefixes']),
                        'azure_location':
                        virtual_net.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
    # 3. Return discovered VNets for all RHs
    return discovered_virtual_nets