Skip to content

Commit 2b1f8d4

Browse files
committed
removed dependency on Az Module
1 parent fea49c2 commit 2b1f8d4

11 files changed

+439
-351
lines changed

src/bicep/add-ons/imaging/modules/automationAccount.bicep

Lines changed: 55 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ param wsusServer string
7373

7474
var parameters = {
7575
arcGisProInstaller: arcGisProInstaller
76+
computeGalleryImageResourceId: computeGalleryImageResourceId
7677
computeGalleryResourceId: computeGalleryResourceId
7778
containerName: containerName
7879
customizations: string(customizations)
@@ -111,7 +112,7 @@ var parameters = {
111112
officeInstaller: officeInstaller
112113
replicaCount: string(replicaCount)
113114
resourceGroupName: resourceGroupName
114-
computeGalleryImageResourceId: computeGalleryImageResourceId
115+
resourceManagerUri: environment().resourceManager
115116
sourceImageType: sourceImageType
116117
storageAccountResourceId: storageAccountResourceId
117118
subnetResourceId: subnetResourceId
@@ -131,7 +132,6 @@ var parameters = {
131132
}
132133
var privateEndpointName = 'pe-${automationAccountName}'
133134
var runbookName = 'New-AzureZeroTrustImageBuild'
134-
var storageEndpoint = environment().suffixes.storage
135135
var subscriptionId = subscription().subscriptionId
136136
var tenantId = subscription().tenantId
137137

@@ -205,7 +205,21 @@ resource privateDnsZoneGroup 'Microsoft.Network/privateEndpoints/privateDnsZoneG
205205
}
206206
}
207207

