com.microsoft.azure.management.network.Network Java Examples

The following examples show how to use com.microsoft.azure.management.network.Network. 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 check out the related API usage on the sidebar.
Example #1
Source File: NetworkPeeringImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Observable<Network> getRemoteNetworkAsync() {
    final NetworkPeeringImpl self = this;
    if (self.remoteNetwork != null) {
        return Observable.just(self.remoteNetwork);
    } else if (this.isSameSubscription()) {
        // Fetch the remote network if within the same subscription
        return this.manager().networks().getByIdAsync(this.remoteNetworkId())
            .doOnNext(new Action1<Network>() {
                @Override
                public void call(Network network) {
                    self.remoteNetwork = network;
                }
            });
    } else {
        // Otherwise bail out
        self.remoteNetwork = null;
        return Observable.just(null);
    }
}
 
Example #2
Source File: NetworkManager.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
List<Subnet> listAssociatedSubnets(List<SubnetInner> subnetRefs) {
    final Map<String, Network> networks = new HashMap<>();
    final List<Subnet> subnets = new ArrayList<>();

    if (subnetRefs != null) {
        for (SubnetInner subnetRef : subnetRefs) {
            String networkId = ResourceUtils.parentResourceIdFromResourceId(subnetRef.id());
            Network network = networks.get(networkId.toLowerCase());
            if (network == null) {
                network = this.networks().getById(networkId);
                networks.put(networkId.toLowerCase(), network);
            }

            String subnetName = ResourceUtils.nameFromResourceId(subnetRef.id());
            subnets.add(network.subnets().get(subnetName));
        }
    }

    return Collections.unmodifiableList(subnets);
}
 
Example #3
Source File: NetworkManager.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
Subnet getAssociatedSubnet(SubResource subnetRef) {
    if (subnetRef == null) {
        return null;
    }

    String vnetId = ResourceUtils.parentResourceIdFromResourceId(subnetRef.id());
    String subnetName = ResourceUtils.nameFromResourceId(subnetRef.id());

    if (vnetId == null || subnetName == null) {
        return null;
    }

    Network network = this.networks().getById(vnetId);
    if (network == null) {
        return null;
    }

    return network.subnets().get(subnetName);
}
 
Example #4
Source File: AzurePlatformResources.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void addToResultIfRegionsAreMatch(Region region, Map<String, Set<CloudNetwork>> result, Network network) {
    if (network.region() != null) {
        String actualRegionLabel = network.region().label();
        String actualRegionName = network.region().name();

        LOGGER.info("The region label '{}' and the region name '{}' are for Azure network id: {} name: {}",
                actualRegionLabel, actualRegionName, network.id(), network.name());
        if (regionMatch(actualRegionLabel, region) || regionMatch(actualRegionName, region)) {
            CloudNetwork cloudNetwork = convertToCloudNetwork(network);
            result.computeIfAbsent(actualRegionLabel, s -> new HashSet<>()).add(cloudNetwork);
            result.computeIfAbsent(actualRegionName, s -> new HashSet<>()).add(cloudNetwork);
        }
    } else {
        LOGGER.info("Network with id {} and name {} has no region which is not supported by CDP: {}",
                network.id(), network.name(), network);
        throw new BadRequestException(String.format("Network with id %s and name %s has no region which is not supported by CDP.",
                network.id(), network.name()));
    }
}
 
Example #5
Source File: NicIPConfigurationBaseImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public NetworkSecurityGroup getNetworkSecurityGroup() {
    Network network = this.getNetwork();
    if (network == null) {
        return null;
    }

    String subnetName = this.subnetName();
    if (subnetName == null) {
        return null;
    }

    Subnet subnet = network.subnets().get(subnetName);
    if (subnet == null) {
        return null;
    }

    return subnet.getNetworkSecurityGroup();
}
 
Example #6
Source File: TestNetwork.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Network createResource(Networks networks) throws Exception {
    Region region = Region.US_EAST2;
    String groupName = "rg" + this.testId;

    String networkName = SdkContext.randomResourceName("net", 15);

    Network network = networks.define(networkName)
            .withRegion(region)
            .withNewResourceGroup(groupName)
            .withNewDdosProtectionPlan()
            .withVmProtection()
            .create();
    Assert.assertTrue(network.isDdosProtectionEnabled());
    Assert.assertNotNull(network.ddosProtectionPlanId());
    Assert.assertTrue(network.isVmProtectionEnabled());

    return network;
}
 
