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

  1. System.out.println("Creating network security group...");
  2. NetworkSecurityGroup networksg = azure.networkSecurityGroups().define("myNSG")
  3. .withRegion(Region.CHINA_NORTH)
  4. .withExistingResourceGroup("myResourceGroup")
  5. .create();

注:NSG需要附加在网络接口NetworkInerface中。附加方式如下

  1. NetworkInterface networkInterface = azure.networkInterfaces().define("myNIC")
              .withRegion(Region.CHINA_NORTH)
  2. .withExistingResourceGroup("myResourceGroup")
              .withExistingPrimaryNetwork(network).withSubnet("mySubnet")
  3. .withPrimaryPrivateIPAddressDynamic()
              .withExistingPrimaryPublicIPAddress(publicIPAddress)
  4. .withExistingNetworkSecurityGroup(networksg)
              .create();

添加NSG规则(入站,出站)

  1. //inbound rule
  2. networksg.update().defineRule("rule1").allowInbound().fromAddress("125.136.3.25").fromPort(5885).toAnyAddress()
  3. .toAnyPort().withAnyProtocol().withPriority(300).attach().apply();
  4. networksg.update().defineRule("rule2").allowInbound().fromAddress("125.136.3.55").fromPort(5899).toAnyAddress()
  5. .toAnyPort().withAnyProtocol().withPriority(500).attach().apply();

  6. //outbound rule
  7. networksg.update().defineRule("rule3").allowOutbound().fromAddress("125.136.3.78").fromPort(6886).toAnyAddress()
  8. .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

操作 允许或拒绝

添加数据磁盘

  1. System.out.println("Creating virtual machine...");
  2. VirtualMachine virtualMachine = azure.virtualMachines().define("myVM").withRegion(Region.CHINA_NORTH)
  3. .withExistingResourceGroup("myResourceGroup").withExistingPrimaryNetworkInterface(networkInterface)
  4. .withLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
  5. .withAdminUsername("azureuser").withAdminPassword("Azure12345678").withComputerName("myVM")
  6. .withNewDataDisk(254, 0, CachingTypes.READ_WRITE, StorageAccountTypes.PREMIUM_LRS)
  7. .withExistingAvailabilitySet(availabilitySet).withSize("Standard_DS1").create();

