forked from Azure/AzureStack-Tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAzureStack.ComputeAdmin.psm1
More file actions
377 lines (294 loc) · 15.1 KB
/
AzureStack.ComputeAdmin.psm1
File metadata and controls
377 lines (294 loc) · 15.1 KB
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
# Copyright (c) Microsoft Corporation. All rights reserved.
# See LICENSE.txt in the project root for license information.
<#
.SYNOPSIS
Uploads a VM Image to your Azure Stack and creates a Marketplace item for it.
#>
Function Add-VMImage{
[CmdletBinding(DefaultParameterSetName='VMImageFromLocal')]
Param(
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromLocal')]
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromAzure')]
[ValidateNotNullorEmpty()]
[String] $publisher,
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromLocal')]
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromAzure')]
[ValidateNotNullorEmpty()]
[String] $offer,
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromLocal')]
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromAzure')]
[ValidateNotNullorEmpty()]
[String] $sku,
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromLocal')]
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromAzure')]
[ValidateNotNullorEmpty()]
[String] $version,
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromLocal')]
[ValidateNotNullorEmpty()]
[String] $osDiskLocalPath,
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromAzure')]
[ValidateNotNullorEmpty()]
[String] $osDiskBlobURI,
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromLocal')]
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromAzure')]
[ValidateSet('Windows' ,'Linux')]
[String] $osType,
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromLocal')]
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromAzure')]
[ValidateNotNullorEmpty()]
[String] $tenantID,
[Parameter(ParameterSetName='VMImageFromLocal')]
[Parameter(ParameterSetName='VMImageFromAzure')]
[String] $location = 'local',
[Parameter(ParameterSetName='VMImageFromLocal')]
[string[]] $dataDisksLocalPaths,
[Parameter(ParameterSetName='VMImageFromAzure')]
[string[]] $dataDiskBlobURIs,
[Parameter(ParameterSetName='VMImageFromLocal')]
[Parameter(ParameterSetName='VMImageFromAzure')]
[string] $billingPartNumber,
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromLocal')]
[Parameter(Mandatory=$true, ParameterSetName='VMImageFromAzure')]
[System.Management.Automation.PSCredential] $azureStackCredentials,
[Parameter(ParameterSetName='VMImageFromLocal')]
[Parameter(ParameterSetName='VMImageFromAzure')]
[string] $azureStackDomain = 'azurestack.local',
[Parameter(ParameterSetName='VMImageFromLocal')]
[Parameter(ParameterSetName='VMImageFromAzure')]
[string] $title,
[Parameter(ParameterSetName='VMImageFromLocal')]
[Parameter(ParameterSetName='VMImageFromAzure')]
[string] $description,
[Parameter(ParameterSetName='VMImageFromLocal')]
[Parameter(ParameterSetName='VMImageFromAzure')]
[bool] $CreateGalleryItem = $true
)
if($CreateGalleryItem -eq $false -and $PSBoundParameters.ContainsKey('title'))
{
Write-Error -Message "The title parameter only applies to creating a gallery item." -ErrorAction Stop
}
if($CreateGalleryItem -eq $false -and $PSBoundParameters.ContainsKey('description'))
{
Write-Error -Message "The description parameter only applies to creating a gallery item." -ErrorAction Stop
}
$resourceGroupName = "addvmimageresourcegroup"
$storageAccountName = "addvmimagestorageaccount"
$containerName = "addvmimagecontainer"
$subscriptionName = "Default Provider Subscription"
$endpoints = (Invoke-RestMethod -Uri https://api.$azureStackDomain/metadata/endpoints?api-version=1.0 -Method Get)
$activeDirectoryServiceEndpointResourceId = $endpoints.authentication.audiences[0]
$galleryEndpoint = $endpoints.galleryEndpoint
$graphEndpoint = $endpoints.graphEndpoint
$loginEndpoint = $endpoints.authentication.loginEndpoint
$authority = $loginEndpoint + $tenantID + "/"
Add-AzureRmEnvironment -Name 'Azure Stack' `
-ActiveDirectoryEndpoint $authority `
-ActiveDirectoryServiceEndpointResourceId $activeDirectoryServiceEndpointResourceId `
-ResourceManagerEndpoint "https://api.$azureStackDomain/" `
-GalleryEndpoint $galleryEndpoint `
-GraphEndpoint $graphEndpoint `
$environment = Get-AzureRmEnvironment 'Azure Stack'
$profile = Add-AzureRmAccount -Environment $environment -Credential $azureStackCredentials
Select-AzureRmProfile -Profile $profile
$subscription = Get-AzureRmSubscription -SubscriptionName $subscriptionName | Select-AzureRmSubscription
#pre validate if image is not already deployed
if (Get-AzureRmVMImage -Location $location -PublisherName $publisher -Offer $offer -Skus $sku -Version $version -ErrorAction SilentlyContinue) {
Write-Error -Message ('VM Image with publisher "{0}", offer "{1}", sku "{2}", version "{3}" already is present. Please remove it first or change on of the values' -f $publisher,$offer,$sku,$version) -ErrorAction Stop
}
#potentially the RG was not cleaned up when exception happened in previous run. Test for exist
if (-not (Get-AzureRmResourceGroup -Name $resourceGroupName -Location $location -ErrorAction SilentlyContinue)) {
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
}
#same for storage
if (-not (Get-AzureRmStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue)) {
$storageAccount = New-AzureRmStorageAccount -Name $storageAccountName -Location $location -ResourceGroupName $resourceGroupName -Type Standard_LRS
}
Set-AzureRmCurrentStorageAccount -StorageAccountName $storageAccountName -ResourceGroupName $resourceGroupName
#same for container
if (-not (Get-AzureStorageContainer -Name $containerName -ErrorAction SilentlyContinue)) {
New-AzureStorageContainer -Name $containerName -Permission Blob
}
if($pscmdlet.ParameterSetName -eq "VMImageFromLocal")
{
$script:osDiskName = Split-Path $osDiskLocalPath -Leaf
$script:osDiskBlobURIFromLocal = "https://$storageAccountName.blob.$azureStackDomain/$containerName/$osDiskName"
Add-AzureRmVhd -Destination $osDiskBlobURIFromLocal -ResourceGroupName $resourceGroupName -LocalFilePath $osDiskLocalPath -OverWrite
$script:dataDiskBlobURIsFromLocal = New-Object System.Collections.ArrayList
if ($PSBoundParameters.ContainsKey('dataDisksLocalPaths'))
{
foreach($dataDiskLocalPath in $dataDisksLocalPaths)
{
$dataDiskName = Split-Path $dataDiskLocalPath -Leaf
$dataDiskBlobURI = "https://$storageAccountName.blob.$azureStackDomain/$containerName/$dataDiskName"
$dataDiskBlobURIsFromLocal.Add($dataDiskBlobURI)
Add-AzureRmVhd -Destination $dataDiskBlobURI -ResourceGroupName $resourceGroupName -LocalFilePath $dataDiskLocalPath -OverWrite
}
}
}
$powershellClientId = "0a7bdc5c-7b57-40be-9939-d4c5fc7cd417"
$adminToken = Get-AzureStackToken `
-Authority $authority `
-Resource $activeDirectoryServiceEndpointResourceId `
-AadTenantId $tenantID `
-ClientId $powershellClientId `
-Credential $azureStackCredentials
$headers = @{ Authorization = ("Bearer $adminToken") }
$armEndpoint = 'https://api.' + $azureStackDomain
$uri = $armEndpoint + '/subscriptions/' + $subscription.Subscription.SubscriptionId + '/providers/Microsoft.Compute.Admin/locations/' + $location + '/artifactTypes/platformImage/publishers/' + $publisher
$uri = $uri + '/offers/' + $offer + '/skus/' + $sku + '/versions/' + $version + '?api-version=2015-12-01-preview'
#building platform image JSON
#building osDisk json
if($pscmdlet.ParameterSetName -eq "VMImageFromLocal")
{
$osDiskJSON = '"OsDisk":{"OsType":"'+ $osType + '","Uri":"'+$osDiskBlobURIFromLocal+'"}'
}
else
{
$osDiskJSON = '"OsDisk":{"OsType":"'+ $osType + '","Uri":"'+$osDiskBlobURI+'"}'
}
#building details JSON
$detailsJSON = ''
if ($PSBoundParameters.ContainsKey('billingPartNumber'))
{
$detailsJSON = '"Details":{"BillingPartNumber":"' + $billingPartNumber+'"}'
}
#building dataDisk JSON
$dataDisksJSON = ''
if($pscmdlet.ParameterSetName -eq "VMImageFromLocal")
{
if ($dataDiskBlobURIsFromLocal.Count -ne 0)
{
$dataDisksJSON = '"DataDisks":['
$i = 0
foreach($dataDiskBlobURI in $dataDiskBlobURIsFromLocal)
{
if($i -ne 0)
{
$dataDisksJSON = $dataDisksJSON +', '
}
$newDataDisk = '{"Lun":' + $i + ', "Uri":"' + $dataDiskBlobURI + '"}'
$dataDisksJSON = $dataDisksJSON + $newDataDisk;
++$i
}
$dataDisksJSON = $dataDisksJSON +']'
}
}
else
{
if ($dataDiskBlobURIs.Count -ne 0)
{
$dataDisksJSON = '"DataDisks":['
$i = 0
foreach($dataDiskBlobURI in $dataDiskBlobURIs)
{
if($i -ne 0)
{
$dataDisksJSON = $dataDisksJSON +', '
}
$newDataDisk = '{"Lun":' + $i + ', "Uri":"' + $dataDiskBlobURI + '"}'
$dataDisksJSON = $dataDisksJSON + $newDataDisk;
++$i
}
$dataDisksJSON = $dataDisksJSON +']'
}
}
#building ARMResource
$propertyBody = $osDiskJSON
if(![string]::IsNullOrEmpty($dataDisksJson))
{
$propertyBody = $propertyBody + ', ' + $dataDisksJson
}
if(![string]::IsNullOrEmpty($detailsJson))
{
$propertyBody = $propertyBody + ', ' + $detailsJson
}
$RequestBody = '{"Properties":{'+$propertyBody+'}}'
Invoke-RestMethod -Method PUT -Uri $uri -Body $RequestBody -ContentType 'application/json' -Headers $Headers
$platformImage = Invoke-RestMethod -Method GET -Uri $uri -ContentType 'application/json' -Headers $Headers
while($platformImage.Properties.ProvisioningState -ne 'Succeeded')
{
if($platformImage.Properties.ProvisioningState -eq 'Failed')
{
Write-Error -Message "VM image download failed." -ErrorAction Stop
}
if($platformImage.Properties.ProvisioningState -eq 'Canceled')
{
Write-Error -Message "VM image download was canceled." -ErrorAction Stop
}
Write-Host "Downloading";
Start-Sleep -Seconds 4
$platformImage = Invoke-RestMethod -Method GET -Uri $uri -ContentType 'application/json' -Headers $Headers
}
if($CreateGalleryItem -eq $true -And $platformImage.Properties.ProvisioningState -eq 'Succeeded')
{
Add-Type -AssemblyName System.IO.Compression.FileSystem
$basePath = Split-Path -Parent $MyInvocation.MyCommand.Module.Path
$compressedGalleryItemPath = Join-Path $basePath 'CustomizedVMGalleryItem.azpkg'
$extractedGalleryItemPath = Join-Path $basePath 'galleryItem'
New-Item -ItemType directory -Path $extractedGalleryItemPath
[System.IO.Compression.ZipFile]::ExtractToDirectory($compressedGalleryItemPath, $extractedGalleryItemPath)
$createUIDefinitionPath = Join-Path $extractedGalleryItemPath 'DeploymentTemplates\CreateUIDefinition.json'
$JSON = Get-Content $createUIDefinitionPath | Out-String | ConvertFrom-Json
$JSON.parameters.osPlatform = $osType
$JSON.parameters.imageReference.publisher = $publisher
$JSON.parameters.imageReference.offer = $offer
$JSON.parameters.imageReference.sku = $sku
$JSON | ConvertTo-Json -Compress| set-content $createUIDefinitionPath
$manifestPath = Join-Path $extractedGalleryItemPath 'manifest.json'
$JSON = Get-Content $manifestPath | Out-String | ConvertFrom-Json
$displayName = ''
if ($PSBoundParameters.ContainsKey('title'))
{
$displayName = $title
}
else
{
$displayName = "{0}-{1}-{2}" -f $publisher, $offer, $sku
}
$name = (New-Guid).guid
$JSON.name = $name
$JSON.publisher = $publisher
$JSON.version = $version
$JSON.displayName = $displayName
$JSON.publisherDisplayName = $publisher
$JSON.publisherLegalName = $publisher
$JSON | ConvertTo-Json -Compress| set-content $manifestPath
$stringsPath = Join-Path $extractedGalleryItemPath 'strings\resources.resjson'
$JSON = Get-Content $stringsPath | Out-String | ConvertFrom-Json
$descriptionToSet = ''
if ($PSBoundParameters.ContainsKey('description'))
{
$descriptionToSet = $description
}
else
{
$descriptionToSet = "Create a virtual machine from a VM image. Publisher: {0}, Offer: {1}, Sku:{2}, Version: {3}" -f $publisher, $offer, $sku, $version
}
$extractedName = 'MarketplaceItem.zip'
$compressedGalleryPackagerPath = Join-Path $basePath $extractedName
$extractedGalleryPackagerPath = Join-Path $basePath 'MarketplaceItem'
$JSON.longSummary = $descriptionToSet
$JSON.description = $descriptionToSet
$JSON.summary = $descriptionToSet
$JSON | ConvertTo-Json -Compress | set-content $stringsPath
Invoke-WebRequest -Uri http://www.aka.ms/azurestackmarketplaceitem -OutFile $compressedGalleryPackagerPath
[System.IO.Compression.ZipFile]::ExtractToDirectory($compressedGalleryPackagerPath, $extractedGalleryPackagerPath)
$extractedGalleryPackagerExePath = Join-Path $extractedGalleryPackagerPath "Azure Stack Marketplace Item Generator and Sample\AzureGalleryPackageGenerator"
$galleryItemName = $publisher + "." + $name + "." + $version + ".azpkg"
$newPKGPath = Join-Path $extractedGalleryPackagerExePath $galleryItemName
$currentPath = $pwd
cd $extractedGalleryPackagerExePath
.\AzureGalleryPackager.exe package -m $manifestPath -o .
cd $currentPath
$galleryItemURI = "https://$storageAccountName.blob.$azureStackDomain/$containerName/$galleryItemName"
$blob = Set-AzureStorageBlobContent –Container $containerName –File $newPKGPath –Blob $galleryItemName
Add-AzureRMGalleryItem -SubscriptionId $subscription.Subscription.SubscriptionId -GalleryItemUri $galleryItemURI -ApiVersion 2015-04-01
#cleanup
Remove-Item $extractedGalleryItemPath -Recurse -Force
Remove-Item $extractedGalleryPackagerPath -Recurse -Force
Remove-Item $compressedGalleryPackagerPath
}
Remove-AzureStorageContainer –Name $containerName -Force
Remove-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -AccountName $storageAccountName
Remove-AzureRmResourceGroup -Name $resourceGroupName -Force
}