Example #7
Source File: ManageManagedDisks.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private static Network prepareNetwork(Azure azure, Region region, String rgName) {
    final String vnetName = SdkContext.randomResourceName("vnet", 24);

    Network network = azure.networks().define(vnetName)
            .withRegion(region)
            .withNewResourceGroup(rgName)
            .withAddressSpace("172.16.0.0/16")
            .defineSubnet("subnet1")
            .withAddressPrefix("172.16.1.0/24")
            .attach()
            .create();
    return network;
}
 
Example #8
Source File: AzurePlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private CloudNetwork convertToCloudNetwork(Network network) {
    Set<CloudSubnet> subnets = new HashSet<>();
    for (Entry<String, Subnet> subnet : network.subnets().entrySet()) {
        subnets.add(new CloudSubnet(subnet.getKey(), subnet.getKey(), null, subnet.getValue().addressPrefix()));
    }
    Map<String, Object> properties = new HashMap<>();
    properties.put("addressSpaces", network.addressSpaces());
    properties.put("dnsServerIPs", network.dnsServerIPs());
    properties.put("resourceGroupName", network.resourceGroupName());

    return new CloudNetwork(network.name(), network.id(), subnets, properties);
}
 
Example #9
Source File: TestNetwork.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Network createResource(Networks networks) throws Exception {
    final String newName = "net" + this.testId;
    Region region = Region.US_WEST;
    String groupName = "rg" + this.testId;


    // Create a network
    final Network network = networks.define(newName)
            .withRegion(region)
            .withNewResourceGroup(groupName)
            .withAddressSpace("10.0.0.0/28")
            .withSubnet("subnetA", "10.0.0.0/29")
            .defineSubnet("subnetB")
                .withAddressPrefix("10.0.0.8/29")
                .withAccessFromService(ServiceEndpointType.MICROSOFT_STORAGE)
                .attach()
            .create();

    // Verify address spaces
    Assert.assertEquals(1, network.addressSpaces().size());
    Assert.assertTrue(network.addressSpaces().contains("10.0.0.0/28"));

    // Verify subnets
    Assert.assertEquals(2, network.subnets().size());
    Subnet subnet = network.subnets().get("subnetA");
    Assert.assertEquals("10.0.0.0/29", subnet.addressPrefix());

    subnet = network.subnets().get("subnetB");
    Assert.assertEquals("10.0.0.8/29", subnet.addressPrefix());
    Assert.assertNotNull(subnet.servicesWithAccess());
    Assert.assertTrue(subnet.servicesWithAccess().containsKey(ServiceEndpointType.MICROSOFT_STORAGE));
    Assert.assertTrue(subnet.servicesWithAccess().get(ServiceEndpointType.MICROSOFT_STORAGE).size() > 0);
    return network;
}
 
Example #10
Source File: TestNetwork.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Network updateResource(Network network) throws Exception {
    network.update()
            .withoutDdosProtectionPlan()
            .withoutVmProtection()
            .apply();
    Assert.assertFalse(network.isDdosProtectionEnabled());
    Assert.assertNull(network.ddosProtectionPlanId());
    Assert.assertFalse(network.isVmProtectionEnabled());
    return network;
}
 
Example #11
Source File: NetworkPeeringImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<NetworkPeering> getRemotePeeringAsync() {
    final NetworkPeeringImpl self = this;
    return this.getRemoteNetworkAsync()
        .flatMap(new Func1<Network, Observable<NetworkPeering>>() {
            @Override
            public Observable<NetworkPeering> call(Network remoteNetwork) {
                if (remoteNetwork == null) {
                    return Observable.just(null);
                } else {
                    return remoteNetwork.peerings().getByRemoteNetworkAsync(self.networkId());
                }
            }
        });
}
 
Example #12
Source File: TestNetwork.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Network updateResource(Network network) throws Exception {
    network.updateTags()
            .withoutTag("tag1")
            .withTag("tag2", "value2")
            .applyTags();
    Assert.assertFalse(network.tags().containsKey("tag1"));
    Assert.assertEquals("value2", network.tags().get("tag2"));
    return network;
}
 
