【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);
注:
- 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
【Azure Developer】使用Java SDK代码创建Azure VM (包含设置NSG,及添加数据磁盘SSD)的更多相关文章
- 【Azure 环境】【Azure Developer】使用Python代码获取Azure 中的资源的Metrics定义及数据
问题描述 使用Python SDK来获取Azure上的各种资源的Metrics的名称以及Metrics Data的示例 问题解答 通过 azure-monitor-query ,可以创建一个 metr ...
- 利用Meida Service的Java SDK来调用Azure Media Services的Index V2实现视频字幕自动识别
Azure Media Services新的Index V2 支持自动将视频文件中的语音自动识别成字幕文件WebVtt,非常方便的就可以跟Azure Media Player集成,将一个原来没字幕的视 ...
- 【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例
当需要通过代码的方式执行PowerShell脚本时,可以参考以下的示例. Azure SDK中提供了两个方法来执行PowerShell脚本 (SDK Source Code: https://gith ...
- Azure机器学习入门(二)创建Azure机器学习工作区
我们将开始深入了解如何使用Azure机器学习的基本功能,帮助您开始迈向Azure机器学习的数据科学家之路. Azure ML Studio (Azure Machine Learning Studio ...
- 【Azure Developer】【Python 】使用 azure.identity 和 azure.common.credentials 获取Azure AD的Access Token的两种方式
问题描述 使用Python代码,展示如何从Azure AD 中获取目标资源的 Access Token. 如要了解如何从AAD中获取 client id,client secret,tenant id ...
- Azure机器学习入门(三)创建Azure机器学习实验
在此动手实践中,我们将在Azure机器学习Studio中一步步地开发预测分析模型,首先我们从UCI机器学习库的链接下载普查收入数据集的样本并开始动手实践: http://archive.ics.uci ...
- JAVA 从一个List里删除包含另一个List的数据
/** * 从listA里删除listB里有的数据 * @param listA * @param listB * @return */ public static List<String> ...
- 【Microsoft Azure学习之旅】Azure Java SDK - Service Bus的认证问题
[2014年12月12日增加备注:12月10日,Microsoft Azure Java SDK team发布了v0.7.0版本,增加对Service Bus SAS的支持,已解决这个问题:-)] 最 ...
- 在Azure China用自定义镜像创建Azure VM Scale Set
在Azure China用自定义镜像创建Azure VM Scale Set 在此感谢世纪互联的工程师Johnny Lee和Lan,你们给了我很大的帮助.因为Azure China的官网没有给出完整的 ...
随机推荐
- [计算机图形学]绘制填充模型:重心坐标、z-buffer
目录 一.点乘和叉乘 0. 向量表示 1. 点乘 2.叉乘 2.1 坐标运算方式 2.2 向量运算方式 2.3 叉乘的用途 二.Bounding Box 三.重心坐标 四.z-buffer 五.总结 ...
- <span>居中
在父元素中加style="text-align:center"; 比如下面这样 <head> </head> <body> <di ...
- Flask:处理Web表单
尽管 Flask 的请求对象提供的信息足以处理 Web 表单,但有些任务很单调,而且要重复操作.比如,生成表单的 HTML 代码和验证提交的表单数据.Flask-WTF 扩展可以把处理 Web 表单的 ...
- 001 说说Python中的深拷贝和浅拷贝
在Python编程中忽略深拷贝和浅拷贝可能会造成未知的风险. 比如我们打算保存一份原始对象的副本作为上一状态的记录,此后修改原始对象数据时,若是副本对象的数据也发生改变,那么这就是一个严重的错误. 注 ...
- LeetCode-二叉树的镜像
二叉树的镜像 二叉树的镜像 给定一个二叉树,输出二叉树的镜像. 只需要使用一个简单的递归,分别对左右子树反转后再对当前结点进行反转. #include<iostream> #include ...
- MyBatis文档
MyBatis 学习笔记 简介 什么是Mybatis MyBatis 是一款优秀的持久层框架,是Apache的一个Java开源项目 ,它支持自定义 SQL.存储过程以及高级映射, 免除了几乎所有的 J ...
- 什么是内存对齐,go中内存对齐分析
内存对齐 什么是内存对齐 为什么需要内存对齐 减少次数 保障原子性 对齐系数 对齐规则 总结 参考 内存对齐 什么是内存对齐 弄明白什么是内存对齐的时候,先来看一个demo type s struct ...
- C++树——遍历二叉树
在讲遍历之前,我们要先创建一个树: #include <iostream> using namespace std; typedef struct node; typedef node * ...
- SQL SERVER跨数据库服务,联表进行查询
SELECT * FROM 数据库A..表A a, 数据库B..表B b WHERE a.field=b.field
- 【LeetCode】4. Median of Two Sorted Arrays(思维)
[题意] 给两个有序数组,寻找两个数组组成后的中位数,要求时间复杂度为O(log(n+m)). [题解] 感觉这道题想法非常妙!! 假定原数组为a,b,数组长度为lena,lenb. 那么中位数一定是 ...