-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathProgram.cs
424 lines (366 loc) · 20.2 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
namespace aci_doc_sample_dotnet
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ContainerInstance.Fluent;
using Microsoft.Azure.Management.ContainerInstance.Fluent.Models;
class Program
{
static void Main(string[] args)
{
#region local_config
string resourceGroupName = SdkContext.RandomResourceName("rg-aci-", 6);
string containerGroupName = SdkContext.RandomResourceName("aci-", 6);
string multiContainerGroupName = containerGroupName + "-multi";
string asyncContainerGroupName = containerGroupName + "-async";
string taskContainerGroupName = containerGroupName + "-task";
string containerImageApp = "microsoft/aci-helloworld";
string containerImageSidecar = "microsoft/aci-tutorial-sidecar";
string taskContainerImage = "microsoft/aci-wordcount";
// Set the AZURE_AUTH_LOCATION environment variable with the full
// path to an auth file. Create an auth file with the Azure CLI:
// az ad sp create-for-rbac --sdk-auth > my.azureauth
string authFilePath = Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION");
// Authenticate with Azure
IAzure azure = GetAzureContext(authFilePath);
#endregion
// Create a resource group in which the container groups are to be
// created.
CreateResourceGroup(azure, resourceGroupName, Region.USEast);
// Demonstrate various container group operations
CreateContainerGroup(azure, resourceGroupName, containerGroupName, containerImageApp);
CreateContainerGroupMulti(azure, resourceGroupName, multiContainerGroupName, containerImageApp, containerImageSidecar);
CreateContainerGroupWithPolling(azure, resourceGroupName, asyncContainerGroupName, containerImageApp);
RunTaskBasedContainer(azure, resourceGroupName, taskContainerGroupName, taskContainerImage, null);
ListContainerGroups(azure, resourceGroupName);
PrintContainerGroupDetails(azure, resourceGroupName, containerGroupName);
// Clean up container groups
Console.WriteLine($"\nPress ENTER to delete all container groups...");
Console.ReadLine();
DeleteContainerGroup(azure, resourceGroupName, containerGroupName);
DeleteContainerGroup(azure, resourceGroupName, multiContainerGroupName);
DeleteContainerGroup(azure, resourceGroupName, asyncContainerGroupName);
DeleteContainerGroup(azure, resourceGroupName, taskContainerGroupName);
// Remove resource group (if the user so chooses)
Console.WriteLine();
Console.Write($"Delete resource group '{resourceGroupName}'? [yes] no: ");
string response = Console.ReadLine().Trim().ToLower();
if (response != "n" && response != "no")
{
DeleteResourceGroup(azure, resourceGroupName);
}
Console.WriteLine();
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
#region azure_auth
/// <summary>
/// Returns an authenticated Azure context using the credentials in the
/// specified auth file.
/// </summary>
/// <param name="authFilePath">The full path to a credentials file on the local filesystem.</param>
/// <returns>Authenticated IAzure context.</returns>
private static IAzure GetAzureContext(string authFilePath)
{
IAzure azure;
ISubscription sub;
try
{
Console.WriteLine($"Authenticating with Azure using credentials in file at {authFilePath}");
azure = Azure.Authenticate(authFilePath).WithDefaultSubscription();
sub = azure.GetCurrentSubscription();
Console.WriteLine($"Authenticated with subscription '{sub.DisplayName}' (ID: {sub.SubscriptionId})");
}
catch (Exception ex)
{
Console.WriteLine($"\nFailed to authenticate:\n{ex.Message}");
if (String.IsNullOrEmpty(authFilePath))
{
Console.WriteLine("Have you set the AZURE_AUTH_LOCATION environment variable?");
}
throw;
}
return azure;
}
#endregion
#region create_resource_group
/// <summary>
/// Creates a resource group of the specified name.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group to be created.</param>
/// <param name="azureRegion">The Region in which to create the resource group.</param>
private static void CreateResourceGroup(IAzure azure, string resourceGroupName, Region azureRegion)
{
Console.WriteLine($"\nCreating resource group '{resourceGroupName}'...");
azure.ResourceGroups.Define(resourceGroupName)
.WithRegion(azureRegion)
.Create();
}
#endregion
#region create_container_group
/// <summary>
/// Creates a container group with a single container.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage">The container image name and tag, for example 'microsoft\aci-helloworld:latest'.</param>
private static void CreateContainerGroup(IAzure azure,
string resourceGroupName,
string containerGroupName,
string containerImage)
{
Console.WriteLine($"\nCreating container group '{containerGroupName}'...");
// Get the resource group's region
IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
Region azureRegion = resGroup.Region;
// Create the container group
var containerGroup = azure.ContainerGroups.Define(containerGroupName)
.WithRegion(azureRegion)
.WithExistingResourceGroup(resourceGroupName)
.WithLinux()
.WithPublicImageRegistryOnly()
.WithoutVolume()
.DefineContainerInstance(containerGroupName + "-1")
.WithImage(containerImage)
.WithExternalTcpPort(80)
.WithCpuCoreCount(1.0)
.WithMemorySizeInGB(1)
.Attach()
.WithDnsPrefix(containerGroupName)
.Create();
Console.WriteLine($"Once DNS has propagated, container group '{containerGroup.Name}' will be reachable at http://{containerGroup.Fqdn}");
}
#endregion
#region create_container_group_multi
/// <summary>
/// Creates a container group with two containers in the specified resource group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage1">The first container image name and tag, for example 'microsoft\aci-helloworld:latest'.</param>
/// <param name="containerImage2">The second container image name and tag, for example 'microsoft\aci-tutorial-sidecar:latest'.</param>
private static void CreateContainerGroupMulti(IAzure azure,
string resourceGroupName,
string containerGroupName,
string containerImage1,
string containerImage2)
{
Console.WriteLine($"\nCreating multi-container container group '{containerGroupName}'...");
// Get the resource group's region
IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
Region azureRegion = resGroup.Region;
// Create the container group
var containerGroup = azure.ContainerGroups.Define(containerGroupName)
.WithRegion(azureRegion)
.WithExistingResourceGroup(resourceGroupName)
.WithLinux()
.WithPublicImageRegistryOnly()
.WithoutVolume()
.DefineContainerInstance(containerGroupName + "-1")
.WithImage(containerImage1)
.WithExternalTcpPort(80)
.WithCpuCoreCount(0.5)
.WithMemorySizeInGB(1)
.Attach()
.DefineContainerInstance(containerGroupName + "-2")
.WithImage(containerImage2)
.WithoutPorts()
.WithCpuCoreCount(0.5)
.WithMemorySizeInGB(1)
.Attach()
.WithDnsPrefix(containerGroupName)
.Create();
Console.WriteLine($"Once DNS has propagated, container group '{containerGroup.Name}' will be reachable at http://{containerGroup.Fqdn}");
}
#endregion
#region create_container_group_polling
/// <summary>
/// Creates a container group with a single container asynchronously, and
/// polls its status until its state is 'Running'.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage">The container image name and tag, for example 'microsoft\aci-helloworld:latest'.</param>
private static void CreateContainerGroupWithPolling(IAzure azure,
string resourceGroupName,
string containerGroupName,
string containerImage)
{
Console.WriteLine($"\nCreating container group '{containerGroupName}'...");
// Get the resource group's region
IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
Region azureRegion = resGroup.Region;
// Create the container group using a fire-and-forget task
Task.Run(() =>
azure.ContainerGroups.Define(containerGroupName)
.WithRegion(azureRegion)
.WithExistingResourceGroup(resourceGroupName)
.WithLinux()
.WithPublicImageRegistryOnly()
.WithoutVolume()
.DefineContainerInstance(containerGroupName + "-1")
.WithImage(containerImage)
.WithExternalTcpPort(80)
.WithCpuCoreCount(1.0)
.WithMemorySizeInGB(1)
.Attach()
.WithDnsPrefix(containerGroupName)
.CreateAsync()
);
// Poll for the container group
IContainerGroup containerGroup = null;
while(containerGroup == null)
{
containerGroup = azure.ContainerGroups.GetByResourceGroup(resourceGroupName, containerGroupName);
Console.Write(".");
SdkContext.DelayProvider.Delay(1000);
}
Console.WriteLine();
// Poll until the container group is running
while(containerGroup.State != "Running")
{
Console.WriteLine($"Container group state: {containerGroup.Refresh().State}");
Thread.Sleep(1000);
}
Console.WriteLine($"\nOnce DNS has propagated, container group '{containerGroup.Name}' will be reachable at http://{containerGroup.Fqdn}");
}
#endregion
#region create_container_group_task
/// <summary>
/// Creates a container group with a single task-based container who's
/// restart policy is 'Never'. If specified, the container runs a custom
/// command line at startup.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage">The container image name and tag, for example 'microsoft\aci-wordcount:latest'.</param>
/// <param name="startCommandLine">The command line that should be executed when the container starts. This value can be <c>null</c>.</param>
private static void RunTaskBasedContainer(IAzure azure,
string resourceGroupName,
string containerGroupName,
string containerImage,
string startCommandLine)
{
// If a start command wasn't specified, use a default
if (String.IsNullOrEmpty(startCommandLine))
{
startCommandLine = "python wordcount.py http://shakespeare.mit.edu/romeo_juliet/full.html";
}
// Configure some environment variables in the container which the
// wordcount.py or other script can read to modify its behavior.
Dictionary<string, string> envVars = new Dictionary<string, string>
{
{ "NumWords", "5" },
{ "MinLength", "8" }
};
Console.WriteLine($"\nCreating container group '{containerGroupName}' with start command '{startCommandLine}'");
// Get the resource group's region
IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
Region azureRegion = resGroup.Region;
// Create the container group
var containerGroup = azure.ContainerGroups.Define(containerGroupName)
.WithRegion(azureRegion)
.WithExistingResourceGroup(resourceGroupName)
.WithLinux()
.WithPublicImageRegistryOnly()
.WithoutVolume()
.DefineContainerInstance(containerGroupName + "-1")
.WithImage(containerImage)
.WithExternalTcpPort(80)
.WithCpuCoreCount(1.0)
.WithMemorySizeInGB(1)
.WithStartingCommandLines(startCommandLine.Split())
.WithEnvironmentVariables(envVars)
.Attach()
.WithDnsPrefix(containerGroupName)
.WithRestartPolicy(ContainerGroupRestartPolicy.Never)
.Create();
// Print the container's logs
Console.WriteLine($"Logs for container '{containerGroupName}-1':");
Console.WriteLine(containerGroup.GetLogContent(containerGroupName + "-1"));
}
#endregion
#region list_container_groups
/// <summary>
/// Prints the container groups in the specified resource group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group containing the container group(s).</param>
private static void ListContainerGroups(IAzure azure, string resourceGroupName)
{
Console.WriteLine($"Listing container groups in resource group '{resourceGroupName}'...");
foreach (var containerGroup in azure.ContainerGroups.ListByResourceGroup(resourceGroupName))
{
Console.WriteLine($"{containerGroup.Name}");
}
}
#endregion
#region get_container_group
/// <summary>
/// Gets the specified container group and then prints a few of its properties and their values.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group containing the container group.</param>
/// <param name="containerGroupName">The name of the container group whose details should be printed.</param>
private static void PrintContainerGroupDetails(IAzure azure, string resourceGroupName, string containerGroupName)
{
Console.Write($"\nGetting container group details for container group '{containerGroupName}'...");
IContainerGroup containerGroup = null;
while (containerGroup == null)
{
Console.Write(".");
containerGroup = azure.ContainerGroups.GetByResourceGroup(resourceGroupName, containerGroupName);
SdkContext.DelayProvider.Delay(1000);
}
Console.WriteLine();
Console.WriteLine(containerGroup.Name);
Console.WriteLine("--------------------------------");
Console.WriteLine($"State: {containerGroup.State}");
Console.WriteLine($"FQDN: {containerGroup.Fqdn}");
Console.WriteLine($"IP: {containerGroup.IPAddress}");
Console.WriteLine($"Region: {containerGroup.RegionName}");
}
#endregion
#region delete_container_group
/// <summary>
/// Deletes the specified container group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group containing the container group.</param>
/// <param name="containerGroupName">The name of the container group to delete.</param>
private static void DeleteContainerGroup(IAzure azure, string resourceGroupName, string containerGroupName)
{
IContainerGroup containerGroup = null;
while (containerGroup == null)
{
containerGroup = azure.ContainerGroups.GetByResourceGroup(resourceGroupName, containerGroupName);
SdkContext.DelayProvider.Delay(1000);
}
Console.WriteLine($"Deleting container group '{containerGroupName}'...");
azure.ContainerGroups.DeleteById(containerGroup.Id);
}
#endregion
#region delete_resource_group
/// <summary>
/// Deletes the specified resource group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group to delete.</param>
private static void DeleteResourceGroup(IAzure azure, string resourceGroupName)
{
Console.WriteLine($"\nDeleting resource group '{resourceGroupName}'...");
azure.ResourceGroups.DeleteByName(resourceGroupName);
}
#endregion
}
}