Example #13
Source File: TestBatchAIFileServers.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public BatchAIWorkspace createResource(BatchAIWorkspaces workspaces) throws Exception {
    final Region region = Region.EUROPE_WEST;
    final String groupName = SdkContext.randomResourceName("rg", 10);
    final String wsName = SdkContext.randomResourceName("ws", 10);
    final String fsName = SdkContext.randomResourceName("fs", 15);
    final String vnetName = SdkContext.randomResourceName("vnet", 15);
    final String subnetName = "MySubnet";
    final String userName = "tirekicker";

    BatchAIWorkspace workspace = workspaces.define(wsName)
            .withRegion(region)
            .withNewResourceGroup(groupName)
            .create();

    Network network = networks.define(vnetName)
            .withRegion(region)
            .withExistingResourceGroup(groupName)
            .withAddressSpace("192.168.0.0/16")
            .withSubnet(subnetName, "192.168.200.0/24")
            .create();

    BatchAIFileServer fileServer = workspace.fileServers().define(fsName)
            .withDataDisks(10, 2, StorageAccountType.STANDARD_LRS, CachingType.READWRITE)
            .withVMSize(VirtualMachineSizeTypes.STANDARD_D1_V2.toString())
            .withUserName(userName)
            .withPassword("MyPassword!")
            .withSubnet(network.id(), subnetName)
            .create();

    Assert.assertEquals(network.id() + "/subnets/" + subnetName, fileServer.subnet().id());
    Assert.assertEquals(CachingType.READWRITE, fileServer.dataDisks().cachingType());
    return workspace;
}
 
Example #14
Source File: TestVirtualNetworkGateway.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public VirtualNetworkGateway createResource(final VirtualNetworkGateways gateways) throws Exception {

    // Create virtual network gateway
    initializeResourceNames();

    Network network = gateways.manager().networks().define(NETWORK_NAME)
            .withRegion(REGION)
            .withNewResourceGroup(GROUP_NAME)
            .withAddressSpace("192.168.0.0/16")
            .withAddressSpace("10.254.0.0/16")
            .withSubnet("GatewaySubnet", "192.168.200.0/24")
            .withSubnet("FrontEnd", "192.168.1.0/24")
            .withSubnet("BackEnd", "10.254.1.0/24")
            .create();
    VirtualNetworkGateway vngw1 = gateways.define(GATEWAY_NAME1)
            .withRegion(REGION)
            .withExistingResourceGroup(GROUP_NAME)
            .withExistingNetwork(network)
            .withRouteBasedVpn()
            .withSku(VirtualNetworkGatewaySkuName.VPN_GW1)
            .create();

    vngw1.update()
            .definePointToSiteConfiguration()
                .withAddressPool("172.16.201.0/24")
                .withAzureCertificateFromFile(CERTIFICATE_NAME, new File(getClass().getClassLoader().getResource(CERTIFICATE_NAME).getFile()))
                .attach()
            .apply();

    Assert.assertNotNull(vngw1.vpnClientConfiguration());
    Assert.assertEquals("172.16.201.0/24", vngw1.vpnClientConfiguration().vpnClientAddressPool().addressPrefixes().get(0));
    Assert.assertEquals(1, vngw1.vpnClientConfiguration().vpnClientRootCertificates().size());
    Assert.assertEquals(CERTIFICATE_NAME, vngw1.vpnClientConfiguration().vpnClientRootCertificates().get(0).name());
    String profile = vngw1.generateVpnProfile();
    System.out.println(profile);
    return vngw1;
}
 
Example #15
Source File: NetworkPeeringsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<NetworkPeering> getByRemoteNetworkAsync(Network network) {
    if (network != null) {
        return this.getByRemoteNetworkAsync(network.id());
    } else {
        return Observable.just(null);
    }
}
 
Example #16
Source File: NicIPConfigurationImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NicIPConfigurationImpl withNewNetwork(String name, String addressSpaceCidr) {
    Network.DefinitionStages.WithGroup definitionWithGroup = this.networkManager.networks()
            .define(name)
            .withRegion(this.parent().regionName());

    Network.DefinitionStages.WithCreate definitionAfterGroup;
    if (this.parent().newGroup() != null) {
        definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.parent().newGroup());
    } else {
        definitionAfterGroup = definitionWithGroup.withExistingResourceGroup(this.parent().resourceGroupName());
    }
    return withNewNetwork(definitionAfterGroup.withAddressSpace(addressSpaceCidr));
}
 
