コード例 #1
0
 def create_virtual_network(self, network_client, parameters, network_name,
                            subnet_name):
     """ Creates the network resources, such as Virtual network and Subnet.
 Args:
   network_client: A NetworkManagementClient instance.
   parameters:  A dict, containing all the parameters necessary to
     authenticate this user with Azure.
   network_name: The name to use for the Virtual Network resource.
   subnet_name: The name to use for the Subnet resource.
 Returns:
   A Subnet instance from the Virtual Network created.
 """
     group_name = parameters[self.PARAM_RESOURCE_GROUP]
     region = parameters[self.PARAM_ZONE]
     verbose = parameters[self.PARAM_VERBOSE]
     AppScaleLogger.verbose(
         "Creating/Updating the Virtual Network '{}'".format(network_name),
         verbose)
     address_space = AddressSpace(address_prefixes=['10.1.0.0/16'])
     subnet1 = Subnet(name=subnet_name, address_prefix='10.1.0.0/24')
     result = network_client.virtual_networks.create_or_update(
         group_name, network_name,
         VirtualNetwork(location=region,
                        address_space=address_space,
                        subnets=[subnet1]))
     self.sleep_until_update_operation_done(result, network_name, verbose)
     subnet = network_client.subnets.get(group_name, network_name,
                                         subnet_name)
     return subnet
コード例 #2
0
ファイル: account_setup.py プロジェクト: xuzikun2003/aztk
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
コード例 #3
0
    def exec_module(self, **kwargs):

        for key in self.module_arg_spec.keys() + ['tags']:
            setattr(self, key, kwargs[key])

        self.results['check_mode'] = self.check_mode

        resource_group = self.get_resource_group(self.resource_group)
        if not self.location:
            # Set default location
            self.location = resource_group.location

        if not NAME_PATTERN.match(self.name):
            self.fail(
                "Parameter error: name must begin with a letter or number, end with a letter, number "
                "or underscore and may contain only letters, numbers, periods, underscores or hyphens."
            )

        if self.state == 'present' and self.purge_address_prefixes:
            for prefix in self.address_prefixes_cidr:
                if not CIDR_PATTERN.match(prefix):
                    self.fail(
                        "Parameter error: invalid address prefix value {0}".
                        format(prefix))

            if self.dns_servers and len(self.dns_servers) > 2:
                self.fail(
                    "Parameter error: You can provide a maximum of 2 DNS servers."
                )

        changed = False
        results = dict()

        try:
            self.log('Fetching vnet {0}'.format(self.name))
            vnet = self.network_client.virtual_networks.get(
                self.resource_group, self.name)

            results = virtual_network_to_dict(vnet)
            self.log('Vnet exists {0}'.format(self.name))
            self.log(results, pretty_print=True)
            self.check_provisioning_state(vnet, self.state)

            if self.state == 'present':
                if self.address_prefixes_cidr:
                    existing_address_prefix_set = set(
                        vnet.address_space.address_prefixes)
                    requested_address_prefix_set = set(
                        self.address_prefixes_cidr)
                    missing_prefixes = requested_address_prefix_set - existing_address_prefix_set
                    extra_prefixes = existing_address_prefix_set - requested_address_prefix_set
                    if len(missing_prefixes) > 0:
                        self.log('CHANGED: there are missing address_prefixes')
                        changed = True
                        if not self.purge_address_prefixes:
                            # add the missing prefixes
                            for prefix in missing_prefixes:
                                results['address_prefixes'].append(prefix)

                    if len(extra_prefixes) > 0 and self.purge_address_prefixes:
                        self.log(
                            'CHANGED: there are address_prefixes to purge')
                        changed = True
                        # replace existing address prefixes with requested set
                        results[
                            'address_prefixes'] = self.address_prefixes_cidr

                update_tags, results['tags'] = self.update_tags(
                    results['tags'])
                if update_tags:
                    changed = True

                if self.dns_servers:
                    existing_dns_set = set(vnet.dhcp_options.dns_servers)
                    requested_dns_set = set(self.dns_servers)
                    if existing_dns_set != requested_dns_set:
                        self.log('CHANGED: replacing DNS servers')
                        changed = True
                        results['dns_servers'] = self.dns_servers

                if self.purge_dns_servers and vnet.dhcp_options and len(
                        vnet.dhcp_options.dns_servers) > 0:
                    self.log('CHANGED: purging existing DNS servers')
                    changed = True
                    results['dns_servers'] = []
            elif self.state == 'absent':
                self.log(
                    "CHANGED: vnet exists but requested state is 'absent'")
                changed = True
        except CloudError:
            self.log('Vnet {0} does not exist'.format(self.name))
            if self.state == 'present':
                self.log(
                    "CHANGED: vnet {0} does not exist but requested state is 'present'"
                    .format(self.name))
                changed = True

        self.results['changed'] = changed
        self.results['state'] = results

        if self.check_mode:
            return self.results

        if changed:
            if self.state == 'present':
                if not results:
                    # create a new virtual network
                    self.log("Create virtual network {0}".format(self.name))
                    if not self.address_prefixes_cidr:
                        self.fail(
                            'Parameter error: address_prefixes_cidr required when creating a virtual network'
                        )
                    vnet = VirtualNetwork(
                        location=self.location,
                        address_space=AddressSpace(
                            address_prefixes=self.address_prefixes_cidr))
                    if self.dns_servers:
                        vnet.dhcp_options = DhcpOptions(
                            dns_servers=self.dns_servers)
                    if self.tags:
                        vnet.tags = self.tags
                    self.results['state'] = self.create_or_update_vnet(vnet)
                else:
                    # update existing virtual network
                    self.log("Update virtual network {0}".format(self.name))
                    vnet = VirtualNetwork(
                        location=results['location'],
                        address_space=AddressSpace(
                            address_prefixes=results['address_prefixes']),
                        tags=results['tags'])
                    if results.get('dns_servers'):
                        vnet.dhcp_options = DhcpOptions(
                            dns_servers=results['dns_servers'])
                    self.results['state'] = self.create_or_update_vnet(vnet)
            elif self.state == 'absent':
                self.delete_virtual_network()
                self.results['state']['status'] = 'Deleted'

        return self.results
