use of com.microsoft.azure.management.network.Network in project azure-sdk-for-java by Azure.
the class ManageApplicationGateway method runSample.
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
public static boolean runSample(Azure azure) {
final String rgName = SdkContext.randomResourceName("rgNEAG", 15);
final String pipName = SdkContext.randomResourceName("pip" + "-", 18);
final String userName = "tirekicker";
final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com";
int backendPools = 2;
int vmCountInAPool = 4;
Region[] regions = { Region.US_EAST, Region.UK_WEST };
String[] addressSpaces = { "172.16.0.0/16", "172.17.0.0/16" };
String[][] publicIpCreatableKeys = new String[backendPools][vmCountInAPool];
String[][] ipAddresses = new String[backendPools][vmCountInAPool];
try {
//=============================================================
// Create a resource group (Where all resources gets created)
//
ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST).create();
System.out.println("Created a new resource group - " + resourceGroup.id());
//=============================================================
// Create a public IP address for the Application Gateway
System.out.println("Creating a public IP address for the application gateway ...");
PublicIPAddress publicIPAddress = azure.publicIPAddresses().define(pipName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).create();
System.out.println("Created a public IP address");
// Print the virtual network details
Utils.print(publicIPAddress);
//=============================================================
// Create backend pools
// Prepare a batch of Creatable definitions
List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
for (int i = 0; i < backendPools; i++) {
//=============================================================
// Create 1 network creatable per region
// Prepare Creatable Network definition (Where all the virtual machines get added to)
String networkName = SdkContext.randomResourceName("vnetNEAG-", 20);
Creatable<Network> networkCreatable = azure.networks().define(networkName).withRegion(regions[i]).withExistingResourceGroup(resourceGroup).withAddressSpace(addressSpaces[i]);
//=============================================================
// Create 1 storage creatable per region (For storing VMs disk)
String storageAccountName = SdkContext.randomResourceName("stgneag", 20);
Creatable<StorageAccount> storageAccountCreatable = azure.storageAccounts().define(storageAccountName).withRegion(regions[i]).withExistingResourceGroup(resourceGroup);
String linuxVMNamePrefix = SdkContext.randomResourceName("vm-", 15);
for (int j = 0; j < vmCountInAPool; j++) {
//=============================================================
// Create 1 public IP address creatable
Creatable<PublicIPAddress> publicIPAddressCreatable = azure.publicIPAddresses().define(String.format("%s-%d", linuxVMNamePrefix, j)).withRegion(regions[i]).withExistingResourceGroup(resourceGroup).withLeafDomainLabel(String.format("%s-%d", linuxVMNamePrefix, j));
publicIpCreatableKeys[i][j] = publicIPAddressCreatable.key();
//=============================================================
// Create 1 virtual machine creatable
Creatable<VirtualMachine> virtualMachineCreatable = azure.virtualMachines().define(String.format("%s-%d", linuxVMNamePrefix, j)).withRegion(regions[i]).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork(networkCreatable).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressCreatable).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2).withNewStorageAccount(storageAccountCreatable);
creatableVirtualMachines.add(virtualMachineCreatable);
}
}
//=============================================================
// Create two backend pools of virtual machines
StopWatch stopwatch = new StopWatch();
System.out.println("Creating virtual machines (two backend pools)");
stopwatch.start();
CreatedResources<VirtualMachine> virtualMachines = azure.virtualMachines().create(creatableVirtualMachines);
stopwatch.stop();
System.out.println("Created virtual machines (two backend pools)");
for (VirtualMachine virtualMachine : virtualMachines.values()) {
System.out.println(virtualMachine.id());
}
System.out.println("Virtual machines created: (took " + (stopwatch.getTime() / 1000) + " seconds) to create == " + virtualMachines.size() + " == virtual machines (4 virtual machines per backend pool)");
//=======================================================================
// Get IP addresses from created resources
System.out.println("IP Addresses in the backend pools are - ");
for (int i = 0; i < backendPools; i++) {
for (int j = 0; j < vmCountInAPool; j++) {
PublicIPAddress pip = (PublicIPAddress) virtualMachines.createdRelatedResource(publicIpCreatableKeys[i][j]);
pip.refresh();
ipAddresses[i][j] = pip.ipAddress();
System.out.println(String.format("[backend pool = %d][vm = %d] = %s", i, j, ipAddresses[i][j]));
}
System.out.println("======");
}
//=======================================================================
// Create an application gateway
System.out.println("================= CREATE ======================");
System.out.println("Creating an application gateway");
stopwatch.reset();
stopwatch.start();
final String sslCertificatePfxPath = ManageApplicationGateway.class.getClassLoader().getResource("myTest._pfx").getPath();
final String sslCertificatePfxPath2 = ManageApplicationGateway.class.getClassLoader().getResource("myTest2._pfx").getPath();
ApplicationGateway applicationGateway = azure.applicationGateways().define("myFirstAppGateway").withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).defineRequestRoutingRule("HTTP-80-to-8080").fromPublicFrontend().fromFrontendHttpPort(80).toBackendHttpPort(8080).toBackendIPAddress(ipAddresses[0][0]).toBackendIPAddress(ipAddresses[0][1]).toBackendIPAddress(ipAddresses[0][2]).toBackendIPAddress(ipAddresses[0][3]).attach().defineRequestRoutingRule("HTTPs-443-to-8080").fromPublicFrontend().fromFrontendHttpsPort(443).withSslCertificateFromPfxFile(new File(sslCertificatePfxPath)).withSslCertificatePassword("Abc123").toBackendHttpPort(8080).toBackendIPAddress(ipAddresses[1][0]).toBackendIPAddress(ipAddresses[1][1]).toBackendIPAddress(ipAddresses[1][2]).toBackendIPAddress(ipAddresses[1][3]).attach().withExistingPublicIPAddress(publicIPAddress).create();
stopwatch.stop();
System.out.println("Application gateway created: (took " + (stopwatch.getTime() / 1000) + " seconds)");
Utils.print(applicationGateway);
//=======================================================================
// Update an application gateway
// configure the first routing rule for SSL offload
System.out.println("================= UPDATE ======================");
System.out.println("Updating the application gateway");
stopwatch.reset();
stopwatch.start();
applicationGateway.update().withoutRequestRoutingRule("HTTP-80-to-8080").defineRequestRoutingRule("HTTPs-1443-to-8080").fromPublicFrontend().fromFrontendHttpsPort(1443).withSslCertificateFromPfxFile(new File(sslCertificatePfxPath2)).withSslCertificatePassword("Abc123").toBackendHttpPort(8080).toBackendIPAddress(ipAddresses[0][0]).toBackendIPAddress(ipAddresses[0][1]).toBackendIPAddress(ipAddresses[0][2]).toBackendIPAddress(ipAddresses[0][3]).withHostName("www.contoso.com").withCookieBasedAffinity().attach().apply();
stopwatch.stop();
System.out.println("Application gateway updated: (took " + (stopwatch.getTime() / 1000) + " seconds)");
Utils.print(applicationGateway);
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().deleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
return false;
}
use of com.microsoft.azure.management.network.Network in project azure-sdk-for-java by Azure.
the class ManageVirtualMachineWithUnmanagedDisks method runSample.
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
public static boolean runSample(Azure azure) {
final Region region = Region.US_WEST_CENTRAL;
final String windowsVMName = Utils.createRandomName("wVM");
final String linuxVMName = Utils.createRandomName("lVM");
final String rgName = Utils.createRandomName("rgCOMV");
final String userName = "tirekicker";
final String password = "12NewPA$$w0rd!";
final String dataDiskName = "disk2";
try {
//=============================================================
// Create a Windows virtual machine
System.out.println("Creating a Windows VM");
Date t1 = new Date();
VirtualMachine windowsVM = azure.virtualMachines().define(windowsVMName).withRegion(region).withNewResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(userName).withAdminPassword(password).withUnmanagedDisks().withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
Date t2 = new Date();
System.out.println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + windowsVM.id());
// Print virtual machine details
Utils.print(windowsVM);
//=============================================================
// Update - Tag the virtual machine
windowsVM.update().withTag("who-rocks", "java").withTag("where", "on azure").apply();
System.out.println("Tagged VM: " + windowsVM.id());
//=============================================================
// Update - Attach data disks
windowsVM.update().withNewUnmanagedDataDisk(10).defineUnmanagedDataDisk(dataDiskName).withNewVhd(20).withCaching(CachingTypes.READ_WRITE).attach().apply();
System.out.println("Attached a new data disk" + dataDiskName + " to VM" + windowsVM.id());
Utils.print(windowsVM);
//=============================================================
// Update - detach data disk
windowsVM.update().withoutUnmanagedDataDisk(dataDiskName).apply();
System.out.println("Detached data disk " + dataDiskName + " from VM " + windowsVM.id());
//=============================================================
// Update - Resize (expand) the data disk
// First, deallocate the virtual machine and then proceed with resize
System.out.println("De-allocating VM: " + windowsVM.id());
windowsVM.deallocate();
System.out.println("De-allocated VM: " + windowsVM.id());
VirtualMachineUnmanagedDataDisk dataDisk = windowsVM.unmanagedDataDisks().get(0);
windowsVM.update().updateUnmanagedDataDisk(dataDisk.name()).withSizeInGB(30).parent().apply();
System.out.println("Expanded VM " + windowsVM.id() + "'s data disk to 30GB");
//=============================================================
// Update - Expand the OS drive size by 10 GB
int osDiskSizeInGb = windowsVM.osDiskSize();
if (osDiskSizeInGb == 0) {
// Server is not returning the OS Disk size, possible bug in server
System.out.println("Server is not returning the OS disk size, possible bug in the server?");
System.out.println("Assuming that the OS disk size is 256 GB");
osDiskSizeInGb = 256;
}
windowsVM.update().withOSDiskSizeInGB(osDiskSizeInGb + 10).apply();
System.out.println("Expanded VM " + windowsVM.id() + "'s OS disk to " + (osDiskSizeInGb + 10));
//=============================================================
// Start the virtual machine
System.out.println("Starting VM " + windowsVM.id());
windowsVM.start();
System.out.println("Started VM: " + windowsVM.id() + "; state = " + windowsVM.powerState());
//=============================================================
// Restart the virtual machine
System.out.println("Restarting VM: " + windowsVM.id());
windowsVM.restart();
System.out.println("Restarted VM: " + windowsVM.id() + "; state = " + windowsVM.powerState());
//=============================================================
// Stop (powerOff) the virtual machine
System.out.println("Powering OFF VM: " + windowsVM.id());
windowsVM.powerOff();
System.out.println("Powered OFF VM: " + windowsVM.id() + "; state = " + windowsVM.powerState());
// Get the network where Windows VM is hosted
Network network = windowsVM.getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork();
//=============================================================
// Create a Linux VM in the same virtual network
System.out.println("Creating a Linux VM in the network");
VirtualMachine linuxVM = azure.virtualMachines().define(linuxVMName).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet(// Referencing the default subnet name when no name specified at creation
"subnet1").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withUnmanagedDisks().withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
System.out.println("Created a Linux VM (in the same virtual network): " + linuxVM.id());
Utils.print(linuxVM);
//=============================================================
// List virtual machines in the resource group
String resourceGroupName = windowsVM.resourceGroupName();
System.out.println("Printing list of VMs =======");
for (VirtualMachine virtualMachine : azure.virtualMachines().listByResourceGroup(resourceGroupName)) {
Utils.print(virtualMachine);
}
//=============================================================
// Delete the virtual machine
System.out.println("Deleting VM: " + windowsVM.id());
azure.virtualMachines().deleteById(windowsVM.id());
System.out.println("Deleted VM: " + windowsVM.id());
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().deleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
return false;
}
use of com.microsoft.azure.management.network.Network in project azure-tools-for-java by Microsoft.
the class AzureSDKManager method createVirtualMachine.
public static VirtualMachine createVirtualMachine(String subscriptionId, @NotNull String name, @NotNull String resourceGroup, boolean withNewResourceGroup, @NotNull String size, @NotNull String region, final VirtualMachineImage vmImage, Object knownImage, boolean isKnownImage, final StorageAccount storageAccount, com.microsoft.tooling.msservices.model.storage.StorageAccount newStorageAccount, boolean withNewStorageAccount, final Network network, VirtualNetwork newNetwork, boolean withNewNetwork, @NotNull String subnet, @Nullable PublicIPAddress pip, boolean withNewPip, @Nullable AvailabilitySet availabilitySet, boolean withNewAvailabilitySet, @NotNull final String username, @Nullable final String password, @Nullable String publicKey) throws Exception {
AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
Azure azure = azureManager.getAzure(subscriptionId);
boolean isWindows;
if (isKnownImage) {
isWindows = knownImage instanceof KnownWindowsVirtualMachineImage;
} else {
isWindows = vmImage.osDiskImage().operatingSystem().equals(OperatingSystemTypes.WINDOWS);
}
// ------ Resource Group ------
VirtualMachine.DefinitionStages.WithGroup withGroup = azure.virtualMachines().define(name).withRegion(region);
Creatable<ResourceGroup> newResourceGroup = null;
VirtualMachine.DefinitionStages.WithNetwork withNetwork;
if (withNewResourceGroup) {
newResourceGroup = azure.resourceGroups().define(resourceGroup).withRegion(region);
withNetwork = withGroup.withNewResourceGroup(newResourceGroup);
} else {
withNetwork = withGroup.withExistingResourceGroup(resourceGroup);
}
// ------ Virtual Network -----
VirtualMachine.DefinitionStages.WithPublicIPAddress withPublicIpAddress;
if (withNewNetwork) {
Network.DefinitionStages.WithGroup networkWithGroup = azure.networks().define(newNetwork.name).withRegion(region);
Creatable<Network> newVirtualNetwork;
if (withNewResourceGroup) {
newVirtualNetwork = networkWithGroup.withNewResourceGroup(newResourceGroup).withAddressSpace(newNetwork.addressSpace).withSubnet(newNetwork.subnet.name, newNetwork.subnet.addressSpace);
} else {
newVirtualNetwork = networkWithGroup.withExistingResourceGroup(resourceGroup).withAddressSpace(newNetwork.addressSpace).withSubnet(newNetwork.subnet.name, newNetwork.subnet.addressSpace);
}
withPublicIpAddress = withNetwork.withNewPrimaryNetwork(newVirtualNetwork).withPrimaryPrivateIPAddressDynamic();
// withPublicIpAddress = withNetwork.withNewPrimaryNetwork("10.0.0.0/28").
// .withPrimaryPrivateIpAddressDynamic();
} else {
withPublicIpAddress = withNetwork.withExistingPrimaryNetwork(network).withSubnet(subnet).withPrimaryPrivateIPAddressDynamic();
}
// ------ Public IP Address------
VirtualMachine.DefinitionStages.WithOS withOS;
if (pip == null) {
if (withNewPip) {
withOS = withPublicIpAddress.withNewPrimaryPublicIPAddress(name + "pip");
} else {
withOS = withPublicIpAddress.withoutPrimaryPublicIPAddress();
}
} else {
withOS = withPublicIpAddress.withExistingPrimaryPublicIPAddress(pip);
}
// ------ OS and credentials -----
VirtualMachine.DefinitionStages.WithCreate withCreate;
if (isWindows) {
VirtualMachine.DefinitionStages.WithWindowsAdminUsernameManagedOrUnmanaged withWindowsAdminUsername;
if (isKnownImage) {
withWindowsAdminUsername = withOS.withPopularWindowsImage((KnownWindowsVirtualMachineImage) knownImage);
} else {
withWindowsAdminUsername = withOS.withSpecificWindowsImageVersion(vmImage.imageReference());
}
withCreate = withWindowsAdminUsername.withAdminUsername(username).withAdminPassword(password).withUnmanagedDisks();
} else {
VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged withLinuxRootPasswordOrPublicKey;
if (isKnownImage) {
withLinuxRootPasswordOrPublicKey = withOS.withPopularLinuxImage((KnownLinuxVirtualMachineImage) knownImage).withRootUsername(username);
} else {
withLinuxRootPasswordOrPublicKey = withOS.withSpecificLinuxImageVersion(vmImage.imageReference()).withRootUsername(username);
}
VirtualMachine.DefinitionStages.WithLinuxCreateManagedOrUnmanaged withLinuxCreate;
// we assume either password or public key is not empty
if (password != null && !password.isEmpty()) {
withLinuxCreate = withLinuxRootPasswordOrPublicKey.withRootPassword(password);
if (publicKey != null) {
withLinuxCreate = withLinuxCreate.withSsh(publicKey);
}
} else {
withLinuxCreate = withLinuxRootPasswordOrPublicKey.withSsh(publicKey);
}
withCreate = withLinuxCreate.withUnmanagedDisks();
}
withCreate = withCreate.withSize(size);
// ---- Storage Account --------
if (withNewStorageAccount) {
StorageAccount.DefinitionStages.WithCreate newAccount;
StorageAccount.DefinitionStages.WithGroup withGroupAccount = azure.storageAccounts().define(newStorageAccount.getName()).withRegion(newStorageAccount.getLocation());
if (newStorageAccount.isNewResourceGroup()) {
newAccount = withGroupAccount.withNewResourceGroup(newStorageAccount.getResourceGroupName());
} else {
newAccount = withGroupAccount.withExistingResourceGroup(newStorageAccount.getResourceGroupName());
}
// only general purpose accounts used to create vm
newAccount.withGeneralPurposeAccountKind().withSku(SkuName.fromString(newStorageAccount.getType()));
withCreate = withCreate.withNewStorageAccount(newAccount);
} else {
withCreate = withCreate.withExistingStorageAccount(storageAccount);
}
if (withNewAvailabilitySet) {
withCreate = withCreate.withNewAvailabilitySet(name + "as");
} else if (availabilitySet != null) {
withCreate = withCreate.withExistingAvailabilitySet(availabilitySet);
}
return withCreate.create();
}
use of com.microsoft.azure.management.network.Network in project azure-tools-for-java by Microsoft.
the class AzureDockerUtils method getVirtualNetworks.
public static Map<String, Pair<String, List<String>>> getVirtualNetworks(Azure azureClient, String region) {
Map<String, Pair<String, List<String>>> result = new HashMap<>();
if (azureClient != null) {
for (Network vnet : azureClient.networks().list()) {
if (vnet.regionName().toLowerCase().equals(region) || vnet.regionName().toLowerCase().equals(region)) {
List<String> subnets = new ArrayList<>();
subnets.addAll(vnet.subnets().keySet());
result.put(vnet.id(), new Pair<>(vnet.name(), subnets));
}
}
}
return result;
}
use of com.microsoft.azure.management.network.Network in project azure-tools-for-java by Microsoft.
the class AzureDockerUtils method getVirtualNetworks.
public static List<AzureDockerVnet> getVirtualNetworks(Azure azureClient) {
List<AzureDockerVnet> result = new ArrayList<>();
if (azureClient != null) {
for (Network net : azureClient.networks().list()) {
AzureDockerVnet vnet = new AzureDockerVnet();
vnet.name = net.name();
vnet.addrSpace = net.addressSpaces().get(0);
vnet.id = net.id();
vnet.region = net.regionName().toLowerCase();
vnet.resourceGroup = net.resourceGroupName();
vnet.subnets = new ArrayList<>();
for (Subnet subnet : net.subnets().values()) {
vnet.subnets.add(subnet.name());
}
result.add(vnet);
}
}
return result;
}
Aggregations