-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathNewAzureVMCommand.cs
373 lines (318 loc) · 15 KB
/
NewAzureVMCommand.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
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using AutoMapper;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.ServiceManagemenet.Common;
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Storage;
using Microsoft.Azure.Management.Storage.Models;
using System;
using System.Collections;
using System.Linq;
using System.Management.Automation;
using System.Reflection;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Models;
namespace Microsoft.Azure.Commands.Compute
{
[Cmdlet(VerbsCommon.New, ProfileNouns.VirtualMachine)]
[OutputType(typeof(PSAzureOperationResponse))]
public class NewAzureVMCommand : VirtualMachineBaseCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
[Alias("VMProfile")]
[Parameter(
Mandatory = true,
Position = 2,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public PSVirtualMachine VM { get; set; }
[Parameter(
Position = 3,
HelpMessage = "Disable BG Info Extension")]
public SwitchParameter DisableBginfoExtension { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public Hashtable[] Tags { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = false)]
[ValidateNotNullOrEmpty]
public string LicenseType { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
if (this.VM.DiagnosticsProfile == null)
{
var storageUri = GetOrCreateStorageAccountForBootDiagnostics();
if (storageUri != null)
{
this.VM.DiagnosticsProfile = new DiagnosticsProfile
{
BootDiagnostics = new BootDiagnostics
{
Enabled = true,
StorageUri = storageUri.ToString(),
}
};
}
}
ExecuteClientAction(() =>
{
var parameters = new VirtualMachine
{
DiagnosticsProfile = this.VM.DiagnosticsProfile,
HardwareProfile = this.VM.HardwareProfile,
StorageProfile = this.VM.StorageProfile,
NetworkProfile = this.VM.NetworkProfile,
OsProfile = this.VM.OSProfile,
Plan = this.VM.Plan,
LicenseType = this.LicenseType,
AvailabilitySet = this.VM.AvailabilitySetReference,
Location = !string.IsNullOrEmpty(this.Location) ? this.Location : this.VM.Location,
Tags = this.Tags != null ? this.Tags.ToDictionary() : this.VM.Tags
};
var op = this.VirtualMachineClient.CreateOrUpdateWithHttpMessagesAsync(
this.ResourceGroupName,
this.VM.Name,
parameters);
var wait = op.GetAwaiter();
var resultop = wait.GetResult();
var result = Mapper.Map<PSAzureOperationResponse>(resultop);
if (!(this.DisableBginfoExtension.IsPresent || IsLinuxOs()))
{
var currentBginfoVersion = GetBginfoExtension();
if (!string.IsNullOrEmpty(currentBginfoVersion))
{
var extensionParameters = new VirtualMachineExtension
{
Location = this.Location,
Publisher = VirtualMachineBGInfoExtensionContext.ExtensionDefaultPublisher,
VirtualMachineExtensionType = VirtualMachineBGInfoExtensionContext.ExtensionDefaultName,
TypeHandlerVersion = currentBginfoVersion,
AutoUpgradeMinorVersion = true,
};
typeof(Resource).GetRuntimeProperty("Name").SetValue(extensionParameters, VirtualMachineBGInfoExtensionContext.ExtensionDefaultName);
typeof(Resource).GetRuntimeProperty("Type")
.SetValue(extensionParameters, VirtualMachineExtensionType);
var op2 = ComputeClient.ComputeManagementClient.VirtualMachineExtensions.CreateOrUpdateWithHttpMessagesAsync(
this.ResourceGroupName,
this.VM.Name,
VirtualMachineBGInfoExtensionContext.ExtensionDefaultName,
extensionParameters).GetAwaiter().GetResult();
result = Mapper.Map<PSAzureOperationResponse>(op2);
}
}
WriteObject(result);
});
}
private string GetBginfoExtension()
{
var canonicalizedLocation = this.Location.Canonicalize();
var publishers =
ComputeClient.ComputeManagementClient.VirtualMachineImages.ListPublishers(canonicalizedLocation);
var publisher = publishers.FirstOrDefault(e => e.Name.Equals(VirtualMachineBGInfoExtensionContext.ExtensionDefaultPublisher));
if (publisher == null || !publisher.Name.Equals(VirtualMachineBGInfoExtensionContext.ExtensionDefaultPublisher))
{
return null;
}
var virtualMachineImageClient = ComputeClient.ComputeManagementClient.VirtualMachineExtensionImages;
var imageTypes =
virtualMachineImageClient.ListTypes(canonicalizedLocation,
VirtualMachineBGInfoExtensionContext.ExtensionDefaultPublisher);
var extensionType = imageTypes.FirstOrDefault(
e => e.Name.Equals(VirtualMachineBGInfoExtensionContext.ExtensionDefaultName));
if (extensionType == null || !extensionType.Name.Equals(VirtualMachineBGInfoExtensionContext.ExtensionDefaultName))
{
return null;
}
var bginfoVersions =
virtualMachineImageClient.ListVersions(canonicalizedLocation,
VirtualMachineBGInfoExtensionContext.ExtensionDefaultPublisher,
VirtualMachineBGInfoExtensionContext.ExtensionDefaultName);
if (bginfoVersions != null
&& bginfoVersions.Count > 0)
{
return bginfoVersions.Max(ver =>
{
Version result;
return (Version.TryParse(ver.Name, out result))
? string.Format("{0}.{1}", result.Major, result.Minor)
: VirtualMachineBGInfoExtensionContext.ExtensionDefaultVersion;
});
}
return null;
}
private bool IsLinuxOs()
{
if (this.VM == null)
{
return false;
}
if ((this.VM.StorageProfile != null)
&& (this.VM.StorageProfile.OsDisk != null)
&& (this.VM.StorageProfile.OsDisk.OsType != null))
{
return (this.VM.StorageProfile.OsDisk.OsType.Equals(OperatingSystemTypes.Linux));
}
return ((this.VM.OSProfile != null)
&& (this.VM.OSProfile.LinuxConfiguration != null));
}
private Uri GetOrCreateStorageAccountForBootDiagnostics()
{
var storageAccountName = GetStorageAccountNameFromStorageProfile();
var storageClient =
AzureSession.ClientFactory.CreateClient<StorageManagementClient>(DefaultProfile.Context,
AzureEnvironment.Endpoint.ResourceManager);
if (!string.IsNullOrEmpty(storageAccountName))
{
try
{
var storageAccountList = storageClient.StorageAccounts.List();
if (storageAccountList != null)
{
var osDiskStorageAccount = storageAccountList.StorageAccounts.First(e => e.Name.Equals(storageAccountName));
if (osDiskStorageAccount != null
&& osDiskStorageAccount.AccountType.HasValue
&& !osDiskStorageAccount.AccountType.Value.ToString().ToLowerInvariant().Contains("premium"))
{
return osDiskStorageAccount.PrimaryEndpoints.Blob;
}
}
}
catch (Exception e)
{
if (e.Message.Contains("ResourceNotFound"))
{
WriteWarning(string.Format(
Properties.Resources.StorageAccountNotFoundForBootDiagnostics, storageAccountName));
}
else
{
WriteWarning(string.Format(
Properties.Resources.ErrorDuringGettingStorageAccountForBootDiagnostics, storageAccountName, e.Message));
}
}
}
var storageAccount = TryToChooseExistingStandardStorageAccount(storageClient);
if (storageAccount == null)
{
return CreateStandardStorageAccount(storageClient);
}
WriteWarning(string.Format(Properties.Resources.UsingExistingStorageAccountForBootDiagnostics, storageAccount.Name));
return storageAccount.PrimaryEndpoints.Blob;
}
private string GetStorageAccountNameFromStorageProfile()
{
if (this.VM == null
|| this.VM.StorageProfile == null
|| this.VM.StorageProfile.OsDisk == null
|| this.VM.StorageProfile.OsDisk.Vhd == null
|| this.VM.StorageProfile.OsDisk.Vhd.Uri == null)
{
return null;
}
return GetStorageAccountNameFromUriString(this.VM.StorageProfile.OsDisk.Vhd.Uri);
}
private StorageAccount TryToChooseExistingStandardStorageAccount(StorageManagementClient client)
{
var storageAccountList = client.StorageAccounts.ListByResourceGroup(this.ResourceGroupName);
if (storageAccountList == null)
{
return null;
}
try
{
return storageAccountList.StorageAccounts.First(
e => e.AccountType.HasValue
&& !e.AccountType.Value.ToString().ToLowerInvariant().Contains("premium"));
}
catch (InvalidOperationException e)
{
WriteWarning(string.Format(
Properties.Resources.ErrorDuringChoosingStandardStorageAccount, e.Message));
return null;
}
}
private Uri CreateStandardStorageAccount(StorageManagementClient client)
{
string storageAccountName;
var i = 0;
do
{
storageAccountName = GetRandomStorageAccountName(i);
i++;
}
while (i < 10 && !client.StorageAccounts.CheckNameAvailability(storageAccountName).NameAvailable);
var storaeAccountParameter = new StorageAccountCreateParameters
{
AccountType = AccountType.StandardGRS,
Location = this.Location ?? this.VM.Location,
};
try
{
client.StorageAccounts.Create(this.ResourceGroupName, storageAccountName, storaeAccountParameter);
var getresponse = client.StorageAccounts.GetProperties(this.ResourceGroupName, storageAccountName);
WriteWarning(string.Format(Properties.Resources.CreatingStorageAccountForBootDiagnostics, storageAccountName));
return getresponse.StorageAccount.PrimaryEndpoints.Blob;
}
catch (Exception e)
{
// Failed to create a storage account for boot diagnostics.
WriteWarning(string.Format(Properties.Resources.ErrorDuringCreatingStorageAccountForBootDiagnostics, e));
return null;
}
}
private string GetRandomStorageAccountName(int interation)
{
const int maxSubLength = 5;
const int maxResLength = 6;
const int maxVMLength = 4;
var subscriptionName = VirtualMachineCmdletHelper.GetTruncatedStr(this.DefaultContext.Subscription.Name, maxSubLength);
var resourcename = VirtualMachineCmdletHelper.GetTruncatedStr(this.ResourceGroupName, maxResLength);
var vmname = VirtualMachineCmdletHelper.GetTruncatedStr(this.VM.Name, maxVMLength);
var datetimestr = DateTime.Now.ToString("MMddHHmm");
var output = subscriptionName + resourcename + vmname + datetimestr + interation;
output = new string((from c in output where char.IsLetterOrDigit(c) select c).ToArray());
return output.ToLowerInvariant();
}
private static string GetStorageAccountNameFromUriString(string uriStr)
{
Uri uri;
if (!Uri.TryCreate(uriStr, UriKind.RelativeOrAbsolute, out uri))
{
return null;
}
var storageUri = uri.Authority;
var index = storageUri.IndexOf('.');
return storageUri.Substring(0, index);
}
}
}