This repository has been archived by the owner on Dec 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Program.cs
232 lines (198 loc) · 10.4 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using System;
using System.Collections.Generic;
namespace CreateVirtualMachineUsingSpecializedDiskFromVhd
{
public class Program
{
private static string userName = Utilities.CreateUsername();
private static string password = Utilities.CreatePassword();
private static Region region = Region.USWestCentral;
/**
* Azure Compute sample for managing virtual machines.
* - Create an un-managed virtual machine from PIR image with data disks
* - Create managed disks from specialized un-managed OS and Data disk of virtual machine
* - Create a virtual machine by attaching the managed disks
* - Get SAS Uri to the virtual machine's managed disks
*/
public static void RunSample(IAzure azure)
{
var linuxVmName1 = Utilities.CreateRandomName("VM1");
var linuxVmName2 = Utilities.CreateRandomName("VM2");
var managedOSDiskName = Utilities.CreateRandomName("ds-os-");
var managedDataDiskNamePrefix = Utilities.CreateRandomName("ds-data-");
var rgName = Utilities.CreateRandomName("rgCOMV");
var publicIpDnsLabel = Utilities.CreateRandomName("pip");
var storageAccountName = Utilities.CreateRandomName("stg");
var apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Samples/Asset/install_apache.sh";
var apacheInstallCommand = "bash install_apache.sh";
var apacheInstallScriptUris = new List<string>();
apacheInstallScriptUris.Add(apacheInstallScript);
try
{
//=============================================================
// Create a Linux VM using an image from PIR (Platform Image Repository)
Utilities.Log("Creating a un-managed Linux VM");
var linuxVM = azure.VirtualMachines.Define(linuxVmName1)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithNewPrimaryNetwork("10.0.0.0/28")
.WithPrimaryPrivateIPAddressDynamic()
.WithNewPrimaryPublicIPAddress(publicIpDnsLabel)
.WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
.WithRootUsername(userName)
.WithRootPassword(password)
.WithUnmanagedDisks()
.DefineUnmanagedDataDisk("disk-1")
.WithNewVhd(50)
.WithLun(1)
.Attach()
.DefineUnmanagedDataDisk("disk-2")
.WithNewVhd(50)
.WithLun(2)
.Attach()
.DefineNewExtension("CustomScriptForLinux")
.WithPublisher("Microsoft.OSTCExtensions")
.WithType("CustomScriptForLinux")
.WithVersion("1.4")
.WithMinorVersionAutoUpgrade()
.WithPublicSetting("fileUris", apacheInstallScriptUris)
.WithPublicSetting("commandToExecute", apacheInstallCommand)
.Attach()
.WithNewStorageAccount(storageAccountName)
.WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
.Create();
Utilities.Log("Created a Linux VM with un-managed OS and data disks: " + linuxVM.Id);
Utilities.PrintVirtualMachine(linuxVM);
// Gets the specialized OS and Data disk VHDs of the virtual machine
//
var specializedOSVhdUri = linuxVM.OSUnmanagedDiskVhdUri;
var dataVhdUris = new List<string>();
foreach (var dataDisk in linuxVM.UnmanagedDataDisks.Values)
{
dataVhdUris.Add(dataDisk.VhdUri);
}
//=============================================================
// Delete the virtual machine
Utilities.Log("Deleting VM: " + linuxVM.Id);
azure.VirtualMachines.DeleteById(linuxVM.Id);
Utilities.Log("Deleted the VM");
//=============================================================
// Create Managed disk from the specialized OS VHD
Utilities.Log($"Creating managed disk from the specialized OS VHD: {specializedOSVhdUri} ");
var osDisk = azure.Disks.Define(managedOSDiskName)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithLinuxFromVhd(specializedOSVhdUri)
.WithStorageAccountName(storageAccountName)
.WithSizeInGB(100)
.Create();
Utilities.Log("Created managed disk holding OS: " + osDisk.Id);
// Utilities.Print(osDisk); TODO
//=============================================================
// Create Managed disks from the Data VHDs
var dataDisks = new List<IDisk>();
var i = 0;
foreach (String dataVhdUri in dataVhdUris)
{
Utilities.Log($"Creating managed disk from the Data VHD: {dataVhdUri}");
var dataDisk = azure.Disks.Define(managedDataDiskNamePrefix + "-" + i)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithData()
.FromVhd(dataVhdUri)
.WithStorageAccountName(storageAccountName)
.WithSizeInGB(150)
.WithSku(DiskSkuTypes.StandardLRS)
.Create();
dataDisks.Add(dataDisk);
Utilities.Log("Created managed disk holding data: " + dataDisk.Id);
// Utilities.Print(dataDisk); TODO
i++;
}
//=============================================================
// Create a Linux VM by attaching the disks
Utilities.Log("Creating a Linux VM using specialized OS and data disks");
var linuxVM2 = azure.VirtualMachines.Define(linuxVmName2)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithNewPrimaryNetwork("10.0.0.0/28")
.WithPrimaryPrivateIPAddressDynamic()
.WithoutPrimaryPublicIPAddress()
.WithSpecializedOSDisk(osDisk, OperatingSystemTypes.Linux)
.WithExistingDataDisk(dataDisks[0])
.WithExistingDataDisk(dataDisks[1], 1, CachingTypes.ReadWrite)
.WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
.Create();
Utilities.PrintVirtualMachine(linuxVM2);
var dataDiskIds = new List<string>();
foreach (var disk in linuxVM2.DataDisks.Values)
{
dataDiskIds.Add(disk.Id);
}
//=============================================================
// Detach the data disks from the virtual machine
Utilities.Log("Updating VM by detaching the data disks");
linuxVM2.Update()
.WithoutDataDisk(0)
.WithoutDataDisk(1)
.Apply();
Utilities.PrintVirtualMachine(linuxVM2);
//=============================================================
// Get the readonly SAS URI to the data disks
Utilities.Log("Getting data disks SAS Uris");
foreach (String diskId in dataDiskIds)
{
var dataDisk = azure.Disks.GetById(diskId);
var dataDiskSasUri = dataDisk.GrantAccess(24 * 60);
Utilities.Log($"Data disk SAS Uri: {dataDiskSasUri}");
}
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.DeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception g)
{
Utilities.Log(g);
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception e)
{
Utilities.Log(e);
}
}
}
}