Example #17
Source File: NicIPConfigurationImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Gets the subnet to associate with the IP configuration.
 * <p>
 * This method will never return null as subnet is required for a IP configuration, in case of
 * update mode if user didn't choose to change the subnet then existing subnet will be returned.
 * Updating the nic subnet has a restriction, the new subnet must reside in the same virtual network
 * as the current one.
 *
 * @return the subnet resource
 */
private SubnetInner subnetToAssociate() {
    SubnetInner subnetInner = new SubnetInner();
    if (this.isInCreateMode) {
        if (this.creatableVirtualNetworkKey != null) {
            Network network = (Network) parent().createdDependencyResource(this.creatableVirtualNetworkKey);
            subnetInner.withId(network.inner().subnets().get(0).id());
            return subnetInner;
        }

        for (SubnetInner subnet : this.existingVirtualNetworkToAssociate.inner().subnets()) {
            if (subnet.name().equalsIgnoreCase(this.subnetToAssociate)) {
                subnetInner.withId(subnet.id());
                return subnetInner;
            }
        }

        throw new RuntimeException("A subnet with name '" + subnetToAssociate + "' not found under the network '" + this.existingVirtualNetworkToAssociate.name() + "'");

    } else {
        if (subnetToAssociate != null) {
            int idx = this.inner().subnet().id().lastIndexOf('/');
            subnetInner.withId(this.inner().subnet().id().substring(0, idx + 1) + subnetToAssociate);
        } else {
            subnetInner.withId(this.inner().subnet().id());
        }
        return subnetInner;
    }
}
 
Example #18
Source File: VirtualNetworkGatewayImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public VirtualNetworkGatewayImpl withNewNetwork(String name, String addressSpace, String subnetAddressSpaceCidr) {
    Network.DefinitionStages.WithGroup definitionWithGroup = this.manager().networks()
            .define(name)
            .withRegion(this.regionName());

    Network.DefinitionStages.WithCreate definitionAfterGroup;
    if (this.newGroup() != null) {
        definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.newGroup());
    } else {
        definitionAfterGroup = definitionWithGroup.withExistingResourceGroup(this.resourceGroupName());
    }
    Creatable<Network> network = definitionAfterGroup.withAddressSpace(addressSpace).withSubnet(GATEWAY_SUBNET, subnetAddressSpaceCidr);
    return withNewNetwork(network);
}
 
Example #19
Source File: ApplicationGatewayImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private Creatable<Network> ensureDefaultNetworkDefinition() {
    if (this.creatableNetwork == null) {
        final String vnetName = SdkContext.randomResourceName("vnet", 10);
        this.creatableNetwork = this.manager().networks().define(vnetName)
                .withRegion(this.region())
                .withExistingResourceGroup(this.resourceGroupName())
                .withAddressSpace("10.0.0.0/24")
                .withSubnet(DEFAULT, "10.0.0.0/25")
                .withSubnet("apps", "10.0.0.128/25");
    }

    return this.creatableNetwork;
}
 
Example #20
Source File: NetworkImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Network> refreshAsync() {
    return super.refreshAsync().map(new Func1<Network, Network>() {
        @Override
        public Network call(Network network) {
            NetworkImpl impl = (NetworkImpl) network;
            impl.initializeChildrenFromInner();
            return impl;
        }
    });
}
 
Example #21
Source File: NetworkPeeringImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NetworkPeeringImpl withRemoteNetwork(Network network) {
    if (network != null) {
        this.remoteNetwork = network;
        return this.withRemoteNetwork(network.id());
    }
    return this;
}
 
