use of com.microsoft.azure.management.compute.VirtualMachine in project azure-sdk-for-java by Azure.
the class ManageVirtualMachineExtension 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 linuxVMName = SdkContext.randomResourceName("lVM", 10);
final String windowsVMName = SdkContext.randomResourceName("wVM", 10);
final String rgName = SdkContext.randomResourceName("rgCOVE", 15);
final String pipDnsLabelLinuxVM = SdkContext.randomResourceName("rgPip1", 25);
final String pipDnsLabelWindowsVM = SdkContext.randomResourceName("rgPip2", 25);
// Linux configurations
//
final String firstLinuxUserName = "tirekicker";
final String firstLinuxUserPassword = "12NewPA$$w0rd!";
final String firstLinuxUserNewPassword = "muy!234OR";
final String secondLinuxUserName = "seconduser";
final String secondLinuxUserPassword = "B12a6@12xyz!";
final String secondLinuxUserExpiration = "2020-12-31";
final String thirdLinuxUserName = "thirduser";
final String thirdLinuxUserPassword = "12xyz!B12a6@";
final String thirdLinuxUserExpiration = "2020-12-31";
final String linuxCustomScriptExtensionName = "CustomScriptForLinux";
final String linuxCustomScriptExtensionPublisherName = "Microsoft.OSTCExtensions";
final String linuxCustomScriptExtensionTypeName = "CustomScriptForLinux";
final String linuxCustomScriptExtensionVersionName = "1.4";
final String mySqlLinuxInstallScript = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/4397e808d07df60ff3cdfd1ae40999f0130eb1b3/mysql-standalone-server-ubuntu/scripts/install_mysql_server_5.6.sh";
final String installMySQLLinuxCommand = "bash install_mysql_server_5.6.sh Abc.123x(";
final List<String> linuxScriptFileUris = new ArrayList<>();
linuxScriptFileUris.add(mySqlLinuxInstallScript);
final String windowsCustomScriptExtensionName = "CustomScriptExtension";
final String windowsCustomScriptExtensionPublisherName = "Microsoft.Compute";
final String windowsCustomScriptExtensionTypeName = "CustomScriptExtension";
final String windowsCustomScriptExtensionVersionName = "1.7";
final String mySqlWindowsInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/master/azure-samples/src/main/resources/installMySQL.ps1";
final String installMySQLWindowsCommand = "powershell.exe -ExecutionPolicy Unrestricted -File installMySQL.ps1";
final List<String> windowsScriptFileUris = new ArrayList<>();
windowsScriptFileUris.add(mySqlWindowsInstallScript);
final String linuxVMAccessExtensionName = "VMAccessForLinux";
final String linuxVMAccessExtensionPublisherName = "Microsoft.OSTCExtensions";
final String linuxVMAccessExtensionTypeName = "VMAccessForLinux";
final String linuxVMAccessExtensionVersionName = "1.4";
// Windows configurations
//
final String firstWindowsUserName = "tirekicker";
final String firstWindowsUserPassword = "12NewPA$$w0rd!";
final String firstWindowsUserNewPassword = "muy!234OR";
final String secondWindowsUserName = "seconduser";
final String secondWindowsUserPassword = "B12a6@12xyz!";
final String thirdWindowsUserName = "thirduser";
final String thirdWindowsUserPassword = "12xyz!B12a6@";
final String windowsVMAccessExtensionName = "VMAccessAgent";
final String windowsVMAccessExtensionPublisherName = "Microsoft.Compute";
final String windowsVMAccessExtensionTypeName = "VMAccessAgent";
final String windowsVMAccessExtensionVersionName = "2.3";
try {
//=============================================================
// Create a Linux VM with root (sudo) user
System.out.println("Creating a Linux VM");
VirtualMachine linuxVM = azure.virtualMachines().define(linuxVMName).withRegion(region).withNewResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(pipDnsLabelLinuxVM).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_14_04_LTS).withRootUsername(firstLinuxUserName).withRootPassword(firstLinuxUserPassword).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
System.out.println("Created a Linux VM with" + linuxVM.id());
Utils.print(linuxVM);
//=============================================================
// Add a second sudo user to Linux VM using VMAccess extension
linuxVM.update().defineNewExtension(linuxVMAccessExtensionName).withPublisher(linuxVMAccessExtensionPublisherName).withType(linuxVMAccessExtensionTypeName).withVersion(linuxVMAccessExtensionVersionName).withProtectedSetting("username", secondLinuxUserName).withProtectedSetting("password", secondLinuxUserPassword).withProtectedSetting("expiration", secondLinuxUserExpiration).attach().apply();
System.out.println("Added a second sudo user to the Linux VM");
//=============================================================
// Add a third sudo user to Linux VM by updating VMAccess extension
linuxVM.update().updateExtension(linuxVMAccessExtensionName).withProtectedSetting("username", thirdLinuxUserName).withProtectedSetting("password", thirdLinuxUserPassword).withProtectedSetting("expiration", thirdLinuxUserExpiration).parent().apply();
System.out.println("Added a third sudo user to the Linux VM");
//=============================================================
// Reset ssh password of first user of Linux VM by updating VMAccess extension
linuxVM.update().updateExtension(linuxVMAccessExtensionName).withProtectedSetting("username", firstLinuxUserName).withProtectedSetting("password", firstLinuxUserNewPassword).withProtectedSetting("reset_ssh", "true").parent().apply();
System.out.println("Password of first user of Linux VM has been updated");
//=============================================================
// Removes the second sudo user from Linux VM using VMAccess extension
linuxVM.update().updateExtension(linuxVMAccessExtensionName).withProtectedSetting("remove_user", secondLinuxUserName).parent().apply();
//=============================================================
// Install MySQL in Linux VM using CustomScript extension
linuxVM.update().defineNewExtension(linuxCustomScriptExtensionName).withPublisher(linuxCustomScriptExtensionPublisherName).withType(linuxCustomScriptExtensionTypeName).withVersion(linuxCustomScriptExtensionVersionName).withMinorVersionAutoUpgrade().withPublicSetting("fileUris", linuxScriptFileUris).withPublicSetting("commandToExecute", installMySQLLinuxCommand).attach().apply();
System.out.println("Installed MySql using custom script extension");
Utils.print(linuxVM);
//=============================================================
// Removes the extensions from Linux VM
linuxVM.update().withoutExtension(linuxCustomScriptExtensionName).withoutExtension(linuxVMAccessExtensionName).apply();
System.out.println("Removed the custom script and VM Access extensions from Linux VM");
Utils.print(linuxVM);
//=============================================================
// Create a Windows VM with admin user and install choco package manager and MySQL using custom script
System.out.println("Creating a Windows VM");
VirtualMachine windowsVM = azure.virtualMachines().define(windowsVMName).withRegion(region).withExistingResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(pipDnsLabelWindowsVM).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(firstWindowsUserName).withAdminPassword(firstWindowsUserPassword).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).defineNewExtension(windowsCustomScriptExtensionName).withPublisher(windowsCustomScriptExtensionPublisherName).withType(windowsCustomScriptExtensionTypeName).withVersion(windowsCustomScriptExtensionVersionName).withMinorVersionAutoUpgrade().withPublicSetting("fileUris", windowsScriptFileUris).withPublicSetting("commandToExecute", installMySQLWindowsCommand).attach().create();
System.out.println("Created a Windows VM" + windowsVM.id());
Utils.print(windowsVM);
//=============================================================
// Add a second admin user to Windows VM using VMAccess extension
windowsVM.update().defineNewExtension(windowsVMAccessExtensionName).withPublisher(windowsVMAccessExtensionPublisherName).withType(windowsVMAccessExtensionTypeName).withVersion(windowsVMAccessExtensionVersionName).withProtectedSetting("username", secondWindowsUserName).withProtectedSetting("password", secondWindowsUserPassword).attach().apply();
System.out.println("Added a second admin user to the Windows VM");
//=============================================================
// Add a third admin user to Windows VM by updating VMAccess extension
windowsVM.update().updateExtension(windowsVMAccessExtensionName).withProtectedSetting("username", thirdWindowsUserName).withProtectedSetting("password", thirdWindowsUserPassword).parent().apply();
System.out.println("Added a third admin user to the Windows VM");
//=============================================================
// Reset admin password of first user of Windows VM by updating VMAccess extension
windowsVM.update().updateExtension(windowsVMAccessExtensionName).withProtectedSetting("username", firstWindowsUserName).withProtectedSetting("password", firstWindowsUserNewPassword).parent().apply();
System.out.println("Password of first user of Windows VM has been updated");
//=============================================================
// Removes the extensions from Windows VM
windowsVM.update().withoutExtension(windowsVMAccessExtensionName).apply();
System.out.println("Removed the VM Access extensions from Windows VM");
Utils.print(windowsVM);
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.compute.VirtualMachine in project azure-sdk-for-java by Azure.
the class ManageNetworkInterface 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_NORTH_CENTRAL;
final String vnetName = SdkContext.randomResourceName("vnet", 24);
final String networkInterfaceName1 = SdkContext.randomResourceName("nic1", 24);
final String networkInterfaceName2 = SdkContext.randomResourceName("nic2", 24);
final String networkInterfaceName3 = SdkContext.randomResourceName("nic3", 24);
final String publicIPAddressLeafDNS1 = SdkContext.randomResourceName("pip1", 24);
final String publicIPAddressLeafDNS2 = SdkContext.randomResourceName("pip2", 24);
// TODO adjust the length of vm name from 8 to 24
final String vmName = SdkContext.randomResourceName("vm", 8);
final String rgName = SdkContext.randomResourceName("rgNEMI", 24);
final String userName = "tirekicker";
final String password = "12NewPA$$w0rd!";
try {
//============================================================
// Create a virtual machine with multiple network interfaces
// Define a virtual network for the VMs in this availability set
System.out.println("Creating a virtual network ...");
Network network = azure.networks().define(vnetName).withRegion(region).withNewResourceGroup(rgName).withAddressSpace("172.16.0.0/16").defineSubnet("Front-end").withAddressPrefix("172.16.1.0/24").attach().defineSubnet("Mid-tier").withAddressPrefix("172.16.2.0/24").attach().defineSubnet("Back-end").withAddressPrefix("172.16.3.0/24").attach().create();
System.out.println("Created a virtual network: " + network.id());
Utils.print(network);
System.out.println("Creating multiple network interfaces");
System.out.println("Creating network interface 1");
NetworkInterface networkInterface1 = azure.networkInterfaces().define(networkInterfaceName1).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Front-end").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1).withIPForwarding().create();
System.out.println("Created network interface 1");
Utils.print(networkInterface1);
System.out.println("Creating network interface 2");
NetworkInterface networkInterface2 = azure.networkInterfaces().define(networkInterfaceName2).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Mid-tier").withPrimaryPrivateIPAddressDynamic().create();
System.out.println("Created network interface 2");
Utils.print(networkInterface2);
System.out.println("Creating network interface 3");
NetworkInterface networkInterface3 = azure.networkInterfaces().define(networkInterfaceName3).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Back-end").withPrimaryPrivateIPAddressDynamic().create();
System.out.println("Created network interface 3");
Utils.print(networkInterface3);
//=============================================================
// Create a virtual machine with multiple network interfaces
System.out.println("Creating a Windows VM");
Date t1 = new Date();
VirtualMachine vm = azure.virtualMachines().define(vmName).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetworkInterface(networkInterface1).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(userName).withAdminPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withExistingSecondaryNetworkInterface(networkInterface2).withExistingSecondaryNetworkInterface(networkInterface3).create();
Date t2 = new Date();
System.out.println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + vm.id());
// Print virtual machine details
Utils.print(vm);
// ===========================================================
// Configure a network interface
System.out.println("Updating the first network interface");
networkInterface1.update().withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS2).apply();
System.out.println("Updated the first network interface");
Utils.print(networkInterface1);
System.out.println();
//============================================================
// List network interfaces
System.out.println("Walking through network inter4faces in resource group: " + rgName);
PagedList<NetworkInterface> networkInterfaces = azure.networkInterfaces().listByResourceGroup(rgName);
for (NetworkInterface networkinterface : networkInterfaces) {
Utils.print(networkinterface);
}
//============================================================
// Delete a network interface
System.out.println("Deleting a network interface: " + networkInterface2.id());
System.out.println("First, deleting the vm");
azure.virtualMachines().deleteById(vm.id());
System.out.println("Second, deleting the network interface");
azure.networkInterfaces().deleteById(networkInterface2.id());
System.out.println("Deleted network interface");
System.out.println("============================================================");
System.out.println("Remaining network interfaces are ...");
networkInterfaces = azure.networkInterfaces().listByResourceGroup(rgName);
for (NetworkInterface networkinterface : networkInterfaces) {
Utils.print(networkinterface);
}
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.compute.VirtualMachine in project azure-sdk-for-java by Azure.
the class ManageNetworkSecurityGroup 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_NORTH_CENTRAL;
final String frontEndNSGName = SdkContext.randomResourceName("fensg", 24);
final String backEndNSGName = SdkContext.randomResourceName("bensg", 24);
final String rgName = SdkContext.randomResourceName("rgNEMS", 24);
final String vnetName = SdkContext.randomResourceName("vnet", 24);
final String networkInterfaceName1 = SdkContext.randomResourceName("nic1", 24);
final String networkInterfaceName2 = SdkContext.randomResourceName("nic2", 24);
final String publicIPAddressLeafDNS1 = SdkContext.randomResourceName("pip1", 24);
final String frontEndVMName = SdkContext.randomResourceName("fevm", 24);
final String backEndVMName = SdkContext.randomResourceName("bevm", 24);
final String userName = "tirekicker";
final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com";
try {
// Define a virtual network for VMs in this availability set
System.out.println("Creating a virtual network ...");
Network network = azure.networks().define(vnetName).withRegion(region).withNewResourceGroup(rgName).withAddressSpace("172.16.0.0/16").defineSubnet("Front-end").withAddressPrefix("172.16.1.0/24").attach().defineSubnet("Back-end").withAddressPrefix("172.16.2.0/24").attach().create();
System.out.println("Created a virtual network: " + network.id());
Utils.print(network);
//============================================================
// Create a network security group for the front end of a subnet
// front end subnet contains two rules
// - ALLOW-SSH - allows SSH traffic into the front end subnet
// - ALLOW-WEB- allows HTTP traffic into the front end subnet
System.out.println("Creating a security group for the front end - allows SSH and HTTP");
NetworkSecurityGroup frontEndNSG = azure.networkSecurityGroups().define(frontEndNSGName).withRegion(region).withNewResourceGroup(rgName).defineRule("ALLOW-SSH").allowInbound().fromAnyAddress().fromAnyPort().toAnyAddress().toPort(22).withProtocol(SecurityRuleProtocol.TCP).withPriority(100).withDescription("Allow SSH").attach().defineRule("ALLOW-HTTP").allowInbound().fromAnyAddress().fromAnyPort().toAnyAddress().toPort(80).withProtocol(SecurityRuleProtocol.TCP).withPriority(101).withDescription("Allow HTTP").attach().create();
System.out.println("Created a security group for the front end: " + frontEndNSG.id());
Utils.print(frontEndNSG);
//============================================================
// Create a network security group for the back end of a subnet
// back end subnet contains two rules
// - ALLOW-SQL - allows SQL traffic only from the front end subnet
// - DENY-WEB - denies all outbound internet traffic from the back end subnet
System.out.println("Creating a security group for the front end - allows SSH and " + "denies all outbound internet traffic ");
NetworkSecurityGroup backEndNSG = azure.networkSecurityGroups().define(backEndNSGName).withRegion(region).withExistingResourceGroup(rgName).defineRule("ALLOW-SQL").allowInbound().fromAddress("172.16.1.0/24").fromAnyPort().toAnyAddress().toPort(1433).withProtocol(SecurityRuleProtocol.TCP).withPriority(100).withDescription("Allow SQL").attach().defineRule("DENY-WEB").denyOutbound().fromAnyAddress().fromAnyPort().toAnyAddress().toAnyPort().withAnyProtocol().withDescription("Deny Web").withPriority(200).attach().create();
System.out.println("Created a security group for the back end: " + backEndNSG.id());
Utils.print(backEndNSG);
System.out.println("Creating multiple network interfaces");
System.out.println("Creating network interface 1");
//========================================================
// Create a network interface and apply the
// front end network security group
System.out.println("Creating a network interface for the front end");
NetworkInterface networkInterface1 = azure.networkInterfaces().define(networkInterfaceName1).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Front-end").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1).withIPForwarding().withExistingNetworkSecurityGroup(frontEndNSG).create();
System.out.println("Created network interface for the front end");
Utils.print(networkInterface1);
//========================================================
// Create a network interface and apply the
// back end network security group
System.out.println("Creating a network interface for the back end");
NetworkInterface networkInterface2 = azure.networkInterfaces().define(networkInterfaceName2).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Back-end").withPrimaryPrivateIPAddressDynamic().withExistingNetworkSecurityGroup(backEndNSG).create();
Utils.print(networkInterface2);
//=============================================================
// Create a virtual machine (for the front end)
// with the network interface that has the network security group for the front end
System.out.println("Creating a Linux virtual machine (for the front end) - " + "with the network interface that has the network security group for the front end");
Date t1 = new Date();
VirtualMachine frontEndVM = azure.virtualMachines().define(frontEndVMName).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetworkInterface(networkInterface1).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
Date t2 = new Date();
System.out.println("Created Linux VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + frontEndVM.id());
// Print virtual machine details
Utils.print(frontEndVM);
//=============================================================
// Create a virtual machine (for the back end)
// with the network interface that has the network security group for the back end
System.out.println("Creating a Linux virtual machine (for the back end) - " + "with the network interface that has the network security group for the back end");
t1 = new Date();
VirtualMachine backEndVM = azure.virtualMachines().define(backEndVMName).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetworkInterface(networkInterface2).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
t2 = new Date();
System.out.println("Created a Linux VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + backEndVM.id());
Utils.print(backEndVM);
//========================================================
// List network security groups
System.out.println("Walking through network security groups");
List<NetworkSecurityGroup> networkSecurityGroups = azure.networkSecurityGroups().listByResourceGroup(rgName);
for (NetworkSecurityGroup networkSecurityGroup : networkSecurityGroups) {
Utils.print(networkSecurityGroup);
}
//========================================================
// Update a network security group
System.out.println("Updating the front end network security group to allow FTP");
frontEndNSG.update().defineRule("ALLOW-FTP").allowInbound().fromAnyAddress().fromAnyPort().toAnyAddress().toPortRange(20, 21).withProtocol(SecurityRuleProtocol.TCP).withDescription("Allow FTP").withPriority(200).attach().apply();
System.out.println("Updated the front end network security group");
Utils.print(frontEndNSG);
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.compute.VirtualMachine in project azure-sdk-for-java by Azure.
the class ManageDns 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 customDomainName = "THE CUSTOM DOMAIN THAT YOU OWN (e.g. contoso.com)";
final String rgName = SdkContext.randomResourceName("rgNEMV_", 24);
final String appServicePlanName = SdkContext.randomResourceName("jplan1_", 15);
final String webAppName = SdkContext.randomResourceName("webapp1-", 20);
try {
ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST2).create();
//============================================================
// Creates root DNS Zone
System.out.println("Creating root DNS zone " + customDomainName + "...");
DnsZone rootDnsZone = azure.dnsZones().define(customDomainName).withExistingResourceGroup(resourceGroup).create();
System.out.println("Created root DNS zone " + rootDnsZone.name());
Utils.print(rootDnsZone);
//============================================================
// Sets NS records in the parent zone (hosting custom domain) to make Azure DNS the authoritative
// source for name resolution for the zone
System.out.println("Go to your registrar portal and configure your domain " + customDomainName + " with following name server addresses");
for (String nameServer : rootDnsZone.nameServers()) {
System.out.println(" " + nameServer);
}
System.out.println("Press a key after finishing above step");
System.in.read();
//============================================================
// Creates a web App
System.out.println("Creating Web App " + webAppName + "...");
WebApp webApp = azure.webApps().define(webAppName).withRegion(Region.US_EAST2).withExistingResourceGroup(rgName).withNewWindowsPlan(PricingTier.BASIC_B1).defineSourceControl().withPublicGitRepository("https://github.com/jianghaolu/azure-site-test").withBranch("master").attach().create();
System.out.println("Created web app " + webAppName);
Utils.print(webApp);
//============================================================
// Creates a CName record and bind it with the web app
// Step 1: Adds CName Dns record to root DNS zone that specify web app host domain as an
// alias for www.[customDomainName]
System.out.println("Updating DNS zone by adding a CName record...");
rootDnsZone = rootDnsZone.update().withCNameRecordSet("www", webApp.defaultHostName()).apply();
System.out.println("DNS zone updated");
Utils.print(rootDnsZone);
// Waiting for a minute for DNS CName entry to propagate
System.out.println("Waiting a minute for CName record entry to propagate...");
Thread.sleep(60 * 1000);
// Step 2: Adds a web app host name binding for www.[customDomainName]
// This binding action will fail if the CName record propagation is not yet completed
System.out.println("Updating Web app with host name binding...");
webApp.update().defineHostnameBinding().withThirdPartyDomain(customDomainName).withSubDomain("www").withDnsRecordType(CustomHostNameDnsRecordType.CNAME).attach().apply();
System.out.println("Web app updated");
Utils.print(webApp);
//============================================================
// Creates a virtual machine with public IP
System.out.println("Creating a virtual machine with public IP...");
VirtualMachine virtualMachine1 = azure.virtualMachines().define(SdkContext.randomResourceName("employeesvm-", 20)).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(SdkContext.randomResourceName("empip-", 20)).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername("testuser").withAdminPassword("12NewPA$$w0rd!").withSize(VirtualMachineSizeTypes.STANDARD_D1_V2).create();
System.out.println("Virtual machine created");
//============================================================
// Update DNS zone by adding a A record in root DNS zone pointing to virtual machine IPv4 address
PublicIPAddress vm1PublicIPAddress = virtualMachine1.getPrimaryPublicIPAddress();
System.out.println("Updating root DNS zone " + customDomainName + "...");
rootDnsZone = rootDnsZone.update().defineARecordSet("employees").withIPv4Address(vm1PublicIPAddress.ipAddress()).attach().apply();
System.out.println("Updated root DNS zone " + rootDnsZone.name());
Utils.print(rootDnsZone);
// Prints the CName and A Records in the root DNS zone
//
System.out.println("Getting CName record set in the root DNS zone " + customDomainName + "...");
PagedList<CNameRecordSet> cnameRecordSets = rootDnsZone.cNameRecordSets().list();
for (CNameRecordSet cnameRecordSet : cnameRecordSets) {
System.out.println("Name: " + cnameRecordSet.name() + " Canonical Name: " + cnameRecordSet.canonicalName());
}
System.out.println("Getting ARecord record set in the root DNS zone " + customDomainName + "...");
PagedList<ARecordSet> aRecordSets = rootDnsZone.aRecordSets().list();
for (ARecordSet aRecordSet : aRecordSets) {
System.out.println("Name: " + aRecordSet.name());
for (String ipv4Address : aRecordSet.ipv4Addresses()) {
System.out.println(" " + ipv4Address);
}
}
//============================================================
// Creates a child DNS zone
String partnerSubDomainName = "partners." + customDomainName;
System.out.println("Creating child DNS zone " + partnerSubDomainName + "...");
DnsZone partnersDnsZone = azure.dnsZones().define(partnerSubDomainName).withExistingResourceGroup(resourceGroup).create();
System.out.println("Created child DNS zone " + partnersDnsZone.name());
Utils.print(partnersDnsZone);
//============================================================
// Adds NS records in the root dns zone to delegate partners.[customDomainName] to child dns zone
System.out.println("Updating root DNS zone " + rootDnsZone + "...");
DnsRecordSet.UpdateDefinitionStages.WithNSRecordNameServerOrAttachable<DnsZone.Update> nsRecordStage = rootDnsZone.update().defineNSRecordSet("partners").withNameServer(partnersDnsZone.nameServers().get(0));
for (int i = 1; i < partnersDnsZone.nameServers().size(); i++) {
nsRecordStage = nsRecordStage.withNameServer(partnersDnsZone.nameServers().get(i));
}
nsRecordStage.attach().apply();
System.out.println("Root DNS zone updated");
Utils.print(rootDnsZone);
//============================================================
// Creates a virtual machine with public IP
System.out.println("Creating a virtual machine with public IP...");
VirtualMachine virtualMachine2 = azure.virtualMachines().define(SdkContext.randomResourceName("partnersvm-", 20)).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(SdkContext.randomResourceName("ptnerpip-", 20)).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername("testuser").withAdminPassword("12NewPA$$w0rd!").withSize(VirtualMachineSizeTypes.STANDARD_D1_V2).create();
System.out.println("Virtual machine created");
//============================================================
// Update child DNS zone by adding a A record pointing to virtual machine IPv4 address
PublicIPAddress vm2PublicIPAddress = virtualMachine2.getPrimaryPublicIPAddress();
System.out.println("Updating child DNS zone " + partnerSubDomainName + "...");
partnersDnsZone = partnersDnsZone.update().defineARecordSet("@").withIPv4Address(vm2PublicIPAddress.ipAddress()).attach().apply();
System.out.println("Updated child DNS zone " + partnersDnsZone.name());
Utils.print(partnersDnsZone);
//============================================================
// Removes A record entry from the root DNS zone
System.out.println("Removing A Record from root DNS zone " + rootDnsZone.name() + "...");
rootDnsZone = rootDnsZone.update().withoutARecordSet("employees").apply();
System.out.println("Removed A Record from root DNS zone");
Utils.print(rootDnsZone);
//============================================================
// Deletes the DNS zone
System.out.println("Deleting child DNS zone " + partnersDnsZone.name() + "...");
azure.dnsZones().deleteById(partnersDnsZone.id());
System.out.println("Deleted child DNS zone " + partnersDnsZone.name());
return true;
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(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.compute.VirtualMachine in project azure-sdk-for-java by Azure.
the class ManageVirtualMachinesInParallel 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 int vmCount = 10;
final Region region = Region.US_EAST;
final String rgName = SdkContext.randomResourceName("rgCOPP", 24);
final String networkName = SdkContext.randomResourceName("vnetCOMV", 24);
final String storageAccountName = SdkContext.randomResourceName("stgCOMV", 20);
final String userName = "tirekicker";
final String password = "12NewPA$$w0rd!";
try {
// Create a resource group [Where all resources gets created]
ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(region).create();
// Prepare Creatable Network definition [Where all the virtual machines get added to]
Creatable<Network> creatableNetwork = azure.networks().define(networkName).withRegion(region).withExistingResourceGroup(resourceGroup).withAddressSpace("172.16.0.0/16");
// Prepare Creatable Storage account definition [For storing VMs disk]
Creatable<StorageAccount> creatableStorageAccount = azure.storageAccounts().define(storageAccountName).withRegion(region).withExistingResourceGroup(resourceGroup);
// Prepare a batch of Creatable Virtual Machines definitions
List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
for (int i = 0; i < vmCount; i++) {
Creatable<VirtualMachine> creatableVirtualMachine = azure.virtualMachines().define("VM-" + i).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork(creatableNetwork).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2).withNewStorageAccount(creatableStorageAccount);
creatableVirtualMachines.add(creatableVirtualMachine);
}
StopWatch stopwatch = new StopWatch();
System.out.println("Creating the virtual machines");
stopwatch.start();
Collection<VirtualMachine> virtualMachines = azure.virtualMachines().create(creatableVirtualMachines).values();
stopwatch.stop();
System.out.println("Created virtual machines");
for (VirtualMachine virtualMachine : virtualMachines) {
System.out.println(virtualMachine.id());
}
System.out.println("Virtual Machines create: (took " + (stopwatch.getTime() / 1000) + " seconds) ");
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(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;
}
Aggregations