forked from libre-devops/terraform-plan-destroy-azure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRun-AzTerraform.ps1
More file actions
427 lines (353 loc) · 20.7 KB
/
Copy pathRun-AzTerraform.ps1
File metadata and controls
427 lines (353 loc) · 20.7 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
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
425
426
427
param (
[string]$RunTerraformInit = "true",
[string]$RunTerraformValidate = "true",
[string]$RunTerraformPlan = "false",
[string]$RunTerraformPlanDestroy = "true",
[string]$RunTerraformApply = "false",
[string]$RunTerraformDestroy = "true",
[string]$TerraformInitExtraArgsJson = '["-reconfigure", "-upgrade"]',
[string]$TerraformInitCreateBackendStateFileName = "true",
[string]$TerraformInitCreateBackendStateFilePrefix = "",
[string]$TerraformInitCreateBackendStateFileSuffix = "",
[string]$TerraformPlanExtraArgsJson = '[]',
[string]$TerraformPlanDestroyExtraArgsJson = '[]',
[string]$TerraformApplyExtraArgsJson = '[]',
[string]$TerraformDestroyExtraArgsJson = '[]',
[string]$InstallTenvTerraform = "true",
[string]$TerraformVersion = "latest",
[string]$DebugMode = "false",
[string]$DeletePlanFiles = "true",
[string]$InstallCheckov = "false",
[string]$RunCheckov = "false",
[string]$CheckovSkipCheck = "CKV2_AZURE_31",
[string]$CheckovSoftfail = "true",
[string]$CheckovExtraArgsJson = '[]',
[string]$TerraformPlanFileName = "tfplan.plan",
[string]$TerraformDestroyPlanFileName = "tfplan-destroy.plan",
[string]$TerraformCodeLocation = "examples",
[string]$TerraformStackToRunJson = '["module-development"]', # JSON format Use 'all' to run 0_, 1_, etc and destroy in reverse order 1_, 0_ etc
[string]$CreateTerraformWorkspace = "true",
[string]$TerraformWorkspace = "dev",
[string]$InstallAzureCli = "falFnse",
[string]$UseAzureServiceConnection = "true",
[string]$AttemptAzureLogin = "false",
[string]$UseAzureClientSecretLogin = "false",
[string]$UseAzureOidcLogin = "false",
[string]$UseAzureUserLogin = "true",
[string]$UseAzureManagedIdentityLogin = "false"
)
$ErrorActionPreference = 'Stop'
$currentWorkingDirectory = (Get-Location).path
$fullTerraformCodePath = Join-Path -Path $currentWorkingDirectory -ChildPath $TerraformCodeLocation
# Get script directory
$scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
try
{
Write-Host "→ Installing LibreDevOpsHelpers from PSGallery..."
Install-Module LibreDevOpsHelpers -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop
Write-Host "→ Importing LibreDevOpsHelpers..."
Import-Module LibreDevOpsHelpers -Force
}
catch
{
Write-Host "Error installing LibreDevOpsHelpers from PSGallery: $( $_.Exception.Message )"
exit 1
}
# Log that modules were loaded
_LogMessage -Level "INFO" -Message "[$( $MyInvocation.MyCommand.Name )] Modules loaded successfully" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedDebugMode = ConvertTo-Boolean $DebugMode
_LogMessage -Level 'DEBUG' -Message "DebugMode: `"$DebugMode`" → $convertedDebugMode" -InvocationName "$( $MyInvocation.MyCommand.Name )"
# Enable debug mode if DebugMode is set to $true
if ($true -eq $convertedDebugMode)
{
$Global:DebugPreference = 'Continue' # module functions see this
$Env:TF_LOG = 'DEBUG' # Terraform debug
}
else
{
$Global:DebugPreference = 'SilentlyContinue'
}
try
{
$TerraformStackToRun = $TerraformStackToRunJson | ConvertFrom-Json
if (-not ($TerraformStackToRun -is [System.Collections.IEnumerable]))
{
throw "Parsed value of TerraformStackToRunJson is not an array."
}
$TerraformInitExtraArgs = $TerraformInitExtraArgsJson | ConvertFrom-Json
$TerraformPlanExtraArgs = $TerraformPlanExtraArgsJson | ConvertFrom-Json
$TerraformPlanDestroyExtraArgs = $TerraformPlanDestroyExtraArgsJson | ConvertFrom-Json
$TerraformApplyExtraArgs = $TerraformApplyExtraArgsJson | ConvertFrom-Json
$TerraformDestroyExtraArgs = $TerraformDestroyExtraArgsJson | ConvertFrom-Json
$CheckovExtraArgs = $CheckovExtraArgsJson | ConvertFrom-Json
$convertedInstallTenvTerraform = ConvertTo-Boolean $InstallTenvTerraform
_LogMessage -Level 'DEBUG' -Message "InstallTenvTerraform `"$InstallTenvTerraform`" → $convertedInstallTenvTerraform" -InvocationName $MyInvocation.MyCommand.Name
if ($convertedInstallTenvTerraform)
{
Invoke-InstallTenv
Test-TenvExists
Invoke-TenvTfInstall -TerraformVersion $TerraformVersion
}
Get-InstalledPrograms -Programs @("terraform")
$convertedUseAzureServiceConnection = ConvertTo-Boolean $UseAzureServiceConnection
_LogMessage -Level 'DEBUG' -Message "UseAzureServiceConnection: `"$UseAzureServiceConnection`" → $convertedUseAzureServiceConnection" -InvocationName $MyInvocation.MyCommand.Name
# Convert the string flags to Boolean and log the results at DEBUG level
$convertedInstallAzureCli = ConvertTo-Boolean $InstallAzureCli
_LogMessage -Level 'DEBUG' -Message "InstallAzureCli: `"$InstallAzureCli`" → $convertedInstallAzureCli" -InvocationName $MyInvocation.MyCommand.Name
$convertedAttemptAzureLogin = ConvertTo-Boolean $AttemptAzureLogin
_LogMessage -Level 'DEBUG' -Message "AttemptAzureLogin: `"$AttemptAzureLogin`" → $convertedAttemptAzureLogin" -InvocationName $MyInvocation.MyCommand.Name
$convertedUseAzureClientSecretLogin = ConvertTo-Boolean $UseAzureClientSecretLogin
_LogMessage -Level 'DEBUG' -Message "UseAzureClientSecretLogin: `"$UseAzureClientSecretLogin`" → $convertedUseAzureClientSecretLogin" -InvocationName $MyInvocation.MyCommand.Name
$convertedUseAzureOidcLogin = ConvertTo-Boolean $UseAzureOidcLogin
_LogMessage -Level 'DEBUG' -Message "UseAzureOidcLogin: `"$UseAzureOidcLogin`" → $convertedUseAzureOidcLogin" -InvocationName $MyInvocation.MyCommand.Name
$convertedUseAzureUserLogin = ConvertTo-Boolean $UseAzureUserLogin
_LogMessage -Level 'DEBUG' -Message "UseAzureUserLogin: `"$UseAzureUserLogin`" → $convertedUseAzureUserLogin" -InvocationName $MyInvocation.MyCommand.Name
$convertedUseAzureManagedIdentityLogin = ConvertTo-Boolean $UseAzureManagedIdentityLogin
_LogMessage -Level 'DEBUG' -Message "UseAzureManagedIdentityLogin: `"$UseAzureManagedIdentityLogin`" → $convertedUseAzureManagedIdentityLogin" -InvocationName $MyInvocation.MyCommand.Name
$convertedRunTerraformInit = ConvertTo-Boolean $RunTerraformInit
_LogMessage -Level 'DEBUG' -Message "RunTerraformInit: `"$RunTerraformInit`" → $convertedRunTerraformInit" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedRunTerraformValidate = ConvertTo-Boolean $RunTerraformValiate
_LogMessage -Level 'DEBUG' -Message "RunTerraformValidate: `"$RunTerraformValidate`" → $convertedRunTerraformValidate" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedTerraformInitCreateBackendStateFileName = ConvertTo-Boolean $TerraformInitCreateBackendStateFileName
_LogMessage -Level 'DEBUG' -Message "TerraformInitCreateBackendStateFileName: `"$TerraformInitCreateBackendStateFileName`" → $convertedTerraformInitCreateBackendStateFileName" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedTerraformInitCreateBackendStateFilePrefix = ConvertTo-Null $TerraformInitCreateBackendStateFilePrefix
_LogMessage -Level 'DEBUG' -Message "TerraformInitCreateBackendStateFilePrefix: `"$TerraformInitCreateBackendStateFilePrefix`" → $convertedTerraformInitCreateBackendStateFilePrefix" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedTerraformInitCreateBackendStateFileSuffix = ConvertTo-Null $TerraformInitCreateBackendStateFileSuffix
_LogMessage -Level 'DEBUG' -Message "TerraformInitCreateBackendStateFileSuffix: `"$TerraformInitCreateBackendStateFilePrefix`" → $convertedTerraformInitCreateBackendStateFileSuffix" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedRunTerraformPlan = ConvertTo-Boolean $RunTerraformPlan
_LogMessage -Level 'DEBUG' -Message "RunTerraformPlan: `"$RunTerraformPlan`" → $convertedRunTerraformPlan" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedRunTerraformPlanDestroy = ConvertTo-Boolean $RunTerraformPlanDestroy
_LogMessage -Level 'DEBUG' -Message "RunTerraformPlanDestroy: `"$RunTerraformPlanDestroy`" → $convertedRunTerraformPlanDestroy" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedRunTerraformApply = ConvertTo-Boolean $RunTerraformApply
_LogMessage -Level 'DEBUG' -Message "RunTerraformApply: `"$RunTerraformApply`" → $convertedRunTerraformApply" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedRunTerraformDestroy = ConvertTo-Boolean $RunTerraformDestroy
_LogMessage -Level 'DEBUG' -Message "RunTerraformDestroy: `"$RunTerraformDestroy`" → $convertedRunTerraformDestroy" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedDeletePlanFiles = ConvertTo-Boolean $DeletePlanFiles
_LogMessage -Level 'DEBUG' -Message "DeletePlanFiles: `"$DeletePlanFiles`" → $convertedDeletePlanFiles" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedInstallCheckov = ConvertTo-Boolean $InstallCheckov
_LogMessage -Level 'DEBUG' -Message "InstallCheckov: `"$InstallCheckov`" → $convertedRunCheckov" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedRunCheckov = ConvertTo-Boolean $RunCheckov
_LogMessage -Level 'DEBUG' -Message "RunCheckov: `"$RunCheckov`" → $convertedRunCheckov" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedCheckovSoftfail = ConvertTo-Boolean $CheckovSoftfail
_LogMessage -Level 'DEBUG' -Message "CheckovSoftfail: `"$CheckovSoftfail`" → $convertedCheckovSoftfail" -InvocationName "$( $MyInvocation.MyCommand.Name )"
$convertedCreateTerraformWorkspace = ConvertTo-Boolean $CreateTerraformWorkspace
_LogMessage -Level 'DEBUG' -Message "CreateTerraformWorkspace: `"$CreateTerraformWorkspace`" → $convertedCreateTerraformWorkspace" -InvocationName "$( $MyInvocation.MyCommand.Name )"
if ($convertedAttemptAzureLogin -and $convertedUseAzureServiceConnection)
{
$msg = "This script doesn't support the use of both authentication mechanism. Setting AzureCliLogin to false because of this."
_LogMessage -Level 'WARN' -Message $msg -InvocationName $MyInvocation.MyCommand.Name
$convertedAttemptAzureLogin = $false
}
# ── Chicken-and-egg / mutual exclusivity checks ───────────────────────────────
if (-not $convertedRunTerraformInit -and (
$convertedRunTerraformPlan -or
$convertedRunTerraformPlanDestroy -or
$convertedRunTerraformApply -or
$convertedRunTerraformDestroy))
{
$msg = 'Terraform init must be run before plan / apply / destroy operations.'
_LogMessage -Level 'ERROR' -Message $msg -InvocationName $MyInvocation.MyCommand.Name
throw $msg
}
if ($convertedRunTerraformPlan -and $convertedRunTerraformPlanDestroy)
{
$msg = 'Both Terraform Plan and Terraform Plan-Destroy cannot be true at the same time.'
_LogMessage -Level 'ERROR' -Message $msg -InvocationName $MyInvocation.MyCommand.Name
throw $msg
}
if ($convertedRunTerraformApply -and $convertedRunTerraformDestroy)
{
$msg = 'Both Terraform Apply and Terraform Destroy cannot be true at the same time.'
_LogMessage -Level 'ERROR' -Message $msg -InvocationName $MyInvocation.MyCommand.Name
throw $msg
}
if (-not $convertedRunTerraformPlan -and $convertedRunTerraformApply)
{
$msg = 'You must run terraform **plan** together with **apply** when using this script.'
_LogMessage -Level 'ERROR' -Message $msg -InvocationName $MyInvocation.MyCommand.Name
throw $msg
}
if (-not $convertedRunTerraformPlanDestroy -and $convertedRunTerraformDestroy)
{
$msg = 'You must run terraform **plan destroy** together with **destroy** when using this script.'
_LogMessage -Level 'ERROR' -Message $msg -InvocationName $MyInvocation.MyCommand.Name
throw $msg
}
$processedStacks = @()
try
{
if ($convertedInstallAzureCli -and $convertedAttemptAzureLogin)
{
_LogMessage -Level 'INFO' -Message "Installing Azure CLI…" -InvocationName $MyInvocation.MyCommand.Name
Invoke-InstallAzureCli
}
if ($convertedInstallCheckov -and $convertedRunCheckov)
{
_LogMessage -Level 'INFO' -Message "Installing Checkov…" -InvocationName $MyInvocation.MyCommand.Name
Invoke-InstallCheckov
}
if ($convertedAttemptAzureLogin)
{
Get-InstalledPrograms -Programs @("az")
Connect-AzureCli `
-UseClientSecret $convertedUseAzureClientSecretLogin `
-UseOidc $convertedUseAzureOidcLogin `
-UseUserDeviceCode $convertedUseAzureUserLogin `
-UseManagedIdentity $convertedUseAzureManagedIdentityLogin
}
$stackFolders = Get-TerraformStackFolders `
-CodeRoot $fullTerraformCodePath `
-StacksToRun $TerraformStackToRun
# ──────────────────── REVERSE execution order for destroys ────────────────
if ($convertedRunTerraformPlanDestroy -or $convertedRunTerraformDestroy) {
_LogMessage -Level 'DEBUG' -Message "Begin reverse‐order logic for destroy" -InvocationName $MyInvocation.MyCommand.Name
_LogMessage -Level 'DEBUG' -Message "Original stackFolders: $($stackFolders -join ', ')" -InvocationName $MyInvocation.MyCommand.Name
# Pick out those folders whose name starts with digits_, sort them descending by that leading number
$numericFolders = $stackFolders |
Where-Object { ($_ -split '[\\/]+')[-1] -match '^\d+_' } |
Sort-Object { [int](($_ -split '[\\/]+')[-1] -replace '^(\d+)_.*','$1') } -Descending
# Everything else stays in original order
$otherFolders = $stackFolders | Where-Object { $_ -notin $numericFolders }
# Recombine
$stackFolders = $numericFolders + $otherFolders
_LogMessage -Level 'DEBUG' -Message "Reordered stackFolders: $($stackFolders -join ', ')" -InvocationName $MyInvocation.MyCommand.Name
}
foreach ($folder in $stackFolders)
{
$processedStacks += $folder
_LogMessage -Level 'INFO' -Message "Resolved stack folders: $( $stackFolders -join ', ' )" -InvocationName $MyInvocation.MyCommand.Name
# terraform fmt – always safe
Invoke-TerraformFmtCheck -CodePath $folder
# ── INIT ──────────────────────────────────────────────────────────────
if ($convertedRunTerraformInit)
{
if ($convertedTerraformInitCreateBackendStateFileName)
{
Invoke-TerraformInit `
-CodePath $folder `
-InitArgs $TerraformInitExtraArgs `
-CreateBackendKey $convertedTerraformInitCreateBackendStateFileName `
-StackFolderName $folder `
-BackendKeyPrefix $convertedTerraformInitCreateBackendStateFilePrefix `
-BackendKeySuffix $convertedTerraformInitCreateBackendStateFileSuffix
}
else
{
Invoke-TerraformInit `
-CodePath $folder `
-InitArgs $TerraformInitExtraArgs
}
}
# workspace (needs an init first)
if ($convertedRunTerraformInit -and
$convertedCreateTerraformWorkspace -and
-not [string]::IsNullOrWhiteSpace($TerraformWorkspace))
{
Invoke-TerraformWorkspaceSelect -CodePath $folder -WorkspaceName $TerraformWorkspace
}
# ── VALIDATE ──────────────────────────────────────────────────────────
if ($convertedRunTerraformInit -and $convertedRunTerraformValidate)
{
Invoke-TerraformValidate -CodePath $folder
}
# ── PLAN / PLAN-DESTROY ───────────────────────────────────────────────
if ($convertedRunTerraformPlan)
{
Invoke-TerraformPlan -CodePath $folder -PlanArgs $TerraformPlanExtraArgs -PlanFile $TerraformPlanFileName
}
elseif ($convertedRunTerraformPlanDestroy)
{
Invoke-TerraformPlanDestroy -CodePath $folder -PlanArgs $TerraformPlanDestroyExtraArgs -PlanFile $TerraformDestroyPlanFileName
}
# JSON + Checkov need a plan file
if ($convertedRunTerraformPlan -or $convertedRunTerraformPlanDestroy)
{
if ($convertedRunTerraformPlan)
{
$TfPlanFileName = $TerraformPlanFileName
}
if ($convertedRunTerraformPlanDestroy)
{
$TfPlanFileName = $TerraformDestroyPlanFileName
}
if ($convertedRunCheckov -and $convertedRunTerraformPlan)
{
Convert-TerraformPlanToJson -CodePath $folder -PlanFile $TfPlanFileName
Invoke-Checkov `
-CodePath $folder `
-CheckovSkipChecks $CheckovSkipCheck `
-ExtraArgs $CheckovExtraArgs `
-SoftFail: $convertedCheckovSoftfail
}
}
# ── APPLY / DESTROY ───────────────────────────────────────────────────
if ($convertedRunTerraformApply)
{
Invoke-TerraformApply -CodePath $folder -SkipApprove -ApplyArgs $TerraformApplyExtraArgs
}
elseif ($convertedRunTerraformDestroy)
{
Invoke-TerraformDestroy -CodePath $folder -SkipApprove -DestroyArgs $TerraformDestroyExtraArgs
}
}
}
catch
{
_LogMessage -Level 'ERROR' -Message "Script execution error: $( $_.Exception.Message )" -InvocationName $MyInvocation.MyCommand.Name
throw
}
}
catch
{
_LogMessage -Level "ERROR" -Message "Error: $( $_.Exception.Message )" -InvocationName "$( $MyInvocation.MyCommand.Name )"
exit 1
}
finally
{
if ($convertedDeletePlanFiles)
{
$patterns = @(
$TfPlanFileName,
"${TfPlanFileName}.json",
"${TfPlanFileName}-destroy.tfplan",
"${TfPlanFileName}-destroy.tfplan.json"
)
foreach ($folder in $processedStacks)
{
foreach ($pat in $patterns)
{
$file = Join-Path $folder $pat
if (Test-Path $file)
{
try
{
Remove-Item $file -Force -ErrorAction Stop
_LogMessage -Level DEBUG -Message "Deleted $file" `
-InvocationName $MyInvocation.MyCommand.Name
}
catch
{
_LogMessage -Level WARN -Message "Failed to delete $file – $( $_.Exception.Message )" `
-InvocationName $MyInvocation.MyCommand.Name
}
}
else
{
_LogMessage -Level DEBUG -Message "No file to delete: $file" `
-InvocationName $MyInvocation.MyCommand.Name
}
}
}
}
else
{
_LogMessage -Level DEBUG -Message 'DeletePlanFiles is false – leaving plan files in place.' `
-InvocationName $MyInvocation.MyCommand.Name
}
if ($convertedUseAzureUserLogin -and $convertedAttemptAzureLogin)
{
Disconnect-AzureCli -IsUserDeviceLogin $true
}
$Env:TF_LOG = $null
Set-Location $currentWorkingDirectory
}