-
Notifications
You must be signed in to change notification settings - Fork 453
/
Copy pathjobs.validateModuleDeployment.yml
341 lines (299 loc) · 18.3 KB
/
jobs.validateModuleDeployment.yml
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
#########################################################
## DEPLOYMENT PIPELINE ##
#########################################################
##
## This pipeline template contains the logic to deploy a given module's ARM template using the provided parameter file(s)
##
## Enabled levels of deployment
## - Resource-Group-Level
## - Subscription-Level
## - Management-Group-Level
## - Tenant-Level
##
########################################################
##
##---------------------------------------------##
## TEMPLATE PARAMETERS ##
##---------------------------------------------##
##
## By default it uses the variables specified in the below [parameters] section. However, you can overwrite these variables in the
## referencing pipeline by providing the parameter explicitly.
##
## NOTE: If you don't need to overwrite a shared value, you can IGNORE this section
##
## |============================================================================================================================================================================================================================================|
## | Parameter | Default Value | Description | Example |
## |---------------------------------|--------------------------------------|-----------------------------------------------------------------------------------------------------------|-------------------------------------------------------|
## | serviceConnection | '$(serviceConnection)' | The service connection that connects to Azure. | 'demo-internal' |
## | poolName | '$(poolName)' | You can provide either a [poolname] or [vmImage] to run the job on. | 'Custom Deployment Pool' |
## | vmImage | '$(vmImage)' | You can provide either a [poolname] or [vmImage] to run the job on. | 'ubuntu20.04' |
## | defaultJobTimeoutInMinutes | 120 | The timeout for the job in this pipeline. | 120 |
## | removeDeployment | 'true' | Set to [true] to flag resources for removal. If not provided, defaults to true. | 'true' |
## | customTokens | '' | Additional token pairs in json format. | '{"tokenName":"tokenValue"}' |
## | jobDisplayName | '' | The display name of the job. | 'Deploy module' |
## | modulePath | '$(modulePath)' | The path to the module to deploy. | 'c:/KeyVault' |
## | location | '$(location)' | The location to deploy resources to. | 'EastUs2' |
## | subscriptionId | '$(ARM_SUBSCRIPTION_ID)' | The id of the subscription to deploy into when using a Management group service connection. | 'aed7c000-6387-412e-bed0-24dfddf4bbc6' |
## | managementGroupId | '$(ARM_MGMTGROUP_ID)' | The id of the management group to deploy into. Required only for Management-Group-Level deployments. | '6ycc9620-cb01-454f-9ebc-fc6b1df48d64' |
## | azurePowerShellVersion | '$(azurePowerShellVersion)' | Used for configuring the Azure PowerShellModules Version, one of the example values. | 'latestVersion' or 'OtherVersion' |
## | preferredAzurePowerShellVersion | '$(preferredAzurePowerShellVersion)' | Used for configuring the Azure PowerShellModules Version, either an empty string or the specific version. | '4.4.0' |
## |============================================================================================================================================================================================================================================|
##
##---------------------------------------------##
parameters:
# Pipeline-related parameters
serviceConnection: '$(serviceConnection)'
poolName: '$(poolName)'
vmImage: '$(vmImage)'
defaultJobTimeoutInMinutes: 120
# Logic-related parameters
removeDeployment: false
customTokens: ''
modulePath: '$(modulePath)'
location: '$(location)'
subscriptionId: '$(ARM_SUBSCRIPTION_ID)'
managementGroupId: '$(ARM_MGMTGROUP_ID)'
# Azure PowerShell Version parameters
azurePowerShellVersion: '$(azurePowerShellVersion)'
preferredAzurePowerShellVersion: '$(preferredAzurePowerShellVersion)'
##---------------------------------------------##
## TEMPLATE LOGIC ##
##---------------------------------------------##
jobs:
- template: /.azuredevops/pipelineTemplates/jobs.getModuleTestFiles.yml
- job: deploy
displayName: 'Deploying ' # Auto-populated
timeoutInMinutes: ${{ parameters.defaultJobTimeoutInMinutes }}
pool:
${{ if ne(parameters.vmImage, '') }}:
vmImage: ${{ parameters.vmImage }}
${{ if ne(parameters.poolName, '') }}:
name: ${{ parameters.poolName }}
dependsOn:
- getModuleTestFiles
strategy:
matrix: $[ dependencies.getModuleTestFiles.outputs['getModuleTestFilesTask.moduleTestFilePaths'] ]
##---------------------------------------------##
## TEMPLATE LOGIC ##
##---------------------------------------------##
steps:
# [Agent] Prepare environment
#----------------------------
- task: PowerShell@2
displayName: 'Setup agent for deployment'
inputs:
targetType: inline
pwsh: true
script: |
# Load used functions
. (Join-Path '$(System.DefaultWorkingDirectory)' 'utilities' 'pipelines' 'sharedScripts' 'Set-EnvironmentOnAgent.ps1')
# Define PS modules to install on the runner
$modules = @(
@{ Name = 'Az.Accounts' },
@{ Name = 'Az.Resources' },
@{ Name = 'powershell-yaml'; Version = '0.4.2'}
)
# Additional PS modules need to be installed for the removal step in case it is enabled
if ('${{ parameters.removeDeployment}}' -eq 'true') {
$modules += @(
@{ Name = 'Az.CognitiveServices' },
@{ Name = 'Az.Compute' },
@{ Name = 'Az.KeyVault' },
@{ Name = 'Az.MachineLearningServices' },
@{ Name = 'Az.Monitor' },
@{ Name = 'Az.OperationalInsights' },
@{ Name = 'Az.RecoveryServices' }
)
}
# Set agent up
Set-EnvironmentOnAgent -PSModules $modules
# [Agent] Replace tokens
#-----------------------
- task: PowerShell@2
displayName: 'Replace tokens in template files'
inputs:
targetType: inline
pwsh: true
script: |
# Load used functions
. (Join-Path '$(System.DefaultWorkingDirectory)' 'utilities' 'pipelines' 'tokensReplacement' 'Convert-TokensInFileList.ps1')
. (Join-Path '$(System.DefaultWorkingDirectory)' 'utilities' 'pipelines' 'sharedScripts' 'Get-LocallyReferencedFileList.ps1')
# Get target files
$moduleTestFilePath = Join-Path '$(System.DefaultWorkingDirectory)' '$(modulePath)' '$(moduleTestFilePath)'
# Get target files
$targetFileList = @(
$moduleTestFilePath
)
# Add all module template files as they may contain tokens
$targetFileList += (Get-LocallyReferencedFileList -FilePath $moduleTestFilePath)
$targetFileList = $targetFileList | Sort-Object -Unique
# Construct Token Function Input
$ConvertTokensInputs = @{
FilePathList = $targetFileList
Tokens = @{}
TokenPrefix = '$(tokenPrefix)'
TokenSuffix = '$(tokenSuffix)'
}
# Add enforced tokens
$ConvertTokensInputs.Tokens += @{
subscriptionId = '${{ parameters.subscriptionId }}'
managementGroupId = '${{ parameters.managementGroupId }}'
tenantId = '$(ARM_TENANT_ID)'
}
# Add local (source control) tokens
$tokenMap = @{}
foreach ($token in (Get-ChildItem env: | Where-Object -Property Name -Like "localToken_*")) {
$tokenMap += @{ $token.Name.Replace('localToken_','','OrdinalIgnoreCase') = $token.value }
}
Write-Verbose ('Using local tokens [{0}]' -f ($tokenMap.Keys -join ', ')) -Verbose
$ConvertTokensInputs.Tokens += $tokenMap
# Swap 'namePrefix' token if empty and provided as a Azure DevOps variable
if([String]::IsNullOrEmpty($ConvertTokensInputs.Tokens['namePrefix'])){
Write-Verbose 'Using [namePrefix] token from Azure DevOps Variable Groups' -Verbose
$ConvertTokensInputs.Tokens['namePrefix'] = "$(TOKEN_NAMEPREFIX)"
}
# Add custom tokens (passed in via the pipeline)
if(-not [String]::IsNullOrEmpty('${{ parameters.customTokens }}')) {
$customTokens = '${{ parameters.customTokens }}' | ConvertFrom-Json -AsHashTable
Write-Verbose ('Using custom parameter file tokens [{0}]' -f ($customTokens.Keys -join ', ')) -Verbose
$ConvertTokensInputs.Tokens += $customTokens
}
Write-Verbose "Convert Tokens Input:`n $($ConvertTokensInputs | ConvertTo-Json -Depth 10)" -Verbose
# Invoke Token Replacement Functionality [For Module]
$null = Convert-TokensInFileList @ConvertTokensInputs
# [Validation] task(s)
#---------------------
- task: AzurePowerShell@5
displayName: 'Validate template file via connection [${{ parameters.serviceConnection }}]'
inputs:
azureSubscription: ${{ parameters.serviceConnection }}
azurePowerShellVersion: 'latestVersion'
preferredAzurePowerShellVersion: ''
ScriptType: InlineScript
pwsh: true
inline: |
# Load used functions
. (Join-Path '$(System.DefaultWorkingDirectory)' '$(pipelineFunctionsPath)' 'resourceDeployment' 'Test-TemplateDeployment.ps1')
# Fetching parameters
$location = '${{ parameters.location }}'
$subscriptionId = '${{ parameters.subscriptionId }}'
$managementGroupId = '${{ parameters.managementGroupId }}'
# Resolve template file path
$moduleTestFilePath = Join-Path '$(System.DefaultWorkingDirectory)' '$(modulePath)' '$(moduleTestFilePath)'
# Determine possible parameters depending on file type
if ((Split-Path $moduleTestFilePath -Extension) -eq '.bicep') {
$moduleTemplateContent = bicep build $moduleTestFilePath --stdout | ConvertFrom-Json -AsHashtable
$moduleTemplatePossibleParameters = $moduleTemplateContent.parameters.Keys
} else {
$moduleTemplatePossibleParameters = ((Get-Content $moduleTestFilePath -Raw) | ConvertFrom-Json -AsHashtable).parameters.keys
}
# ----------- #
# INVOKE TEST #
# ----------- #
# Building input object
$functionInput = @{
TemplateFilePath = $moduleTestFilePath
Location = $location
SubscriptionId = $subscriptionId
ManagementGroupId = $managementGroupId
AdditionalParameters = @{}
}
# Handle additional parameters
if (-not [System.Convert]::ToBoolean('$(enableDefaultTelemetry)') -and ($moduleTemplatePossibleParameters.Keys -contains 'enableDefaultTelemetry')) {
$functionInput['additionalParameters'] += @{
enableDefaultTelemetry = [System.Convert]::ToBoolean('$(enableDefaultTelemetry)')
}
}
Write-Verbose "Invoke task with" -Verbose
Write-Verbose ($functionInput | ConvertTo-Json | Out-String) -Verbose
Test-TemplateDeployment @functionInput -Verbose
# [Deployment] task(s)
#---------------------
- task: AzurePowerShell@5
name: deployModule
displayName: 'Deploy template file via connection [${{ parameters.serviceConnection }}]'
inputs:
azureSubscription: ${{ parameters.serviceConnection }}
azurePowerShellVersion: 'latestVersion'
preferredAzurePowerShellVersion: ''
pwsh: true
ScriptType: InlineScript
inline: |
# Load used functions
. (Join-Path '$(System.DefaultWorkingDirectory)' '$(pipelineFunctionsPath)' 'resourceDeployment' 'New-TemplateDeployment.ps1')
# Fetching parameters
$location = '${{ parameters.location }}'
$subscriptionId = '${{ parameters.subscriptionId }}'
$managementGroupId = '${{ parameters.managementGroupId }}'
# Resolve template file path
$moduleTestFilePath = Join-Path '$(System.DefaultWorkingDirectory)' '$(modulePath)' '$(moduleTestFilePath)'
# Determine possible parameters depending on file type
if ((Split-Path $moduleTestFilePath -Extension) -eq '.bicep') {
$moduleTemplateContent = bicep build $moduleTestFilePath --stdout | ConvertFrom-Json -AsHashtable
$moduleTemplatePossibleParameters = $moduleTemplateContent.parameters.Keys
} else {
$moduleTemplatePossibleParameters = ((Get-Content $moduleTestFilePath -Raw) | ConvertFrom-Json -AsHashtable).parameters.keys
}
# ----------- #
# INVOKE TEST #
# ----------- #
# Building input object
$functionInput = @{
TemplateFilePath = $moduleTestFilePath
Location = $location
SubscriptionId = $subscriptionId
ManagementGroupId = $managementGroupId
doNotThrow = $true
AdditionalParameters = @{}
}
# Handle additional parameters
if (-not [System.Convert]::ToBoolean('$(enableDefaultTelemetry)') -and ($moduleTemplatePossibleParameters.Keys -contains 'enableDefaultTelemetry')) {
$functionInput['additionalParameters'] += @{
enableDefaultTelemetry = [System.Convert]::ToBoolean('$(enableDefaultTelemetry)')
}
}
Write-Verbose 'Invoke task with' -Verbose
Write-Verbose ($functionInput | ConvertTo-Json | Out-String) -Verbose
# Invoke deployment
$res = New-TemplateDeployment @functionInput -Verbose
# Get deployment name
$deploymentNames = $res.DeploymentNames | ConvertTo-Json -Compress
Write-Verbose "Deployment name(s) [$deploymentNames]" -Verbose
Write-Host "##vso[task.setvariable variable=deploymentNames]$deploymentNames"
Write-Host "##vso[task.setvariable variable=deploymentNames;isOutput=true]$deploymentNames"
# Populate further outputs
$deploymentOutputHashTable=@{}
foreach ($outputKey in $res.deploymentOutput.Keys) {
Write-Output ('##vso[task.setvariable variable={0}]{1}' -f $outputKey, $res.deploymentOutput[$outputKey].Value)
$deploymentOutputHashTable.add($outputKey,$res.deploymentOutput[$outputKey].Value)
}
$deploymentOutput = $deploymentOutputHashTable | ConvertTo-Json -Compress -Depth 100
Write-Verbose "Deployment output: $deploymentOutput" -Verbose
if ($res.ContainsKey('exception')) {
# Happens only if there is an exception
throw $res.exception
}
# [Removal] task(s)
#------------------
- task: AzurePowerShell@5
displayName: 'Remove deployed resources via [${{ parameters.serviceConnection }}]'
condition: and(succeededOrFailed(), eq('${{ parameters.removeDeployment }}', 'True'), not(eq(variables['deploymentNames'],'')), not(startsWith(variables['deploymentNames'], 'variables[' )))
inputs:
azureSubscription: ${{ parameters.serviceConnection }}
azurePowerShellVersion: ${{ parameters.azurePowerShellVersion }}
preferredAzurePowerShellVersion: ${{ parameters.preferredAzurePowerShellVersion }}
ScriptType: InlineScript
failOnStandardError: false
pwsh: true
inline: |
# Load used function
. (Join-Path '$(System.DefaultWorkingDirectory)' '$(pipelineFunctionsPath)' 'resourceRemoval' 'Initialize-DeploymentRemoval.ps1')
$functionInput = @{
TemplateFilePath = Join-Path '$(System.DefaultWorkingDirectory)' '$(modulePath)' '$(moduleTestFilePath)'
SubscriptionId = '${{ parameters.subscriptionId }}'
ManagementGroupId = '${{ parameters.managementGroupId }}'
DeploymentNames = '$(deploymentNames)' | ConvertFrom-Json
}
Write-Verbose 'Invoke task with' -Verbose
Write-Verbose ($functionInput | ConvertTo-Json | Out-String) -Verbose
Initialize-DeploymentRemoval @functionInput