208-
resource runCommand 'Microsoft.Compute/virtualMachines/runCommands@2023-07-01' = {
208+
resource runBook 'Microsoft.Automation/automationAccounts/runbooks@2023-11-01' = {
209+
parent: automationAccount
210+
name: runbookName
211+
properties: {
212+
runbookType: 'PowerShell'
213+
logProgress: true
214+
logVerbose: true
215+
}
216+
tags: union(
217+
contains(tags, 'Microsoft.Automation/automationAccounts/runbooks') ? tags['Microsoft.Automation/automationAccounts/runbooks'] : {},
218+
mlzTags
219+
)
220+
}
221+
222+
resource updateRunBook 'Microsoft.Compute/virtualMachines/runCommands@2023-07-01' = {
209223
name: 'runbook'
210224
location: location
211225
tags: union(
@@ -218,96 +232,57 @@ resource runCommand 'Microsoft.Compute/virtualMachines/runCommands@2023-07-01' =
218232
asyncExecution: false
219233
parameters: [
220234
{
221-
name: 'AutomationAccountName'
222-
value: automationAccountName
223-
}
224-
{
225-
name: 'ContainerName'
226-
value: containerName
227-
}
228-
{
229-
name: 'Environment'
230-
value: environment().name
231-
}
232-
{
233-
name: 'ResourceGroupName'
234-
value: resourceGroup().name
235+
name: 'RunBookResourceId'
236+
value: runBook.id
235237
}
236238
{
237-
name: 'RunbookName'
238-
value: runbookName
239+
name: 'ResourceManagerUri'
240+
value: environment().resourceManager
239241
}
240242
{
241-
name: 'StorageAccountName'
242-
value: split(storageAccountResourceId, '/')[8]
243-
}
244-
{
245-
name: 'StorageEndpoint'
246-
value: storageEndpoint
247-
}
248-
{
249-
name: 'SubscriptionId'
250-
value: subscription().subscriptionId
251-
}
252-
{
253-
name: 'TenantId'
254-
value: tenant().tenantId
243+
name: 'RunbBookScriptContent'
244+
value: loadTextContent('../scripts/New-AzureZeroTrustImageBuild.ps1')
255245
}
256246
{
257247
name: 'UserAssignedIdentityClientId'
258248
value: userAssignedIdentityClientId
259249
}
260-
{
261-
name: 'UserAssignedIdentityObjectId'
262-
value: userAssignedIdentityPrincipalId
263-
}
264250
]
265251
source: {
266252
script: '''
267-
param (
268-
[string]$AutomationAccountName,
269-
[string]$ContainerName,
270-
[string]$Environment,
271-
[string]$ResourceGroupName,
272-
[string]$RunbookName,
273-
[string]$StorageAccountName,
274-
[string]$StorageEndpoint,
275-
[string]$SubscriptionId,
276-
[string]$TenantId,
277-
[string]$UserAssignedIdentityClientId,
278-
[string]$UserAssignedIdentityObjectId
253+
param(
254+
[string]$ResourceManagerUri,
255+
[string]$RunBookResourceId,
256+
[string]$RunBookScriptContent,
257+
[string]$UserAssignedIdentityClientId
279258
)
280259
$ErrorActionPreference = 'Stop'
281260
$WarningPreference = 'SilentlyContinue'
282-
$BlobName = 'New-AzureZeroTrustImageBuild.ps1'
283-
$StorageAccountUrl = "https://" + $StorageAccountName + ".blob." + $StorageEndpoint + "/"
284-
$TokenUri = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=$StorageAccountUrl&object_id=$UserAssignedIdentityObjectId"
285-
$AccessToken = ((Invoke-WebRequest -Headers @{Metadata=$true} -Uri $TokenUri -UseBasicParsing).Content | ConvertFrom-Json).access_token
286-
$File = "$env:windir\temp\$BlobName"
287-
do
288-
{
289-
try
290-
{
291-
Write-Output "Download Attempt $i"
292-
Invoke-WebRequest -Headers @{"x-ms-version"="2017-11-09"; Authorization ="Bearer $AccessToken"} -Uri "$StorageAccountUrl$ContainerName/$BlobName" -OutFile $File
293-
}
294-
catch [System.Net.WebException]
295-
{
296-
Start-Sleep -Seconds 60
297-
$i++
298-
if($i -gt 10){throw}
299-
continue
300-
}
301-
catch
302-
{
303-
$Output = $_ | select *
304-
Write-Output $Output
305-
throw
261+
262+
Try {
263+
# Fix the resource manager URI since only AzureCloud contains a trailing slash
264+
$ResourceManagerUriFixed = if($ResourceManagerUri[-1] -eq '/'){$ResourceManagerUri.Substring(0,$ResourceManagerUri.Length - 1)} else {$ResourceManagerUri}
265+
266+
# Get an access token for Azure resources
267+
$AzureManagementAccessToken = (Invoke-RestMethod `
268+
-Headers @{Metadata="true"} `
269+
-Uri $('http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=' + $ResourceManagerUriFixed + '&client_id=' + $UserAssignedIdentityClientId)).access_token
270+
271+
# Set header for Azure Management API
272+
$AzureManagementHeader = @{
273+
'Content-Type'='application/json'
274+
'Authorization'='Bearer ' + $AzureManagementAccessToken
306275
}
276+
277+
# Upload Content to Draft
278+
Invoke-RestMethod -Headers $AzureManagementHeader -Method 'PUT' -Uri $($ResourceManagerUriFixed + $RunBookResourceId + '/draft/content?api-version=2023-11-01') -Body $RunBookScriptContent
279+
280+
# Publish the RunBook
281+
Invoke-RestMethod -Headers $AzureManagementHeader -Method 'POST' -Uri $($ResourceManagerUriFixed + $RunBookResourceId + '/publish?api-version=2023-11-01')
282+
}
283+
catch {
284+
throw
307285
}
308-
until(Test-Path -Path $File)
309-
Connect-AzAccount -Environment $Environment -Tenant $TenantId -Subscription $SubscriptionId -Identity -AccountId $UserAssignedIdentityClientId | Out-Null
310-
Import-AzAutomationRunbook -Name $RunbookName -Path $File -Type PowerShell -AutomationAccountName $AutomationAccountName -ResourceGroupName $ResourceGroupName -Published -Force | Out-Null
311286
'''
312287
}
313288
}
@@ -341,7 +316,7 @@ resource jobSchedule 'Microsoft.Automation/automationAccounts/jobSchedules@2022-
341316
}
342317
}
343318
dependsOn: [
344-
runCommand
319+
updateRunBook
345320
]
346321
}
347322

@@ -371,7 +346,7 @@ resource hybridRunbookWorker 'Microsoft.Automation/automationAccounts/hybridRunb
371346
vmResourceId: virtualMachine.id
372347
}
373348
dependsOn: [
374-
runCommand
349+
updateRunBook
375350
]
376351
}
377352