Example #22
Source File: NetworkInventoryCollector.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public List<NetworkVH> fetchNetworkDetails(SubscriptionVH subscription, Map<String, Map<String, String>> tagMap) {
	List<NetworkVH> networkList = new ArrayList<>();

	Azure azure = azureCredentialProvider.getClient(subscription.getTenant(),subscription.getSubscriptionId());
	PagedList<Network> networks = azure.networks().list();

	for (Network network : networks) {
		NetworkVH networkVH = new NetworkVH();
		networkVH.setAddressSpaces(network.addressSpaces());
		networkVH.setDdosProtectionPlanId(network.ddosProtectionPlanId());
		networkVH.setDnsServerIPs(network.dnsServerIPs());
		networkVH.setHashCode(network.hashCode());
		networkVH.setId(network.id());
		networkVH.setDdosProtectionEnabled(network.isDdosProtectionEnabled());
		networkVH.setVmProtectionEnabled(network.isVmProtectionEnabled());
		networkVH.setKey(network.key());
		networkVH.setName(network.name());
		networkVH.setRegion(network.region().name());
		networkVH.setResourceGroupName(network.resourceGroupName());
		networkVH.setTags(Util.tagsList(tagMap, network.resourceGroupName(), network.tags()));
		networkVH.setSubscription(subscription.getSubscriptionId());
		networkVH.setSubscriptionName(subscription.getSubscriptionName());
		networkList.add(networkVH);
	}
	log.info("Target Type : {}  Total: {} ","vnet",networkList.size());
	return networkList;
}
 
Example #23
Source File: TestNetwork.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Network createResource(Networks networks) throws Exception {
    Region region = Region.US_SOUTH_CENTRAL;
    String groupName = "rg" + this.testId;

    String networkName = SdkContext.randomResourceName("net", 15);

    Network network = networks.define(networkName)
            .withRegion(region)
            .withNewResourceGroup(groupName)
            .withTag("tag1", "value1")
            .create();
    Assert.assertEquals("value1", network.tags().get("tag1"));
    return network;
}
 
Example #24
Source File: VirtualMachineOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception {
    String vmNamePrefix = "vmz";
    String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
    String networkNamePrefix = generateRandomResourceName("vnet-", 15);
    int count = 5;

    final Set<String> virtualMachineNames = new HashSet<>();
    for (int i = 0; i < count; i++) {
        virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
    }

    final Set<String> networkNames = new HashSet<>();
    for (int i = 0; i < count; i++) {
        networkNames.add(String.format("%s-%d", networkNamePrefix, i));
    }

    final Set<String> publicIPAddressNames = new HashSet<>();
    for (int i = 0; i < count; i++) {
        publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
    }

    final CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(REGION,
            vmNamePrefix,
            networkNamePrefix,
            publicIpNamePrefix,
            count);
    final AtomicInteger resourceCount = new AtomicInteger(0);
    List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
    computeManager.virtualMachines().createAsync(virtualMachineCreatables)
            .map(new Func1<Indexable, Indexable>() {
                @Override
                public Indexable call(Indexable createdResource) {
                    if (createdResource instanceof Resource) {
                        Resource resource = (Resource) createdResource;
                        System.out.println("Created: " + resource.id());
                        if (resource instanceof VirtualMachine) {
                            VirtualMachine virtualMachine = (VirtualMachine) resource;
                            Assert.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
                            Assert.assertNotNull(virtualMachine.id());
                        } else if (resource instanceof Network) {
                            Network network = (Network) resource;
                            Assert.assertTrue(networkNames.contains(network.name()));
                            Assert.assertNotNull(network.id());
                        } else if (resource instanceof PublicIPAddress) {
                            PublicIPAddress publicIPAddress = (PublicIPAddress) resource;
                            Assert.assertTrue(publicIPAddressNames.contains(publicIPAddress.name()));
                            Assert.assertNotNull(publicIPAddress.id());
                        }
                    }
                    resourceCount.incrementAndGet();
                    return createdResource;
                }
            }).toBlocking().last();
    // 1 resource group, 1 storage, 5 network, 5 publicIp, 5 nic, 5 virtual machines
    // Additional one for CreatableUpdatableResourceRoot.
    // TODO - ans - We should not emit CreatableUpdatableResourceRoot.
    Assert.assertEquals(resourceCount.get(), 23);
}
 
Example #25
Source File: AzureClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public Subnet getSubnetProperties(String resourceGroup, String virtualNetwork, String subnet) {
    return handleAuthException(() -> {
        Network networkByResourceGroup = getNetworkByResourceGroup(resourceGroup, virtualNetwork);
        return networkByResourceGroup == null ? null : networkByResourceGroup.subnets().get(subnet);
    });
}
 
