【Azure Developer】使用Java SDK代码创建Azure VM (包含设置NSG,及添加数据磁盘SSD)

在参考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);

注: 

  1.  lun全称为logical unit number,也就是逻辑单元号。在一个VM中是唯一不能重复的数字,如0, 1, 2,...
  2.  CachingTypes 表示当前磁盘的是只读,还是可读可写
  3.  StorageAccountTypes 则是指定当前磁盘的类型, SSD 或是HDD,虽然SDK中它有四个值,但是中国区只支持Premium_LRS,StandardSSD_LRS,Standard_LRS。分别对应高级SSD,标准SSD,标准HDD.
  4.  中国区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);

结果如图

【Azure Developer】使用Java SDK代码创建Azure VM (包含设置NSG,及添加数据磁盘SSD)

 

参考资料

网络安全组: 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

 

上一篇:SQL Azure与SQL Server两者的对比介绍,看完你就懂了!


下一篇:Azure CTO:什么才是真正的混合云?