コード例 #4
0
    def create_network_interface(network_client, region, group_name, interface_name,
                                 network_name, subnet_name, ip_name):

        result = network_client.virtual_networks.create_or_update(
            group_name,
            network_name,
            VirtualNetwork(
                location=region,
                address_space=AddressSpace(
                    address_prefixes=[
                        '10.1.0.0/16',
                    ],
                ),
                subnets=[
                    Subnet(
                        name=subnet_name,
                        address_prefix='10.1.0.0/24',
                    ),
                ],
            ),
        )

        print('Creating Virtual Network...')
        result.wait() # async operation

        subnet = network_client.subnets.get(group_name, network_name, subnet_name)
        result = network_client.public_ip_addresses.create_or_update(
            group_name,
            ip_name,
            PublicIPAddress(
                location=region,
                public_ip_allocation_method=IPAllocationMethod.dynamic,
                idle_timeout_in_minutes=4,
            ),
        )

        print('Creating Subnet...')
        result.wait() # async operation

        # Creating Public IP
        public_ip_address = network_client.public_ip_addresses.get(group_name, ip_name)
        public_ip_id = public_ip_address.id

        print('Creating Public IP...')
        result.wait() # async operation

        result = network_client.network_interfaces.create_or_update(
            group_name,
            interface_name,
            NetworkInterface(
                location=region,
                ip_configurations=[
                    NetworkInterfaceIPConfiguration(
                        name='default',
                        private_ip_allocation_method=IPAllocationMethod.dynamic,
                        subnet=subnet,
                        public_ip_address=PublicIPAddress(
                            id=public_ip_id,
                        ),
                    ),
                ],
            ),
        )

        print('Creating Network Interface...')
        result.wait() # async operation

        network_interface = network_client.network_interfaces.get(
            group_name,
            interface_name,
        )

        return network_interface.id