Example #26
Source File: VirtualMachineOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
private CreatablesInfo prepareCreatableVirtualMachines(Region region,
                                                       String vmNamePrefix,
                                                       String networkNamePrefix,
                                                       String publicIpNamePrefix,
                                                       int vmCount) {

    Creatable<ResourceGroup> resourceGroupCreatable = resourceManager.resourceGroups()
            .define(RG_NAME)
            .withRegion(region);

    Creatable<StorageAccount> storageAccountCreatable = storageManager.storageAccounts()
            .define(generateRandomResourceName("stg", 20))
            .withRegion(region)
            .withNewResourceGroup(resourceGroupCreatable);

    List<String> networkCreatableKeys = new ArrayList<>();
    List<String> publicIpCreatableKeys = new ArrayList<>();
    List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>();
    for (int i = 0; i < vmCount; i++) {
        Creatable<Network> networkCreatable = networkManager.networks()
                .define(String.format("%s-%d", networkNamePrefix, i))
                .withRegion(region)
                .withNewResourceGroup(resourceGroupCreatable)
                .withAddressSpace("10.0.0.0/28");
        networkCreatableKeys.add(networkCreatable.key());

        Creatable<PublicIPAddress> publicIPAddressCreatable = networkManager.publicIPAddresses()
                .define(String.format("%s-%d", publicIpNamePrefix, i))
                .withRegion(region)
                .withNewResourceGroup(resourceGroupCreatable);
        publicIpCreatableKeys.add(publicIPAddressCreatable.key());


        Creatable<VirtualMachine> virtualMachineCreatable = computeManager.virtualMachines()
                .define(String.format("%s-%d", vmNamePrefix, i))
                .withRegion(region)
                .withNewResourceGroup(resourceGroupCreatable)
                .withNewPrimaryNetwork(networkCreatable)
                .withPrimaryPrivateIPAddressDynamic()
                .withNewPrimaryPublicIPAddress(publicIPAddressCreatable)
                .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                .withRootUsername("tirekicker")
                .withRootPassword("BaR@12!#")
                .withUnmanagedDisks()
                .withNewStorageAccount(storageAccountCreatable);

        virtualMachineCreatables.add(virtualMachineCreatable);
    }
    CreatablesInfo creatablesInfo = new CreatablesInfo();
    creatablesInfo.virtualMachineCreatables = virtualMachineCreatables;
    creatablesInfo.networkCreatableKeys = networkCreatableKeys;
    creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys;
    return creatablesInfo;
}
 
Example #27
Source File: NicIPConfigurationImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public NicIPConfigurationImpl withExistingNetwork(Network network) {
    this.existingVirtualNetworkToAssociate = network;
    return this;
}
 