@@ -391,7 +366,7 @@ resource extension_HybridWorker 'Microsoft.Compute/virtualMachines/extensions@20
391366
}
392367
}
393368
dependsOn: [
394-
runCommand
369+
updateRunBook
395370
]
396371
}
397372

@@ -420,6 +395,6 @@ resource extension_JsonADDomainExtension 'Microsoft.Compute/virtualMachines/exte
420395
}
421396
dependsOn: [
422397
extension_HybridWorker
423-
runCommand
398+
updateRunBook
424399
]
425400
}

src/bicep/add-ons/imaging/modules/buildAutomation.bicep

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,17 +136,17 @@ module managementVM 'managementVM.bicep' = {
136136
name: 'management-vm-${deploymentNameSuffix}'
137137
scope: resourceGroup(subscriptionId, resourceGroupName)
138138
params: {
139-
containerName: containerName
139+
140140
diskEncryptionSetResourceId: diskEncryptionSetResourceId
141141
hybridUseBenefit: hybridUseBenefit
142142
localAdministratorPassword: localAdministratorPassword
143143
localAdministratorUsername: localAdministratorUsername
144144
location: location
145145
mlzTags: mlzTags
146-
storageAccountName: split(storageAccountResourceId, '/')[8]
146+
147147
subnetResourceId: subnetResourceId
148148
tags: tags
149-
userAssignedIdentityPrincipalId: userAssignedIdentityPrincipalId
149+
150150
userAssignedIdentityResourceId: userAssignedIdentityResourceId
151151
virtualMachineName: managementVirtualMachineName
152152
}

src/bicep/add-ons/imaging/modules/generalizeVirtualMachine.bicep

Lines changed: 44 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -33,50 +33,64 @@ resource generalizeVirtualMachine 'Microsoft.Compute/virtualMachines/runCommands
3333
asyncExecution: false
3434
parameters: [
3535
{
36-
name: 'Environment'
37-
value: environment().name
38-
}
39-
{
40-
name: 'ResourceGroupName'
41-
value: resourceGroupName
42-
}
43-
{
44-
name: 'SubscriptionId'
45-
value: subscription().subscriptionId
46-
}
47-
{
48-
name: 'TenantId'
49-
value: tenant().tenantId
36+
name: 'ResourceManagerUri'
37+
value: environment().resourceManager
5038
}
5139
{
5240
name: 'UserAssignedIdentityClientId'
5341
value: userAssignedIdentityClientId
5442
}
5543
{
56-
name: 'VirtualMachineName'
57-
value: imageVirtualMachine.name
44+
name: 'VmResourceId'
45+
value: imageVirtualMachine.id
5846
}
5947
]
6048
source: {
6149
script: '''
6250
param(
63-
[string]$Environment,
64-
[string]$ResourceGroupName,
65-
[string]$SubscriptionId,
66-
[string]$TenantId,
67-
[string]$UserAssignedIdentityClientId,
68-
[string]$VirtualMachineName
51+
[Parameter(Mandatory=$true)]
52+
[string]$ResourceManagerUri,
53+
54+
[Parameter(Mandatory=$true)]
55+
[string]$UserAssignedIdentityClientId,
56+
57+
[Parameter(Mandatory=$true)]
58+
[string]$VmResourceId
6959
)
60+
7061
$ErrorActionPreference = 'Stop'
71-
Connect-AzAccount -Environment $Environment -Tenant $TenantId -Subscription $SubscriptionId -Identity -AccountId $UserAssignedIdentityClientId | Out-Null
72-
$PowerStatus = ''
73-
while ($PowerStatus -ne 'VM stopped')
74-
{
75-
Start-Sleep -Seconds 5
76-
$PowerStatus = (Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VirtualMachineName -Status).Statuses[1].DisplayStatus
62+
$WarningPreference = 'SilentlyContinue'
63+
64+
Try {
65+
# Fix the resource manager URI since only AzureCloud contains a trailing slash
66+
$ResourceManagerUriFixed = if($ResourceManagerUri[-1] -eq '/'){$ResourceManagerUri.Substring(0,$ResourceManagerUri.Length - 1)} else {$ResourceManagerUri}
67+
68+
# Get an access token for Azure resources
69+
$AzureManagementAccessToken = (Invoke-RestMethod `
70+
-Headers @{Metadata="true"} `
71+
-Uri $('http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=' + $ResourceManagerUriFixed + '&client_id=' + $UserAssignedIdentityClientId)).access_token
72+
73+
# Set header for Azure Management API
74+
$AzureManagementHeader = @{
75+
'Content-Type'='application/json'
76+
'Authorization'='Bearer ' + $AzureManagementAccessToken
77+
}
78+
79+
# Stop the VM
80+
$null = Invoke-RestMethod -Headers $AzureManagementHeader -Method 'Post' -Uri $($ResourceManagerUriFixed + $VmResourceId + '/powerOff?api-version=2024-03-01')
81+
# Wait for it to show as stopped in Azure
82+
Do {
83+
Start-Sleep -Seconds 5
84+
$VmStatus = Invoke-RestMethod -Headers $AzureManagementHeader -Method 'Get' -Uri $($ResourceManagerUriFixed + $VmResourceId + '/instanceView?api-version=2024-03-01')
85+
$VMPowerState = ($VMStatus.statuses | Where-Object {$_.code -like 'PowerState*'}).displayStatus
86+
87+
} Until ($VMPowerState -eq 'VM stopped')
88+
# Generatlize the VM
89+
$null = Invoke-RestMethod -Headers $AzureManagementHeader -Method 'Post' -Uri $($ResourceManagerUriFixed + $VmResourceId + '/generalize?api-version=2024-03-01')
90+
}
91+
catch {
92+
throw
7793
}
78-
Set-AzVm -ResourceGroupName $ResourceGroupName -Name $VirtualMachineName -Generalized
79-
Start-Sleep -Seconds 30
8094
'''
8195
}
8296
}

