【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的官网没有给出完整的 ...
随机推荐
- list 打乱排序
public IList<T> RandomSortList<T>(List<T> ListT) { Random random = new Random(); L ...
- 【Notes_9】现代图形学入门——光线追踪(基本原理)
跟着闫令琪老师的课程学习,总结自己学习到的知识点 课程网址GAMES101 B站课程地址GAMES101 课程资料百度网盘[提取码:0000] 目录 光线追踪 为什么要光线追踪 soft shadow ...
- Java基础语法:static修饰符
一.静态变量 描述: 在类中,使用'static'修饰的成员变量,就是静态变量,反之为非静态变量. 区别: 静态变量属于类的,可以使用类名来访问:非静态变量是属于对象的,必须使用对象来访问. 静态变量 ...
- Hyperf-事件机制+异常处理
Hyperf-事件机制+异常处理 标签(空格分隔): php, hyperf 异常处理器 在 Hyperf 里,业务代码都运行在 Worker 进程 上,也就意味着一旦任意一个请求的业务存在没有捕获处 ...
- wxWidgets源码分析(6) - 窗口关闭过程
目录 窗口关闭过程 调用流程 关闭文档 删除视图 删除文档对象 关闭Frame App清理 多文档窗口的关闭 多文档父窗口关闭 多文档子窗口关闭 窗口的正式删除 窗口关闭过程总结 如何手工删除view ...
- wxWidgets源码分析(2) - App主循环
目录 APP主循环 MainLoop 消息循环对象的创建 消息循环 消息派发 总结 APP主循环 MainLoop 前面的wxApp的启动代码可以看到,执行完成wxApp::OnInit()函数后,接 ...
- 解决vue 绑定事件会覆盖默认参数的问题
解决vue 绑定事件会覆盖默认参数的问题 在使用一些ui框架的时候,某些组件的框架中的事件所规定的参数不能满足实际开发的需要,但是直接传入参数会把默认的参数覆盖掉 解决方法:将参数放入箭头函数中,传递 ...
- Python切换版本工具pyenv
目录 安装pyenv 安装与查看py版本 切换py版本 结合ide使用示例 和virtualenv的一些区别 参考文献 使用了一段时间,我发现这玩意根本不是什么神器,简直就是垃圾,安装多版本总是失败, ...
- 话说 synchronized
一.前言 说起java的锁呀,我们先想到的肯定是synchronized[ˈsɪŋ krə naɪ zd]了 ,这个单词很拗口,会读这个单词在以后的面试中很加分(我面试过一些人 不会读 ,他们说的 ...
- Flink的日志配置
------------恢复内容开始------------ 介绍flink在本地运行和on yarn运行时的日志配置. 很多现代框架都是用门面模式进行日志输出,例如使用Slf4j中的接口输出日志,具 ...