-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProgram.cs
483 lines (449 loc) · 24.9 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.Network.Models;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Compute;
using Azure.ResourceManager.Network;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Samples.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure;
using Azure.Identity;
namespace ManageVirtualMachineScaleSetAsync
{
public class Program
{
/**
* Azure Compute sample for managing virtual machine scale sets with un-managed disks -
* - Create a virtual machine scale set behind an Internet facing load balancer
* - Install Apache Web servers in virtual machines in the virtual machine scale set
* - List scale set virtual machine instances and SSH collection string
* - Stop a virtual machine scale set
* - Start a virtual machine scale set
* - Update a virtual machine scale set
* - Double the no. of virtual machines
* - Restart a virtual machine scale set
*/
public async static Task RunSampleAsync(ArmClient client)
{
AzureLocation region = AzureLocation.EastUS;
var rgName = Utilities.CreateRandomName("rgCOVS");
var vmssNetworkConfigurationName = Utilities.CreateRandomName("networkConfiguration");
var ipConfigurationName = Utilities.CreateRandomName("ipconfigruation");
var vnetName = Utilities.CreateRandomName("vnet");
var loadBalancerName1 = Utilities.CreateRandomName("intlb" + "-");
var publicIpName = "pip-" + loadBalancerName1;
var frontendName = loadBalancerName1 + "-FE1";
var backendPoolName1 = loadBalancerName1 + "-BAP1";
var backendPoolName2 = loadBalancerName1 + "-BAP2";
var domainNameLabel = Utilities.CreateRandomName("domain");
var httpProbe = "httpProbe";
var httpsProbe = "httpsProbe";
var httpLoadBalancingRule = "httpRule";
var httpsLoadBalancingRule = "httpsRule";
var natPool50XXto22 = "natPool50XXto22";
var natPool60XXto23 = "natPool60XXto23";
var vmssName = Utilities.CreateRandomName("vmss");
var userName = Utilities.CreateUsername();
var sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD [email protected]";
var apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Samples/Asset/install_apache.sh";
var fileUris = new List<string>();
var lro = await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName, new ResourceGroupData(AzureLocation.EastUS));
var resourceGroup = lro.Value;
fileUris.Add(apacheInstallScript);
try
{
//=============================================================
// Create a virtual network with a frontend subnet
Utilities.Log("Creating virtual network with a frontend subnet ...");
Utilities.Log("Creating a public IP address...");
VirtualNetworkResource network = null;
PublicIPAddressResource publicIPAddress = null;
var networkCollection = resourceGroup.GetVirtualNetworks();
var networkData = new VirtualNetworkData()
{
Location = region,
AddressPrefixes =
{
"172.16.1.0/24"
},
Subnets =
{
new SubnetData()
{
Name = "Front-end",
}
},
};
var networkResource = (await networkCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, vnetName, networkData)).Value;
Utilities.Log("Created a virtual network");
// Print the virtual network details
Utilities.PrintVirtualNetwork(networkResource);
var publicIpAddressCollection = resourceGroup.GetPublicIPAddresses();
var publicIPAddressData = new PublicIPAddressData()
{
Location = region,
Tags = { { "key", "value" } },
PublicIPAllocationMethod = NetworkIPAllocationMethod.Dynamic,
DnsSettings = new PublicIPAddressDnsSettings()
{
DomainNameLabel = domainNameLabel
}
};
var publicIpAddress =(await publicIpAddressCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, publicIpName, publicIPAddressData)).Value;
Utilities.Log("Created a public IP address");
// Print the virtual network details
Utilities.PrintIPAddress(publicIPAddress);
//=============================================================
// Create an Internet facing load balancer with
// One frontend IP address
// Two backend address pools which contain network interfaces for the virtual
// machines to receive HTTP and HTTPS network traffic from the load balancer
// Two load balancing rules for HTTP and HTTPS to map public ports on the load
// balancer to ports in the backend address pool
// Two probes which contain HTTP and HTTPS health probes used to check availability
// of virtual machines in the backend address pool
// Three inbound NAT rules which contain rules that map a public port on the load
// balancer to a port for a specific virtual machine in the backend address pool
// - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23
Utilities.Log("Creating a Internet facing load balancer with ...");
Utilities.Log("- A frontend IP address");
Utilities.Log("- Two backend address pools which contain network interfaces for the virtual\n"
+ " machines to receive HTTP and HTTPS network traffic from the load balancer");
Utilities.Log("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n"
+ " balancer to ports in the backend address pool");
Utilities.Log("- Two probes which contain HTTP and HTTPS health probes used to check availability\n"
+ " of virtual machines in the backend address pool");
Utilities.Log("- Two inbound NAT rules which contain rules that map a public port on the load\n"
+ " balancer to a port for a specific virtual machine in the backend address pool\n"
+ " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23");
var loadBalancerCollection = resourceGroup.GetLoadBalancers();
var loadBalancerData = new LoadBalancerData()
{
Location = region,
LoadBalancingRules =
{
new LoadBalancingRuleData()
{
Name = httpLoadBalancingRule,
Protocol = LoadBalancingTransportProtocol.Tcp,
FrontendPort = 80,
ProbeId = new ResourceIdentifier(httpProbe),
BackendAddressPools =
{
new Azure.ResourceManager.Resources.Models.WritableSubResource()
{
Id = new ResourceIdentifier(backendPoolName1)
}
}
},
new LoadBalancingRuleData()
{
Name= httpsLoadBalancingRule,
Protocol= LoadBalancingTransportProtocol.Tcp,
BackendPort = 443,
ProbeId = new ResourceIdentifier(httpsProbe),
BackendAddressPools =
{
new Azure.ResourceManager.Resources.Models.WritableSubResource()
{
Id = new ResourceIdentifier(backendPoolName2)
}
}
}
},
// Add nat pools to enable direct VM connectivity for
// SSH to port 22 and TELNET to port 23
InboundNatRules =
{
new InboundNatRuleData()
{
Name = natPool50XXto22,
Protocol= LoadBalancingTransportProtocol.Tcp,
BackendPort = 22,
FrontendPortRangeStart = 5000,
FrontendPortRangeEnd = 5099,
},
new InboundNatRuleData()
{
Name = natPool60XXto23,
Protocol= LoadBalancingTransportProtocol.Tcp,
BackendPort = 23,
FrontendPortRangeStart = 6000,
FrontendPortRangeEnd = 6099,
}
},
// Add two probes one per rule
Probes =
{
new ProbeData()
{
RequestPath = "/",
Port = 80,
},
new ProbeData()
{
RequestPath = "/",
Port = 443,
}
}
};
var loadBalancer = (await loadBalancerCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, loadBalancerName1, loadBalancerData)).Value;
// Print load balancer details
Utilities.Log("Created a load balancer");
Utilities.PrintLoadBalancer(loadBalancer);
//=============================================================
// Create a virtual machine scale set with three virtual machines
// And, install Apache Web servers on them
Utilities.Log("Creating virtual machine scale set with three virtual machines"
+ "in the frontend subnet ...");
var t1 = new DateTime();
var vmScaleSetVMCollection = resourceGroup.GetVirtualMachineScaleSets();
var scaleSetData = new VirtualMachineScaleSetData(region)
{
Sku = new ComputeSku()
{
Name = "StandardD3v2",
Capacity = 3,
Tier = "Standard"
},
VirtualMachineProfile = new VirtualMachineScaleSetVmProfile()
{
OSProfile = new VirtualMachineScaleSetOSProfile()
{
LinuxConfiguration = new LinuxConfiguration()
{
SshPublicKeys =
{
new SshPublicKeyConfiguration()
{
KeyData = sshKey,
Path = $"/home/{userName}/.ssh/authorized_keys"
}
}
}
},
StorageProfile = new VirtualMachineScaleSetStorageProfile()
{
DataDisks =
{
new VirtualMachineScaleSetDataDisk(1, DiskCreateOptionType.FromImage)
{
DiskSizeGB = 100,
Caching = CachingType.ReadWrite
},
new VirtualMachineScaleSetDataDisk(2, DiskCreateOptionType.FromImage)
{
DiskSizeGB = 100,
Caching = CachingType.ReadWrite
},
new VirtualMachineScaleSetDataDisk(3, DiskCreateOptionType.FromImage)
{
DiskSizeGB = 100,
},
},
ImageReference = new ImageReference()
{
Publisher = "Canonical",
Offer = "UbuntuServer",
Sku = "16.04-LTS",
Version = "latest"
}
},
NetworkProfile = new VirtualMachineScaleSetNetworkProfile()
{
NetworkInterfaceConfigurations =
{
new VirtualMachineScaleSetNetworkConfiguration(vmssNetworkConfigurationName)
{
IPConfigurations =
{
new VirtualMachineScaleSetIPConfiguration(ipConfigurationName)
{
LoadBalancerInboundNatPools =
{
new Azure.ResourceManager.Resources.Models.WritableSubResource()
{
Id = new ResourceIdentifier(natPool50XXto22)
},
new Azure.ResourceManager.Resources.Models.WritableSubResource()
{
Id = new ResourceIdentifier(natPool60XXto23)
}
},
ApplicationGatewayBackendAddressPools =
{
new Azure.ResourceManager.Resources.Models.WritableSubResource()
{
Id = new ResourceIdentifier(backendPoolName1)
},
new Azure.ResourceManager.Resources.Models.WritableSubResource()
{
Id = new ResourceIdentifier(backendPoolName2)
},
},
LoadBalancerBackendAddressPools =
{
new Azure.ResourceManager.Resources.Models.WritableSubResource()
{
Id = new ResourceIdentifier(loadBalancer.Data.Name)
}
},
SubnetId = networkResource.Id,
Primary = true,
}
}
}
}
},
ExtensionProfile = new VirtualMachineScaleSetExtensionProfile()
{
Extensions =
{
new VirtualMachineScaleSetExtensionData()
{
Publisher = "Microsoft.OSTCExtensions",
ExtensionType = "CustomScriptForLinux",
TypeHandlerVersion = "1.4",
Settings = new BinaryData("{\"commandToExecute\":\"bash install_apache.sh\"}")
}
}
}
},
};
var t2 = new DateTime();
Utilities.Log("Created a virtual machine scale set with "
+ "3 Linux VMs & Apache Web servers on them: (took "
+ (t2 - t1).TotalSeconds + " seconds) ");
Utilities.Log();
var scaleSet = (await vmScaleSetVMCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, vmssName, scaleSetData)).Value;
//=============================================================
// List virtual machine scale set instance network interfaces and SSH connection string
Utilities.Log("Listing scale set virtual machine instance network interfaces and SSH connection string...");
await foreach (var instance in vmScaleSetVMCollection.GetAllAsync())
{
Utilities.Log("Scale set virtual machine instance #" + instance.Id);
Utilities.Log(instance.Id);
var networkInterfaces = instance.Data.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations;
// Pick the first NIC
var networkInterface = networkInterfaces.ElementAt(0);
foreach (var ipConfig in networkInterface.IPConfigurations)
{
if (ipConfig.Primary == true)
{
var loadbalancer =await resourceGroup.GetLoadBalancerAsync(ipConfig.ApplicationGatewayBackendAddressPools.ElementAt(0).Id);
var natRules = loadBalancer.Data.InboundNatRules;
foreach (var natRule in natRules)
{
if (natRule.BackendPort == 22)
{
Utilities.Log("SSH connection string: " + userName + "@" + publicIPAddress.Data.DnsSettings.ReverseFqdn + ":" + natRule.FrontendPort);
break;
}
}
break;
}
}
}
//=============================================================
// Stop the virtual machine scale set
Utilities.Log("Stopping virtual machine scale set ...");
await scaleSet.PowerOffAsync(Azure.WaitUntil.Completed);
Utilities.Log("Stopped virtual machine scale set");
//=============================================================
// Deallocate the virtual machine scale set
Utilities.Log("De-allocating virtual machine scale set ...");
await scaleSet.DeallocateAsync(Azure.WaitUntil.Completed);
Utilities.Log("De-allocated virtual machine scale set");
//=============================================================
// Start the virtual machine scale set
Utilities.Log("Starting virtual machine scale set ...");
await scaleSet.PowerOnAsync(WaitUntil.Completed);
Utilities.Log("Started virtual machine scale set");
//=============================================================
// Update the virtual machine scale set
// - double the no. of virtual machines
Utilities.Log("Updating virtual machine scale set "
+ "- double the no. of virtual machines ...");
await scaleSet.UpdateAsync(WaitUntil.Completed, new VirtualMachineScaleSetPatch()
{
Sku = new ComputeSku()
{
Name = "StandardD3v2",
Capacity = 6,
Tier = "Standard"
},
VirtualMachineProfile = new VirtualMachineScaleSetUpdateVmProfile()
{
StorageProfile = new VirtualMachineScaleSetUpdateStorageProfile()
{
DataDisks =
{
new VirtualMachineScaleSetDataDisk(0, DiskCreateOptionType.FromImage)
{
DiskSizeGB = 100,
Caching = CachingType.ReadWrite
},
new VirtualMachineScaleSetDataDisk(200, DiskCreateOptionType.FromImage)
{
DiskSizeGB = 100,
Caching = CachingType.ReadWrite
}
},
}
}
});
Utilities.Log("Doubled the no. of virtual machines in "
+ "the virtual machine scale set");
//=============================================================
// re-start virtual machine scale set
Utilities.Log("re-starting virtual machine scale set ...");
await scaleSet.RestartAsync(Azure.WaitUntil.Completed);
Utilities.Log("re-started virtual machine scale set");
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
await resourceGroup.DeleteAsync(WaitUntil.Completed);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resourcesinAzure. No clean up is necessary");
}
catch (Exception g)
{
Utilities.Log(g);
}
}
}
public static async Task Main(string[] args)
{
try
{
//=============================================================
// Authenticate
var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
ArmClient client = new ArmClient(credential, subscription);
// Print selected subscription
Utilities.Log("Selected subscription: " + client.GetSubscriptions().Id);
await RunSampleAsync(client);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
}