src/bicep/add-ons/imaging/modules/imageBuild.bicep

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,17 +81,14 @@ module managementVM 'managementVM.bicep' =
8181
name: 'management-vm-${deploymentNameSuffix}'
8282
scope: resourceGroup(subscriptionId, resourceGroupName)
8383
params: {
84-
containerName: containerName
8584
diskEncryptionSetResourceId: diskEncryptionSetResourceId
8685
hybridUseBenefit: hybridUseBenefit
8786
localAdministratorPassword: localAdministratorPassword
8887
localAdministratorUsername: localAdministratorUsername
8988
location: location
9089
mlzTags: mlzTags
91-
storageAccountName: split(storageAccountResourceId, '/')[8]
9290
subnetResourceId: subnetResourceId
9391
tags: tags
94-
userAssignedIdentityPrincipalId: userAssignedIdentityPrincipalId
9592
userAssignedIdentityResourceId: userAssignedIdentityResourceId
9693
virtualMachineName: managementVirtualMachineName
9794
}

src/bicep/add-ons/imaging/modules/managementVM.bicep

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ Copyright (c) Microsoft Corporation.
33
Licensed under the MIT License.
44
*/
55

6-
param containerName string
6+
//param containerName string
77
param diskEncryptionSetResourceId string
88
param hybridUseBenefit bool
99
@secure()
@@ -12,10 +12,10 @@ param localAdministratorPassword string
1212
param localAdministratorUsername string
1313
param location string
1414
param mlzTags object
15-
param storageAccountName string
15+
//param storageAccountName string
1616
param subnetResourceId string
1717
param tags object
18-
param userAssignedIdentityPrincipalId string
18+
//param userAssignedIdentityPrincipalId string
1919
param userAssignedIdentityResourceId string
2020
param virtualMachineName string
2121

@@ -122,7 +122,7 @@ resource virtualMachine 'Microsoft.Compute/virtualMachines@2022-03-01' = {
122122
licenseType: hybridUseBenefit ? 'Windows_Server' : null
123123
}
124124
}
125-
125+
/*
126126
resource modules 'Microsoft.Compute/virtualMachines/runCommands@2023-03-01' = {
127127
name: 'appAzModules'
128128
location: location
@@ -209,5 +209,6 @@ resource modules 'Microsoft.Compute/virtualMachines/runCommands@2023-03-01' = {
209209
}
210210
}
211211
}
212+
*/
212213

213214
output name string = virtualMachine.name

0 commit comments

Comments
 (0)