JDK中WithNewDataDisk接口说明:

  1. /**
  2. * Specifies that a managed disk needs to be created implicitly with the given settings.
  3. *
  4. * @param sizeInGB the size of the managed disk
  5. * @param lun the disk LUN
  6. * @param cachingType a caching type
  7. * @param storageAccountType a storage account type
  8. * @return the next stage of the update
  9. */
  10. Update withNewDataDisk(int sizeInGB,
  11. int lun,
  12. CachingTypes cachingType,
  13. 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. 1 package org.example;
  2. 2
  3. 3 import com.microsoft.azure.management.Azure;
  4. 4 import com.microsoft.azure.management.batch.DataDisk;
  5. 5 import com.microsoft.azure.management.compute.AvailabilitySet;
  6. 6 import com.microsoft.azure.management.compute.AvailabilitySetSkuTypes;
  7. 7 import com.microsoft.azure.management.compute.CachingTypes;
  8. 8 import com.microsoft.azure.management.compute.Disk;
  9. 9 import com.microsoft.azure.management.compute.InstanceViewStatus;
  10. 10 import com.microsoft.azure.management.compute.StorageAccountTypes;
  11. 11 import com.microsoft.azure.management.compute.DiskInstanceView;
  12. 12 import com.microsoft.azure.management.compute.DiskSkuTypes;
  13. 13 import com.microsoft.azure.management.compute.VirtualMachine;
  14. 14 import com.microsoft.azure.management.compute.VirtualMachineSizeTypes;
  15. 15 import com.microsoft.azure.management.network.PublicIPAddress;
  16. 16 import com.microsoft.azure.management.network.Network;
  17. 17 import com.microsoft.azure.management.network.NetworkInterface;
  18. 18 import com.microsoft.azure.management.network.NetworkSecurityGroup;
  19. 19 import com.microsoft.azure.management.resources.ResourceGroup;
  20. 20 import com.microsoft.azure.management.resources.fluentcore.arm.Region;
  21. 21 import com.microsoft.azure.management.resources.fluentcore.model.Creatable;
  22. 22 import com.microsoft.rest.LogLevel;
  23. 23 import java.io.File;
  24. 24 import java.util.Scanner;
  25. 25
  26. 26 import com.microsoft.azure.AzureEnvironment;
  27. 27 import com.microsoft.azure.credentials.ApplicationTokenCredentials;
  28. 28 import com.microsoft.azure.credentials.AzureTokenCredentials;
  29. 29
  30. 30 public class testAzureApp {
  31. 31 public static void createVM()
  32. 32
  33. 33 {
  34. 34
  35. 35 // 使用AAD Application 方式获取 认证
  36. 36 AzureTokenCredentials credentials = new ApplicationTokenCredentials("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  37. 37 "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  38. 38 AzureEnvironment.AZURE_CHINA);
  39. 39 Azure azure = null;
  40. 40
  41. 41 azure = Azure.authenticate(credentials).withSubscription("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
  42. 42
  43. 43 System.out.println("Creating resource group...");
  44. 44 // ResourceGroup resourceGroup =
  45. 45 // azure.resourceGroups().define("myResourceGroup").withRegion(Region.CHINA_NORTH)
  46. 46 // .create();
  47. 47
  48. 48 System.out.println("Creating availability set...");
  49. 49 AvailabilitySet availabilitySet = azure.availabilitySets().define("myAvailabilitySet")
  50. 50 .withRegion(Region.CHINA_NORTH).withExistingResourceGroup("myResourceGroup")
  51. 51 .withSku(AvailabilitySetSkuTypes.ALIGNED).create();
  52. 52
  53. 53 System.out.println("Creating public IP address...");
  54. 54 PublicIPAddress publicIPAddress = azure.publicIPAddresses().define("myPublicIP").withRegion(Region.CHINA_NORTH)
  55. 55 .withExistingResourceGroup("myResourceGroup").withDynamicIP().create();
  56. 56
  57. 57 System.out.println("Creating virtual network...");
  58. 58 Network network = azure.networks().define("myVN").withRegion(Region.CHINA_NORTH)
  59. 59 .withExistingResourceGroup("myResourceGroup").withAddressSpace("10.0.0.0/16")
  60. 60 .withSubnet("mySubnet", "10.0.0.0/24").create();
  61. 61
  62. 62 // NetworkSecurityGroup networksg =
  63. 63 // azure.networkSecurityGroups().getById("/subscriptions/xxxxxxxxxxxxxxxx/resourceGroups/xxxxxxxxxxxxxxxx/providers/Microsoft.Network/networkSecurityGroups/xxxxxxxxxxxxxxxx");
  64. 64 System.out.println("Creating network security group...");
  65. 65 NetworkSecurityGroup networksg = azure.networkSecurityGroups().define("myNSG").withRegion(Region.CHINA_NORTH)
  66. 66 .withExistingResourceGroup("myResourceGroup").create();
  67. 67
  68. 68 // inbound rule
  69. 69 networksg.update().defineRule("rule1").allowInbound().fromAddress("125.136.3.25").fromPort(5885).toAnyAddress()
  70. 70 .toAnyPort().withAnyProtocol().withPriority(300).attach().apply();
  71. 71 networksg.update().defineRule("rule2").allowInbound().fromAddress("125.136.3.55").fromPort(5899).toAnyAddress()
  72. 72 .toAnyPort().withAnyProtocol().withPriority(500).attach().apply();
  73. 73 // outbound rule
  74. 74 networksg.update().defineRule("rule3").allowOutbound().fromAddress("125.136.3.78").fromPort(6886).toAnyAddress()
  75. 75 .toAnyPort().withAnyProtocol().withPriority(600).attach().apply();
  76. 76
  77. 77 System.out.println("Creating network interface...");
  78. 78 NetworkInterface networkInterface = azure.networkInterfaces().define("myNIC").withRegion(Region.CHINA_NORTH)
  79. 79 .withExistingResourceGroup("myResourceGroup").withExistingPrimaryNetwork(network).withSubnet("mySubnet")
  80. 80 .withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(publicIPAddress)
  81. 81 .withExistingNetworkSecurityGroup(networksg).create();
  82. 82
  83. 83 System.out.println("Creating virtual machine...");
  84. 84 VirtualMachine virtualMachine = azure.virtualMachines().define("myVM").withRegion(Region.CHINA_NORTH)
  85. 85 .withExistingResourceGroup("myResourceGroup").withExistingPrimaryNetworkInterface(networkInterface)
  86. 86 .withLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
  87. 87 .withAdminUsername("azureuser").withAdminPassword("Azure12345678").withComputerName("myVM")
  88. 88 .withNewDataDisk(254, 0, CachingTypes.READ_WRITE, StorageAccountTypes.PREMIUM_LRS)
  89. 89 .withExistingAvailabilitySet(availabilitySet).withSize("Standard_DS1").create();
  90. 90
  91. 91 Scanner input = new Scanner(System.in);
  92. 92 System.out.println("Press enter to get information about the VM...");
  93. 93 input.nextLine();
  94. 94 }
  95. 95 }

JDK依赖 pom.xml

  1. <dependency>
  2. <groupId>com.microsoft.azure</groupId>
  3. <artifactId>azure</artifactId>
  4. <version>1.41.0</version>
  5. </dependency>

附录一:Java SDK获取所有订阅号代码

  1. PagedList<Subscription> allsubs= Azure.authenticate(credentials).subscriptions().list();

附录二:Java SDK获取当前订阅号下所有虚拟机代码

  1. PagedList<VirtualMachine> allvms = azure.virtualMachines().list();

附录三: Java SDK获取所有的VM Size对应的CPU核数,Memroy大小

  1. 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)的更多相关文章

  1. 【Azure 环境】【Azure Developer】使用Python代码获取Azure 中的资源的Metrics定义及数据

    问题描述 使用Python SDK来获取Azure上的各种资源的Metrics的名称以及Metrics Data的示例 问题解答 通过 azure-monitor-query ,可以创建一个 metr ...

  2. 利用Meida Service的Java SDK来调用Azure Media Services的Index V2实现视频字幕自动识别

    Azure Media Services新的Index V2 支持自动将视频文件中的语音自动识别成字幕文件WebVtt,非常方便的就可以跟Azure Media Player集成,将一个原来没字幕的视 ...

  3. 【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例

    当需要通过代码的方式执行PowerShell脚本时,可以参考以下的示例. Azure SDK中提供了两个方法来执行PowerShell脚本 (SDK Source Code: https://gith ...

  4. Azure机器学习入门(二)创建Azure机器学习工作区

    我们将开始深入了解如何使用Azure机器学习的基本功能,帮助您开始迈向Azure机器学习的数据科学家之路. Azure ML Studio (Azure Machine Learning Studio ...

  5. 【Azure Developer】【Python 】使用 azure.identity 和 azure.common.credentials 获取Azure AD的Access Token的两种方式

    问题描述 使用Python代码,展示如何从Azure AD 中获取目标资源的 Access Token. 如要了解如何从AAD中获取 client id,client secret,tenant id ...

  6. Azure机器学习入门(三)创建Azure机器学习实验

    在此动手实践中,我们将在Azure机器学习Studio中一步步地开发预测分析模型,首先我们从UCI机器学习库的链接下载普查收入数据集的样本并开始动手实践: http://archive.ics.uci ...

  7. JAVA 从一个List里删除包含另一个List的数据

    /** * 从listA里删除listB里有的数据 * @param listA * @param listB * @return */ public static List<String> ...

  8. 【Microsoft Azure学习之旅】Azure Java SDK - Service Bus的认证问题

    [2014年12月12日增加备注:12月10日,Microsoft Azure Java SDK team发布了v0.7.0版本,增加对Service Bus SAS的支持,已解决这个问题:-)] 最 ...

  9. 在Azure China用自定义镜像创建Azure VM Scale Set

    在Azure China用自定义镜像创建Azure VM Scale Set 在此感谢世纪互联的工程师Johnny Lee和Lan,你们给了我很大的帮助.因为Azure China的官网没有给出完整的 ...

随机推荐

  1. list 打乱排序

    public IList<T> RandomSortList<T>(List<T> ListT) { Random random = new Random(); L ...

  2. 【Notes_9】现代图形学入门——光线追踪(基本原理)

    跟着闫令琪老师的课程学习,总结自己学习到的知识点 课程网址GAMES101 B站课程地址GAMES101 课程资料百度网盘[提取码:0000] 目录 光线追踪 为什么要光线追踪 soft shadow ...

  3. Java基础语法:static修饰符

    一.静态变量 描述: 在类中,使用'static'修饰的成员变量,就是静态变量,反之为非静态变量. 区别: 静态变量属于类的,可以使用类名来访问:非静态变量是属于对象的,必须使用对象来访问. 静态变量 ...

  4. Hyperf-事件机制+异常处理

    Hyperf-事件机制+异常处理 标签(空格分隔): php, hyperf 异常处理器 在 Hyperf 里,业务代码都运行在 Worker 进程 上,也就意味着一旦任意一个请求的业务存在没有捕获处 ...

  5. wxWidgets源码分析(6) - 窗口关闭过程

    目录 窗口关闭过程 调用流程 关闭文档 删除视图 删除文档对象 关闭Frame App清理 多文档窗口的关闭 多文档父窗口关闭 多文档子窗口关闭 窗口的正式删除 窗口关闭过程总结 如何手工删除view ...

  6. wxWidgets源码分析(2) - App主循环

    目录 APP主循环 MainLoop 消息循环对象的创建 消息循环 消息派发 总结 APP主循环 MainLoop 前面的wxApp的启动代码可以看到,执行完成wxApp::OnInit()函数后,接 ...

  7. 解决vue 绑定事件会覆盖默认参数的问题

    解决vue 绑定事件会覆盖默认参数的问题 在使用一些ui框架的时候,某些组件的框架中的事件所规定的参数不能满足实际开发的需要,但是直接传入参数会把默认的参数覆盖掉 解决方法:将参数放入箭头函数中,传递 ...

  8. Python切换版本工具pyenv

    目录 安装pyenv 安装与查看py版本 切换py版本 结合ide使用示例 和virtualenv的一些区别 参考文献 使用了一段时间,我发现这玩意根本不是什么神器,简直就是垃圾,安装多版本总是失败, ...

  9. 话说 synchronized

    一.前言 ​ 说起java的锁呀,我们先想到的肯定是synchronized[ˈsɪŋ krə naɪ zd]了 ,这个单词很拗口,会读这个单词在以后的面试中很加分(我面试过一些人 不会读 ,他们说的 ...

  10. Flink的日志配置

    ------------恢复内容开始------------ 介绍flink在本地运行和on yarn运行时的日志配置. 很多现代框架都是用门面模式进行日志输出,例如使用Slf4j中的接口输出日志,具 ...