-
Notifications
You must be signed in to change notification settings - Fork 2
/
Program.cs
209 lines (182 loc) · 9.91 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
// 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.Network.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Samples.Common;
using System;
using System.Collections.Generic;
namespace CreateVirtualMachinesInParallel
{
public class Program
{
private static readonly string Username = Utilities.CreateUsername();
private static readonly string Password = Utilities.CreatePassword();
/**
* Azure compute sample for creating multiple virtual machines in parallel.
* - Define 1 virtual network per region
* - Define 1 storage account per region
* - Create 5 virtual machines in 2 regions using defined virtual network and storage account
* - Create a traffic manager to route traffic across the virtual machines
*/
public static void RunSample(IAzure azure)
{
string rgName = SdkContext.RandomResourceName("rgCOMV", 10);
IDictionary<Region, int> virtualMachinesByLocation = new Dictionary<Region, int>();
virtualMachinesByLocation.Add(Region.USEast, 5);
virtualMachinesByLocation.Add(Region.USSouthCentral, 5);
try
{
//=============================================================
// Create a resource group (Where all resources gets created)
//
var resourceGroup = azure.ResourceGroups.Define(rgName)
.WithRegion(Region.USWest)
.Create();
Utilities.Log($"Created a new resource group - {resourceGroup.Id}");
var publicIpCreatableKeys = new List<string>();
// Prepare a batch of Creatable definitions
//
var creatableVirtualMachines = new List<ICreatable<IVirtualMachine>>();
foreach (var entry in virtualMachinesByLocation)
{
var region = entry.Key;
var vmCount = entry.Value;
//=============================================================
// Create 1 network creatable per region
// Prepare Creatable Network definition (Where all the virtual machines get added to)
//
var networkName = SdkContext.RandomResourceName("vnetCOPD-", 20);
var networkCreatable = azure.Networks
.Define(networkName)
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup)
.WithAddressSpace("172.16.0.0/16");
//=============================================================
// Create 1 storage creatable per region (For storing VMs disk)
//
var storageAccountName = SdkContext.RandomResourceName("stgcopd", 20);
var storageAccountCreatable = azure.StorageAccounts
.Define(storageAccountName)
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup);
var linuxVMNamePrefix = SdkContext.RandomResourceName("vm-", 15);
for (int i = 1; i <= vmCount; i++)
{
//=============================================================
// Create 1 public IP address creatable
//
var publicIpAddressCreatable = azure.PublicIPAddresses
.Define($"{linuxVMNamePrefix}-{i}")
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup)
.WithLeafDomainLabel($"{linuxVMNamePrefix}-{i}");
publicIpCreatableKeys.Add(publicIpAddressCreatable.Key);
//=============================================================
// Create 1 virtual machine creatable
var virtualMachineCreatable = azure.VirtualMachines
.Define($"{linuxVMNamePrefix}-{i}")
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup)
.WithNewPrimaryNetwork(networkCreatable)
.WithPrimaryPrivateIPAddressDynamic()
.WithNewPrimaryPublicIPAddress(publicIpAddressCreatable)
.WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
.WithRootUsername(Username)
.WithRootPassword(Password)
.WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
.WithNewStorageAccount(storageAccountCreatable);
creatableVirtualMachines.Add(virtualMachineCreatable);
}
}
//=============================================================
// Create !!
var t1 = DateTimeOffset.Now.UtcDateTime;
Utilities.Log("Creating the virtual machines");
var virtualMachines = azure.VirtualMachines.Create(creatableVirtualMachines.ToArray());
var t2 = DateTimeOffset.Now.UtcDateTime;
Utilities.Log("Created virtual machines");
foreach (var virtualMachine in virtualMachines)
{
Utilities.Log(virtualMachine.Id);
}
Utilities.Log($"Virtual machines create: took {(t2 - t1).TotalSeconds } seconds to create == " + creatableVirtualMachines.Count + " == virtual machines");
var publicIpResourceIds = new List<string>();
foreach (string publicIpCreatableKey in publicIpCreatableKeys)
{
var pip = (IPublicIPAddress)virtualMachines.CreatedRelatedResource(publicIpCreatableKey);
publicIpResourceIds.Add(pip.Id);
}
//=============================================================
// Create 1 Traffic Manager Profile
//
var trafficManagerName = SdkContext.RandomResourceName("tra", 15);
var profileWithEndpoint = azure.TrafficManagerProfiles.Define(trafficManagerName)
.WithExistingResourceGroup(resourceGroup)
.WithLeafDomainLabel(trafficManagerName)
.WithPerformanceBasedRouting();
int endpointPriority = 1;
Microsoft.Azure.Management.TrafficManager.Fluent.TrafficManagerProfile.Definition.IWithCreate profileWithCreate = null;
foreach (var publicIpResourceId in publicIpResourceIds)
{
var endpointName = $"azendpoint-{endpointPriority}";
if (endpointPriority == 1)
{
profileWithCreate = profileWithEndpoint.DefineAzureTargetEndpoint(endpointName)
.ToResourceId(publicIpResourceId)
.WithRoutingPriority(endpointPriority)
.Attach();
}
else
{
profileWithCreate = profileWithCreate.DefineAzureTargetEndpoint(endpointName)
.ToResourceId(publicIpResourceId)
.WithRoutingPriority(endpointPriority)
.Attach();
}
endpointPriority++;
}
var trafficManagerProfile = profileWithCreate.Create();
Utilities.Log("Created a traffic manager profile - " + trafficManagerProfile.Id);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.DeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (Exception)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
}
}
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);
}
}
}
}