在參考Azure官方文件進行VM建立時,發現其中沒有包含如何設定NSG的內容,以及如何在建立時就新增資料磁碟的程式碼(設定磁碟為SSD型別)。本文的內容以“使用 Java 建立和管理 Azure 中的 Windows VM”為基礎,在其中新增如何設定NSG(網路安全組 Network Security Group), 新增資料磁碟並設定型別。
首先,建立虛擬機器需要準備的資源有:
-
建立資源組 ResourceGroup
-
建立可用性集 AvailabilitySet
-
建立公共 IP 地址 PublicIPAddress
-
建立虛擬網路 Network
-
建立網路介面 NetworkInterface
-
建立虛擬機器 VirtualMachine
以上資源的程式碼都可以在官網中獲取(https://docs.azure.cn/zh-cn/virtual-machines/windows/java#create-resources),本文最後也附帶了完整程式碼,以供參考。接下來就主要介紹NSG部分
建立網路安全組(NSG: NetworkSecurityGroup)
System.out.println("Creating network security group..."); NetworkSecurityGroup networksg = azure.networkSecurityGroups().define("myNSG") .withRegion(Region.CHINA_NORTH) .withExistingResourceGroup("myResourceGroup") .create();
注:NSG需要附加在網路介面NetworkInerface中。附加方式如下
NetworkInterface networkInterface = azure.networkInterfaces().define("myNIC")
.withRegion(Region.CHINA_NORTH) .withExistingResourceGroup("myResourceGroup")
.withExistingPrimaryNetwork(network).withSubnet("mySubnet") .withPrimaryPrivateIPAddressDynamic()
.withExistingPrimaryPublicIPAddress(publicIPAddress) .withExistingNetworkSecurityGroup(networksg)
.create();
新增NSG規則(入站,出站)
//inbound rule networksg.update().defineRule("rule1").allowInbound().fromAddress("125.136.3.25").fromPort(5885).toAnyAddress() .toAnyPort().withAnyProtocol().withPriority(300).attach().apply(); networksg.update().defineRule("rule2").allowInbound().fromAddress("125.136.3.55").fromPort(5899).toAnyAddress() .toAnyPort().withAnyProtocol().withPriority(500).attach().apply();
//outbound rule networksg.update().defineRule("rule3").allowOutbound().fromAddress("125.136.3.78").fromPort(6886).toAnyAddress() .toAnyPort().withAnyProtocol().withPriority(600).attach().apply();
注:在建立完成networksg後,通過Update()的方式定義Rule。包含入站規則,出站規則,設定源地址,目標地址,源埠,目標埠,協議方式,優先順序,操作等。
引數說明;
屬性 | 說明 |
名稱 | 網路安全組中的唯一名稱 |
優先順序 |
介於 100 和 4096 之間的數字。 規則按優先順序進行處理。先處理編號較小的規則,因為編號越小,優先順序越高。 一旦流量與某個規則匹配,處理即會停止。 因此,不會處理優先順序較低(編號較大)的、其屬性與高優先順序規則相同的所有規則 |
源或目標 | 可以是任何值,也可以是單個 IP 地址、無類別域際路由 (CIDR) 塊(例如 10.0.0.0/24)、服務標記或應用程式安全組 |
協議 | TCP、UDP、ICMP 或 Any |
方向 | 該規則是應用到入站還是出站流量 |
埠範圍 |
可以指定單個埠或埠範圍。 例如,可以指定 80 或 10000-10005 |
操作 | 允許或拒絕 |
新增資料磁碟
System.out.println("Creating virtual machine..."); VirtualMachine virtualMachine = azure.virtualMachines().define("myVM").withRegion(Region.CHINA_NORTH) .withExistingResourceGroup("myResourceGroup").withExistingPrimaryNetworkInterface(networkInterface) .withLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter") .withAdminUsername("azureuser").withAdminPassword("Azure12345678").withComputerName("myVM") .withNewDataDisk(254, 0, CachingTypes.READ_WRITE, StorageAccountTypes.PREMIUM_LRS) .withExistingAvailabilitySet(availabilitySet).withSize("Standard_DS1").create();
JDK中WithNewDataDisk介面說明:
/** * Specifies that a managed disk needs to be created implicitly with the given settings. * * @param sizeInGB the size of the managed disk * @param lun the disk LUN * @param cachingType a caching type * @param storageAccountType a storage account type * @return the next stage of the update */ Update withNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType);
注:
- lun全稱為logical unit number,也就是邏輯單元號。在一個VM中是唯一不能重複的數字,如0, 1, 2,...
- CachingTypes 表示當前磁碟的是隻讀,還是可讀可寫
- StorageAccountTypes 則是指定當前磁碟的型別, SSD 或是HDD,雖然SDK中它有四個值,但是中國區只支援Premium_LRS,StandardSSD_LRS,Standard_LRS。分別對應高階SSD,標準SSD,標準HDD.
- 中國區Azure不支援UltraSSD_LRS型別 。 如在程式碼中使用它,則會出現如下錯誤:Exception in thread "main" com.microsoft.azure.CloudException: SKU UltraSSD_LRS is not supported for resource type Disk in this region. Supported SKUs for this region are Premium_LRS,StandardSSD_LRS,Standard_LRS: SKU UltraSSD_LRS is not supported for resource type Disk in this region. Supported SKUs for this region are Premium_LRS,StandardSSD_LRS,Standard_LRS
完整程式碼
1 package org.example; 2 3 import com.microsoft.azure.management.Azure; 4 import com.microsoft.azure.management.batch.DataDisk; 5 import com.microsoft.azure.management.compute.AvailabilitySet; 6 import com.microsoft.azure.management.compute.AvailabilitySetSkuTypes; 7 import com.microsoft.azure.management.compute.CachingTypes; 8 import com.microsoft.azure.management.compute.Disk; 9 import com.microsoft.azure.management.compute.InstanceViewStatus; 10 import com.microsoft.azure.management.compute.StorageAccountTypes; 11 import com.microsoft.azure.management.compute.DiskInstanceView; 12 import com.microsoft.azure.management.compute.DiskSkuTypes; 13 import com.microsoft.azure.management.compute.VirtualMachine; 14 import com.microsoft.azure.management.compute.VirtualMachineSizeTypes; 15 import com.microsoft.azure.management.network.PublicIPAddress; 16 import com.microsoft.azure.management.network.Network; 17 import com.microsoft.azure.management.network.NetworkInterface; 18 import com.microsoft.azure.management.network.NetworkSecurityGroup; 19 import com.microsoft.azure.management.resources.ResourceGroup; 20 import com.microsoft.azure.management.resources.fluentcore.arm.Region; 21 import com.microsoft.azure.management.resources.fluentcore.model.Creatable; 22 import com.microsoft.rest.LogLevel; 23 import java.io.File; 24 import java.util.Scanner; 25 26 import com.microsoft.azure.AzureEnvironment; 27 import com.microsoft.azure.credentials.ApplicationTokenCredentials; 28 import com.microsoft.azure.credentials.AzureTokenCredentials; 29 30 public class testAzureApp { 31 public static void createVM() 32 33 { 34 35 // 使用AAD Application 方式獲取 認證 36 AzureTokenCredentials credentials = new ApplicationTokenCredentials("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", 37 "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 38 AzureEnvironment.AZURE_CHINA); 39 Azure azure = null; 40 41 azure = Azure.authenticate(credentials).withSubscription("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); 42 43 System.out.println("Creating resource group..."); 44 // ResourceGroup resourceGroup = 45 // azure.resourceGroups().define("myResourceGroup").withRegion(Region.CHINA_NORTH) 46 // .create(); 47 48 System.out.println("Creating availability set..."); 49 AvailabilitySet availabilitySet = azure.availabilitySets().define("myAvailabilitySet") 50 .withRegion(Region.CHINA_NORTH).withExistingResourceGroup("myResourceGroup") 51 .withSku(AvailabilitySetSkuTypes.ALIGNED).create(); 52 53 System.out.println("Creating public IP address..."); 54 PublicIPAddress publicIPAddress = azure.publicIPAddresses().define("myPublicIP").withRegion(Region.CHINA_NORTH) 55 .withExistingResourceGroup("myResourceGroup").withDynamicIP().create(); 56 57 System.out.println("Creating virtual network..."); 58 Network network = azure.networks().define("myVN").withRegion(Region.CHINA_NORTH) 59 .withExistingResourceGroup("myResourceGroup").withAddressSpace("10.0.0.0/16") 60 .withSubnet("mySubnet", "10.0.0.0/24").create(); 61 62 // NetworkSecurityGroup networksg = 63 // azure.networkSecurityGroups().getById("/subscriptions/xxxxxxxxxxxxxxxx/resourceGroups/xxxxxxxxxxxxxxxx/providers/Microsoft.Network/networkSecurityGroups/xxxxxxxxxxxxxxxx"); 64 System.out.println("Creating network security group..."); 65 NetworkSecurityGroup networksg = azure.networkSecurityGroups().define("myNSG").withRegion(Region.CHINA_NORTH) 66 .withExistingResourceGroup("myResourceGroup").create(); 67 68 // inbound rule 69 networksg.update().defineRule("rule1").allowInbound().fromAddress("125.136.3.25").fromPort(5885).toAnyAddress() 70 .toAnyPort().withAnyProtocol().withPriority(300).attach().apply(); 71 networksg.update().defineRule("rule2").allowInbound().fromAddress("125.136.3.55").fromPort(5899).toAnyAddress() 72 .toAnyPort().withAnyProtocol().withPriority(500).attach().apply(); 73 // outbound rule 74 networksg.update().defineRule("rule3").allowOutbound().fromAddress("125.136.3.78").fromPort(6886).toAnyAddress() 75 .toAnyPort().withAnyProtocol().withPriority(600).attach().apply(); 76 77 System.out.println("Creating network interface..."); 78 NetworkInterface networkInterface = azure.networkInterfaces().define("myNIC").withRegion(Region.CHINA_NORTH) 79 .withExistingResourceGroup("myResourceGroup").withExistingPrimaryNetwork(network).withSubnet("mySubnet") 80 .withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(publicIPAddress) 81 .withExistingNetworkSecurityGroup(networksg).create(); 82 83 System.out.println("Creating virtual machine..."); 84 VirtualMachine virtualMachine = azure.virtualMachines().define("myVM").withRegion(Region.CHINA_NORTH) 85 .withExistingResourceGroup("myResourceGroup").withExistingPrimaryNetworkInterface(networkInterface) 86 .withLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter") 87 .withAdminUsername("azureuser").withAdminPassword("Azure12345678").withComputerName("myVM") 88 .withNewDataDisk(254, 0, CachingTypes.READ_WRITE, StorageAccountTypes.PREMIUM_LRS) 89 .withExistingAvailabilitySet(availabilitySet).withSize("Standard_DS1").create(); 90 91 Scanner input = new Scanner(System.in); 92 System.out.println("Press enter to get information about the VM..."); 93 input.nextLine(); 94 } 95 }
JDK依賴 pom.xml
<dependency> <groupId>com.microsoft.azure</groupId> <artifactId>azure</artifactId> <version>1.41.0</version> </dependency>
附錄一:Java SDK獲取所有訂閱號程式碼
PagedList<Subscription> allsubs= Azure.authenticate(credentials).subscriptions().list();
附錄二:Java SDK獲取當前訂閱號下所有虛擬機器程式碼
PagedList<VirtualMachine> allvms = azure.virtualMachines().list();
附錄三: Java SDK獲取所有的VM Size對應的CPU核數,Memroy大小
PagedList<VirtualMachineSize> vmslist = azure.virtualMachines().sizes().listByRegion(Region.CHINA_EAST);
結果如圖
參考資料
網路安全組: https://docs.azure.cn/zh-cn/virtual-network/network-security-groups-overview
使用 Java 建立和管理 Azure 中的 Windows VM: https://docs.azure.cn/zh-cn/virtual-machines/windows/java#create-resources