Example #28
Source File: VirtualMachineScaleSetOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canCreateVirtualMachineScaleSetWithCustomScriptExtension() throws Exception {
    final String vmssName = generateRandomResourceName("vmss", 10);
    final String uname = "jvuser";
    final String password = "123OData!@#123";
    final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Samples/Asset/install_apache.sh";
    final String installCommand = "bash install_apache.sh Abc.123x(";
    List<String> fileUris = new ArrayList<>();
    fileUris.add(apacheInstallScript);

    ResourceGroup resourceGroup = this.resourceManager.resourceGroups()
            .define(RG_NAME)
            .withRegion(REGION)
            .create();

    Network network = this.networkManager
            .networks()
            .define(generateRandomResourceName("vmssvnet", 15))
            .withRegion(REGION)
            .withExistingResourceGroup(resourceGroup)
            .withAddressSpace("10.0.0.0/28")
            .withSubnet("subnet1", "10.0.0.0/28")
            .create();

    LoadBalancer publicLoadBalancer = createHttpLoadBalancers(REGION, resourceGroup, "1");
    VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets().define(vmssName)
            .withRegion(REGION)
            .withExistingResourceGroup(resourceGroup)
            .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0)
            .withExistingPrimaryNetworkSubnet(network, "subnet1")
            .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer)
            .withoutPrimaryInternalLoadBalancer()
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername(uname)
            .withRootPassword(password)
            .withUnmanagedDisks()
            .withNewStorageAccount(generateRandomResourceName("stg", 15))
            .withNewStorageAccount(generateRandomResourceName("stg", 15))
            .defineNewExtension("CustomScriptForLinux")
            .withPublisher("Microsoft.OSTCExtensions")
            .withType("CustomScriptForLinux")
            .withVersion("1.4")
            .withMinorVersionAutoUpgrade()
            .withPublicSetting("fileUris",fileUris)
            .withPublicSetting("commandToExecute", installCommand)
            .attach()
            .withUpgradeMode(UpgradeMode.MANUAL)
            .create();

    checkVMInstances(virtualMachineScaleSet);

    List<String> publicIPAddressIds = virtualMachineScaleSet.primaryPublicIPAddressIds();
    PublicIPAddress publicIPAddress = this.networkManager.publicIPAddresses()
            .getById(publicIPAddressIds.get(0));

    String fqdn = publicIPAddress.fqdn();
    // Assert public load balancing connection
    if (!isPlaybackMode()) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://" + fqdn)
                .build();
        Response response = client.newCall(request).execute();
        Assert.assertEquals(response.code(), 200);
    }

    // Check SSH to VM instances via Nat rule
    //
    for (VirtualMachineScaleSetVM vm : virtualMachineScaleSet.virtualMachines().list()) {
        PagedList<VirtualMachineScaleSetNetworkInterface> networkInterfaces = vm.listNetworkInterfaces();
        Assert.assertEquals(networkInterfaces.size(), 1);
        VirtualMachineScaleSetNetworkInterface networkInterface = networkInterfaces.get(0);
        VirtualMachineScaleSetNicIPConfiguration primaryIpConfig = null;
        primaryIpConfig = networkInterface.primaryIPConfiguration();
        Assert.assertNotNull(primaryIpConfig);
        Integer sshFrontendPort = null;
        List<LoadBalancerInboundNatRule> natRules = primaryIpConfig.listAssociatedLoadBalancerInboundNatRules();
        for (LoadBalancerInboundNatRule natRule : natRules) {
            if (natRule.backendPort() == 22) {
                sshFrontendPort = natRule.frontendPort();
                break;
            }
        }
        Assert.assertNotNull(sshFrontendPort);

        this.sleep(1000 * 60); // Wait some time for VM to be available
        this.ensureCanDoSsh(fqdn, sshFrontendPort, uname, password);
    }
}
 
Example #29
Source File: VirtualNetworkGatewayImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public VirtualNetworkGatewayImpl withNewNetwork(Creatable<Network> creatable) {
    this.creatableNetwork = creatable;
    return this;
}
 
Example #30
Source File: VirtualMachineOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception {
    String vmNamePrefix = "vmz";
    String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
    String networkNamePrefix = generateRandomResourceName("vnet-", 15);
    int count = 5;

    CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(REGION,
            vmNamePrefix,
            networkNamePrefix,
            publicIpNamePrefix,
            count);
    List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
    List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys;
    List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys;

    CreatedResources<VirtualMachine> createdVirtualMachines = computeManager.virtualMachines().create(virtualMachineCreatables);
    Assert.assertTrue(createdVirtualMachines.size() == count);

    Set<String> virtualMachineNames = new HashSet<>();
    for (int i = 0; i < count; i++) {
        virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
    }
    for (VirtualMachine virtualMachine : createdVirtualMachines.values()) {
        Assert.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
        Assert.assertNotNull(virtualMachine.id());
    }

    Set<String> networkNames = new HashSet<>();
    for (int i = 0; i < count; i++) {
        networkNames.add(String.format("%s-%d", networkNamePrefix, i));
    }
    for (String networkCreatableKey : networkCreatableKeys) {
        Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey);
        Assert.assertNotNull(createdNetwork);
        Assert.assertTrue(networkNames.contains(createdNetwork.name()));
    }

    Set<String> publicIPAddressNames = new HashSet<>();
    for (int i = 0; i < count; i++) {
        publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
    }
    for (String publicIpCreatableKey : publicIpCreatableKeys) {
        PublicIPAddress createdPublicIPAddress = (PublicIPAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey);
        Assert.assertNotNull(createdPublicIPAddress);
        Assert.assertTrue(publicIPAddressNames.contains(createdPublicIPAddress.name()));
    }
}