-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathinstall.ps1
More file actions
1448 lines (1237 loc) · 46 KB
/
install.ps1
File metadata and controls
1448 lines (1237 loc) · 46 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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# DevOps Environment Toolkit - Enhanced Windows Installation Script
# Author: H A R S H H A A
# License: MIT
# Version: 2.0.0
# Set execution policy for current session
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force
# Global variables with consistent naming
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$LogFile = "$env:USERPROFILE\.devops-toolkit-install.log"
$BackupDir = "$env:USERPROFILE\.devops-toolkit-backup"
$InstallTimestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$Verbose = $false
$DryRun = $false
$SkipConfirmation = $false
$SelectiveInstall = $false
# Installation flags (consistent naming)
$InstallGit = $false
$InstallDocker = $false
$InstallK8s = $false
$InstallTerraform = $false
$InstallAnsible = $false
$InstallVSCode = $false
$InstallAwsCli = $false
$InstallAzureCli = $false
# System information
$OSVersion = $null
$OSName = ""
# Colors for output
$Red = "Red"
$Green = "Green"
$Yellow = "Yellow"
$Blue = "Blue"
$Magenta = "Magenta"
$Cyan = "Cyan"
$White = "White"
# ASCII Art Banner
function Show-Banner {
Write-Host ""
Write-Host " ╔══════════════════════════════════════════════════════════════╗" -ForegroundColor $Cyan
Write-Host " ║ ║" -ForegroundColor $Cyan
Write-Host " ║ 🚀 DevOps Environment Toolkit - Enhanced Installer 🚀 ║" -ForegroundColor $Cyan
Write-Host " ║ ║" -ForegroundColor $Cyan
Write-Host " ║ Version 2.0.0 - Advanced Features & Error Recovery ║" -ForegroundColor $Cyan
Write-Host " ║ ║" -ForegroundColor $Cyan
Write-Host " ╚══════════════════════════════════════════════════════════════╝" -ForegroundColor $Cyan
Write-Host ""
}
# Enhanced logging system
function Initialize-Logging {
$LogDir = Split-Path -Parent $LogFile
if (-not (Test-Path $LogDir)) {
New-Item -ItemType Directory -Path $LogDir -Force | Out-Null
}
$LogHeader = @"
=== DevOps Toolkit Installation Log - $(Get-Date) ===
Script Version: 2.0.0
OS: $([System.Environment]::OSVersion.VersionString)
User: $env:USERNAME
===============================================
"@
$LogHeader | Out-File -FilePath $LogFile -Encoding UTF8
}
function Write-LogFile {
param(
[string]$Level,
[string]$Message
)
$LogEntry = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] [$Level] $Message"
$LogEntry | Out-File -FilePath $LogFile -Append -Encoding UTF8
}
# Progress tracking
$ProgressTotal = 0
$ProgressCurrent = 0
function Initialize-Progress {
param([int]$Total)
$script:ProgressTotal = $Total
$script:ProgressCurrent = 0
}
function Update-Progress {
$script:ProgressCurrent++
$Percentage = [math]::Round(($ProgressCurrent * 100) / $ProgressTotal)
Write-Host "`r[PROGRESS] $ProgressCurrent/$ProgressTotal ($Percentage%) - " -NoNewline -ForegroundColor $Blue
# Create progress bar
$BarLength = 30
$FilledLength = [math]::Round(($Percentage * $BarLength) / 100)
Write-Host "[" -NoNewline
for ($i = 0; $i -lt $FilledLength; $i++) { Write-Host "█" -NoNewline }
for ($i = $FilledLength; $i -lt $BarLength; $i++) { Write-Host "░" -NoNewline }
Write-Host "]" -NoNewline
}
# Rollback and cleanup functionality
function Invoke-RollbackInstallation {
Write-Info "Rolling back installation..."
# Remove installed packages based on what was attempted
if ($InstallDocker) {
Write-Info "Removing Docker packages..."
Invoke-Command "choco uninstall docker-desktop docker-compose -y" "Removed Docker packages" 2>$null
}
if ($InstallK8s) {
Write-Info "Removing Kubernetes tools..."
Invoke-Command "choco uninstall kubernetes-cli minikube -y" "Removed Kubernetes tools" 2>$null
}
if ($InstallTerraform) {
Write-Info "Removing Terraform..."
Invoke-Command "choco uninstall terraform -y" "Removed Terraform" 2>$null
}
if ($InstallAnsible) {
Write-Info "Removing Ansible..."
Invoke-Command "choco uninstall ansible -y" "Removed Ansible" 2>$null
}
if ($InstallVSCode) {
Write-Info "Removing VS Code..."
Invoke-Command "choco uninstall vscode -y" "Removed VS Code" 2>$null
}
if ($InstallAwsCli) {
Write-Info "Removing AWS CLI..."
Invoke-Command "choco uninstall awscli -y" "Removed AWS CLI" 2>$null
}
if ($InstallAzureCli) {
Write-Info "Removing Azure CLI..."
Invoke-Command "choco uninstall azure-cli -y" "Removed Azure CLI" 2>$null
}
# Remove configuration directories if they were created
if (Test-Path "$env:USERPROFILE\.devops-toolkit") {
Write-Info "Removing configuration directories..."
Remove-Item -Path "$env:USERPROFILE\.devops-toolkit" -Recurse -Force -ErrorAction SilentlyContinue
}
# Restore from backup if available
$BackupPath = "$BackupDir\$InstallTimestamp"
if (Test-Path $BackupPath) {
Write-Info "Restoring from backup..."
Restore-Backup $BackupPath
}
Write-Success "Rollback completed"
}
# Cleanup temporary files
function Remove-TempFiles {
Write-Debug "Cleaning up temporary files..."
# Remove common temporary files
$tempFiles = @(
"$env:USERPROFILE\get-docker.sh",
"$env:USERPROFILE\terraform.zip",
"$env:USERPROFILE\kubectl.exe",
"$env:USERPROFILE\minikube.exe",
"$env:USERPROFILE\terraform.exe"
)
foreach ($file in $tempFiles) {
if (Test-Path $file) {
Remove-Item -Path $file -Force -ErrorAction SilentlyContinue
}
}
Write-Debug "Temporary files cleaned up"
}
# Enhanced error handling and recovery
function Handle-Error {
param(
[string]$ErrorMessage,
[string]$Command
)
Write-Error "Error occurred: $ErrorMessage"
Write-LogFile "ERROR" "Installation failed: $ErrorMessage (Command: $Command)"
Write-Host "Installation failed! Check the log file: $LogFile" -ForegroundColor $Red
# Offer rollback option
if (-not $DryRun) {
Write-Host ""
$Response = Read-Host "Do you want to rollback the installation? (y/N)"
if ($Response -eq "y" -or $Response -eq "Y") {
Invoke-RollbackInstallation
}
}
Remove-TempFiles
Write-Host "You can try to recover by running: $($MyInvocation.MyCommand.Path) -Recover" -ForegroundColor $Yellow
exit 1
}
# Backup and restore functionality
function New-Backup {
Write-Info "Creating backup of existing configurations..."
$BackupPath = "$BackupDir\$InstallTimestamp"
if (-not (Test-Path $BackupPath)) {
New-Item -ItemType Directory -Path $BackupPath -Force | Out-Null
}
# Backup existing configurations
if (Test-Path "$env:USERPROFILE\.devops-toolkit") {
Copy-Item -Path "$env:USERPROFILE\.devops-toolkit" -Destination $BackupPath -Recurse -Force -ErrorAction SilentlyContinue
}
# Backup PowerShell profile
if (Test-Path $PROFILE) {
Copy-Item -Path $PROFILE -Destination "$BackupPath\profile.ps1" -Force -ErrorAction SilentlyContinue
}
Write-Success "Backup created at: $BackupPath"
Write-LogFile "INFO" "Backup created at: $BackupPath"
}
function Restore-Backup {
param([string]$BackupPath)
if (-not $BackupPath) {
# Find the latest backup
$BackupPath = Get-ChildItem -Path $BackupDir -Directory | Sort-Object LastWriteTime -Descending | Select-Object -First 1
if ($BackupPath) {
$BackupPath = $BackupPath.FullName
}
}
if (-not $BackupPath -or -not (Test-Path $BackupPath)) {
Write-Error "No backup found to restore"
return $false
}
Write-Info "Restoring from backup: $BackupPath"
# Restore configurations
if (Test-Path "$BackupPath\.devops-toolkit") {
Remove-Item -Path "$env:USERPROFILE\.devops-toolkit" -Recurse -Force -ErrorAction SilentlyContinue
Copy-Item -Path "$BackupPath\.devops-toolkit" -Destination $env:USERPROFILE -Recurse -Force
}
# Restore PowerShell profile
if (Test-Path "$BackupPath\profile.ps1") {
Copy-Item -Path "$BackupPath\profile.ps1" -Destination $PROFILE -Force
}
Write-Success "Backup restored successfully"
Write-LogFile "INFO" "Backup restored from: $BackupPath"
return $true
}
# System validation and compatibility checks
function Test-SystemCompatibility {
Write-Info "Validating system compatibility..."
# Check available disk space (need at least 5GB)
$Drive = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='C:'"
$AvailableSpaceGB = [math]::Round($Drive.FreeSpace / 1GB, 2)
$RequiredSpaceGB = 5
if ($AvailableSpaceGB -lt $RequiredSpaceGB) {
Write-Error "Insufficient disk space. Need at least $RequiredSpaceGB GB, have $AvailableSpaceGB GB"
return $false
}
# Check available memory (need at least 4GB)
$Memory = Get-WmiObject -Class Win32_ComputerSystem
$TotalMemoryGB = [math]::Round($Memory.TotalPhysicalMemory / 1GB, 2)
if ($TotalMemoryGB -lt 4) {
Write-Warning "Low available memory: $TotalMemoryGB GB. Recommended: 4GB+"
}
# Check internet connectivity
Write-Info "Checking internet connectivity..."
try {
$testConnection = Test-Connection -ComputerName "8.8.8.8" -Count 1 -Quiet -ErrorAction SilentlyContinue
if (-not $testConnection) {
# Try alternative method
try {
$webRequest = Invoke-WebRequest -Uri "https://www.google.com" -UseBasicParsing -TimeoutSec 5 -ErrorAction Stop
if ($webRequest.StatusCode -ne 200) {
Write-Warning "Internet connection may be unstable. Some installations may fail."
}
}
catch {
Write-Warning "No internet connection detected. Some installations may fail."
Write-Info "Continuing with installation - some tools may need manual installation"
}
}
}
catch {
Write-Warning "Cannot verify internet connectivity. Proceeding with installation."
}
# Check Windows version
$OSVersion = [System.Environment]::OSVersion.Version
if ($OSVersion.Major -lt 10) {
Write-Warning "Windows 10 or later is recommended for best compatibility"
}
Write-Success "System validation completed"
Write-LogFile "INFO" "System validation passed"
return $true
}
# Input validation functions
function Test-ValidInput {
param(
[string]$Input,
[string]$Pattern,
[string]$Description
)
if ([string]::IsNullOrWhiteSpace($Input)) {
Write-Error "Empty input not allowed for $Description"
return $false
}
if ($Pattern -and $Input -notmatch $Pattern) {
Write-Error "Invalid input format for $Description: $Input"
return $false
}
# Check for potentially dangerous characters
if ($Input -match '[;&|`$(){}\[\]]') {
Write-Error "Potentially dangerous characters detected in $Description"
return $false
}
return $true
}
function Get-SafePath {
param([string]$Path)
# Remove potentially dangerous characters
return $Path -replace '[;&|`$(){}\[\]]', '' -replace '\.', '/'
}
# Version checking and update mechanisms
function Get-LatestVersion {
param(
[string]$ToolName,
[string]$CurrentVersion,
[string]$VersionUrl
)
Write-Debug "Checking for latest version of $ToolName..."
if ([string]::IsNullOrWhiteSpace($VersionUrl)) {
Write-Debug "No version URL provided for $ToolName"
return
}
try {
$latestVersion = Invoke-RestMethod -Uri $VersionUrl -TimeoutSec 10 -ErrorAction Stop
if ($latestVersion -is [array]) {
$latestVersion = $latestVersion[0]
}
# Clean version string (remove 'v' prefix if present)
$latestVersion = $latestVersion -replace '^v', ''
$currentVersion = $CurrentVersion -replace '^v', ''
if ($currentVersion -ne $latestVersion) {
Write-Info "$ToolName update available: $currentVersion → $latestVersion"
Write-LogFile "INFO" "$ToolName update available: $currentVersion → $latestVersion"
} else {
Write-Debug "$ToolName is up to date: $currentVersion"
}
}
catch {
Write-Debug "Could not retrieve latest version for $ToolName`: $($_.Exception.Message)"
}
}
# Version comparison function
function Compare-Version {
param(
[string]$Version1,
[string]$Version2
)
if ($Version1 -eq $Version2) {
return 0 # Equal
}
# Split versions into arrays
$v1Parts = $Version1 -split '\.'
$v2Parts = $Version2 -split '\.'
# Compare each part
$maxLength = [Math]::Max($v1Parts.Length, $v2Parts.Length)
for ($i = 0; $i -lt $maxLength; $i++) {
$v1Part = if ($i -lt $v1Parts.Length) { [int]$v1Parts[$i] } else { 0 }
$v2Part = if ($i -lt $v2Parts.Length) { [int]$v2Parts[$i] } else { 0 }
if ($v1Part -gt $v2Part) {
return 1 # Version1 > Version2
} elseif ($v1Part -lt $v2Part) {
return 2 # Version1 < Version2
}
}
return 0 # Equal
}
# Enhanced logging functions with file logging
function Write-Info {
param([string]$Message)
Write-Host "[INFO] $Message" -ForegroundColor $Blue
Write-LogFile "INFO" $Message
}
function Write-Success {
param([string]$Message)
Write-Host "[SUCCESS] $Message" -ForegroundColor $Green
Write-LogFile "SUCCESS" $Message
}
function Write-Warning {
param([string]$Message)
Write-Host "[WARNING] $Message" -ForegroundColor $Yellow
Write-LogFile "WARNING" $Message
}
function Write-Error {
param([string]$Message)
Write-Host "[ERROR] $Message" -ForegroundColor $Red
Write-LogFile "ERROR" $Message
}
function Write-Debug {
param([string]$Message)
if ($Verbose) {
Write-Host "[DEBUG] $Message" -ForegroundColor $Magenta
Write-LogFile "DEBUG" $Message
}
}
# Command line argument parsing
function Parse-Arguments {
param([string[]]$Arguments)
for ($i = 0; $i -lt $Arguments.Length; $i++) {
switch ($Arguments[$i]) {
"-Verbose" { $script:Verbose = $true }
"-DryRun" { $script:DryRun = $true }
"-SkipConfirmation" { $script:SkipConfirmation = $true }
"-Selective" { $script:SelectiveInstall = $true }
"-Recover" {
Restore-Backup
exit 0
}
"-Help" {
Show-Help
exit 0
}
"-Version" {
Write-Host "DevOps Environment Toolkit Installer v2.0.0"
exit 0
}
default {
Write-Error "Unknown option: $($Arguments[$i])"
Show-Help
exit 1
}
}
}
}
function Show-Help {
Write-Host "DevOps Environment Toolkit - Enhanced Installer" -ForegroundColor $White
Write-Host ""
Write-Host "Usage: .\install.ps1 [OPTIONS]" -ForegroundColor $Cyan
Write-Host ""
Write-Host "Options:" -ForegroundColor $Cyan
Write-Host " -Verbose Enable verbose output" -ForegroundColor $Yellow
Write-Host " -DryRun Show what would be installed without actually installing" -ForegroundColor $Yellow
Write-Host " -SkipConfirmation Skip confirmation prompts" -ForegroundColor $Yellow
Write-Host " -Selective Enable selective installation menu" -ForegroundColor $Yellow
Write-Host " -Recover Restore from backup" -ForegroundColor $Yellow
Write-Host " -Help Show this help message" -ForegroundColor $Yellow
Write-Host " -Version Show version information" -ForegroundColor $Yellow
Write-Host ""
Write-Host "Examples:" -ForegroundColor $Cyan
Write-Host " .\install.ps1 # Standard installation" -ForegroundColor $Yellow
Write-Host " .\install.ps1 -Verbose -Selective # Verbose selective installation" -ForegroundColor $Yellow
Write-Host " .\install.ps1 -DryRun # Preview installation" -ForegroundColor $Yellow
Write-Host " .\install.ps1 -Recover # Restore from backup" -ForegroundColor $Yellow
}
# Interactive menu system
function Show-InteractiveMenu {
Write-Host ""
Write-Host "Selective Installation Menu" -ForegroundColor $Cyan
Write-Host "Choose which tools to install:" -ForegroundColor $Yellow
Write-Host ""
$MenuOptions = @{
"1" = "Git"
"2" = "Docker & Docker Compose"
"3" = "Kubernetes (kubectl + Minikube)"
"4" = "Terraform"
"5" = "Ansible"
"6" = "VS Code"
"7" = "AWS CLI"
"8" = "Azure CLI"
"9" = "All Tools (Full Installation)"
"0" = "Exit"
}
# Show menu options
foreach ($key in $MenuOptions.Keys | Sort-Object) {
Write-Host " $key) $($MenuOptions[$key])" -ForegroundColor $Yellow
}
Write-Host ""
while ($true) {
$Choices = Read-Host "Enter your choice (comma-separated for multiple)"
# Validate input
if (-not (Test-ValidInput -Input $Choices -Pattern "^[0-9, ]+$" -Description "menu choices")) {
Write-Host "Invalid input. Please enter numbers only (e.g., 1,2,3 or 9)." -ForegroundColor $Red
continue
}
# Process choices
$ChoiceArray = $Choices -split ","
$ValidChoices = $true
foreach ($Choice in $ChoiceArray) {
$Choice = $Choice.Trim()
switch ($Choice) {
"1" { $script:InstallGit = $true }
"2" { $script:InstallDocker = $true }
"3" { $script:InstallK8s = $true }
"4" { $script:InstallTerraform = $true }
"5" { $script:InstallAnsible = $true }
"6" { $script:InstallVSCode = $true }
"7" { $script:InstallAwsCli = $true }
"8" { $script:InstallAzureCli = $true }
"9" {
$script:InstallGit = $true
$script:InstallDocker = $true
$script:InstallK8s = $true
$script:InstallTerraform = $true
$script:InstallAnsible = $true
$script:InstallVSCode = $true
$script:InstallAwsCli = $true
$script:InstallAzureCli = $true
}
"0" {
Write-Info "Installation cancelled by user"
exit 0
}
default {
Write-Warning "Invalid choice: $Choice"
$ValidChoices = $false
}
}
}
if ($ValidChoices) {
break
} else {
Write-Host "Some choices were invalid. Please try again." -ForegroundColor $Red
}
}
}
# Confirmation prompt with enhanced options
function Confirm-Installation {
if ($SkipConfirmation) {
return
}
Write-Host ""
Write-Host "Installation Summary" -ForegroundColor $Yellow
Write-Host "The following tools will be installed:" -ForegroundColor $Cyan
# Show what will be installed
if ($InstallGit) { Write-Host " ✓ Git" -ForegroundColor $Green }
if ($InstallDocker) { Write-Host " ✓ Docker & Docker Compose" -ForegroundColor $Green }
if ($InstallK8s) { Write-Host " ✓ Kubernetes (kubectl + Minikube)" -ForegroundColor $Green }
if ($InstallTerraform) { Write-Host " ✓ Terraform" -ForegroundColor $Green }
if ($InstallAnsible) { Write-Host " ✓ Ansible" -ForegroundColor $Green }
if ($InstallVSCode) { Write-Host " ✓ VS Code" -ForegroundColor $Green }
if ($InstallAwsCli) { Write-Host " ✓ AWS CLI" -ForegroundColor $Green }
if ($InstallAzureCli) { Write-Host " ✓ Azure CLI" -ForegroundColor $Green }
Write-Host ""
Write-Host "Installation options:" -ForegroundColor $Cyan
Write-Host " • Log file: $LogFile" -ForegroundColor $Yellow
Write-Host " • Backup: $BackupDir\$InstallTimestamp" -ForegroundColor $Yellow
Write-Host " • Verbose: $Verbose" -ForegroundColor $Yellow
Write-Host " • Dry run: $DryRun" -ForegroundColor $Yellow
Write-Host ""
while ($true) {
$Response = Read-Host "Do you want to proceed with the installation? (y/N)"
# Validate input
if ([string]::IsNullOrWhiteSpace($Response)) {
$Response = "n"
}
if ($Response -eq "y" -or $Response -eq "Y") {
break
} elseif ($Response -eq "n" -or $Response -eq "N" -or $Response -eq "n") {
Write-Info "Installation cancelled by user"
exit 0
} else {
Write-Host "Invalid input. Please enter 'y' or 'n'." -ForegroundColor $Red
}
}
}
# Secure download function with verification
function Invoke-SecureDownload {
param(
[string]$Url,
[string]$Output,
[string]$Description
)
Write-Debug "Downloading: $Url"
try {
# Use Invoke-WebRequest with security options
$webClient = New-Object System.Net.WebClient
$webClient.SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
# Set timeout
$webClient.Timeout = 300000 # 5 minutes
# Download with retry logic
$maxRetries = 3
$retryCount = 0
while ($retryCount -lt $maxRetries) {
try {
$webClient.DownloadFile($Url, $Output)
break
}
catch {
$retryCount++
if ($retryCount -eq $maxRetries) {
throw
}
Write-Debug "Download attempt $retryCount failed, retrying..."
Start-Sleep -Seconds 2
}
}
# Verify file exists and has content
if (-not (Test-Path $Output) -or ((Get-Item $Output).Length -eq 0)) {
Write-Error "Downloaded file is empty or missing: $Output"
return $false
}
Write-Success "Successfully downloaded $Description"
return $true
}
catch {
Write-Error "Failed to download $Description`: $($_.Exception.Message)"
return $false
}
finally {
if ($webClient) {
$webClient.Dispose()
}
}
}
# Verify file checksum if provided
function Test-FileChecksum {
param(
[string]$File,
[string]$ExpectedChecksum,
[string]$Algorithm = "SHA256"
)
if ([string]::IsNullOrWhiteSpace($ExpectedChecksum)) {
Write-Debug "No checksum provided for verification"
return $true
}
Write-Debug "Verifying $Algorithm checksum for $File"
try {
$fileStream = [System.IO.File]::OpenRead($File)
$hashAlgorithm = [System.Security.Cryptography.HashAlgorithm]::Create($Algorithm)
$hashBytes = $hashAlgorithm.ComputeHash($fileStream)
$actualChecksum = [System.BitConverter]::ToString($hashBytes).Replace("-", "").ToLowerInvariant()
if ($actualChecksum -eq $ExpectedChecksum.ToLowerInvariant()) {
Write-Success "Checksum verification passed"
return $true
} else {
Write-Error "Checksum verification failed: expected $ExpectedChecksum, got $actualChecksum"
return $false
}
}
catch {
Write-Error "Checksum verification failed: $($_.Exception.Message)"
return $false
}
finally {
if ($fileStream) {
$fileStream.Close()
}
if ($hashAlgorithm) {
$hashAlgorithm.Dispose()
}
}
}
function Invoke-Command {
param(
[string]$Command,
[string]$Description
)
if ($DryRun) {
Write-Info "[DRY RUN] Would execute: $Command"
Write-Debug "Description: $Description"
return $true
}
Write-Debug "Executing: $Command"
try {
$result = Invoke-Expression $Command
if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne $null) {
Write-Error "Failed to execute: $Command (exit code: $LASTEXITCODE)"
return $false
}
Write-Success $Description
return $true
}
catch {
Write-Error "Failed to execute: $Command - $($_.Exception.Message)"
return $false
}
}
# Check if command exists
function Test-CommandExists {
param([string]$Command)
try {
$null = Get-Command $Command -ErrorAction Stop
return $true
}
catch {
return $false
}
}
# Install Chocolatey if not present
function Install-Chocolatey {
if (Test-CommandExists "choco") {
Write-Info "Chocolatey is already installed"
return
}
Write-Info "Installing Chocolatey package manager..."
Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
# Refresh environment variables
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
Write-Success "Chocolatey installed successfully"
}
# Install Git
function Install-Git {
if (Test-CommandExists "git") {
$gitVersion = git --version 2>$null
if ($gitVersion) {
$version = ($gitVersion -replace "git version ", "").Trim()
Write-Info "Git is already installed (version: $version)"
# Check for updates
Get-LatestVersion -ToolName "Git" -CurrentVersion $version -VersionUrl "https://api.github.com/repos/git/git/releases/latest"
} else {
Write-Info "Git is already installed"
}
return
}
Write-Info "Installing Git..."
if (Invoke-Command "choco install git -y" "Installed Git") {
# Configure Git with helpful aliases
Write-Info "Configuring Git aliases..."
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
Write-Success "Git configured successfully"
}
}
# Install Docker Desktop
function Install-DockerDesktop {
if (Test-CommandExists "docker") {
$dockerVersion = docker --version 2>$null
if ($dockerVersion) {
$version = ($dockerVersion -replace "Docker version ", "" -replace ",.*", "").Trim()
Write-Info "Docker is already installed (version: $version)"
# Check for updates (Docker doesn't have a simple version API, so we'll just note current version)
Write-LogFile "INFO" "Docker version: $version"
} else {
Write-Info "Docker is already installed"
}
return
}
Write-Info "Installing Docker Desktop..."
try {
if (Invoke-Command "choco install docker-desktop -y" "Installed Docker Desktop") {
Write-Warning "Please restart your computer and start Docker Desktop manually after installation"
Write-Success "Docker Desktop installed successfully"
} else {
throw "Chocolatey installation failed"
}
}
catch {
Write-Error "Failed to install Docker Desktop: $($_.Exception.Message)"
Write-Warning "Please install Docker Desktop manually from https://www.docker.com/products/docker-desktop"
return $false
}
}
# Install Docker Compose
function Install-DockerCompose {
if (Test-CommandExists "docker-compose") {
$composeVersion = docker-compose --version 2>$null
if ($composeVersion) {
$version = ($composeVersion -replace "Docker Compose version ", "" -replace ",.*", "").Trim()
Write-Info "Docker Compose is already installed (version: $version)"
} else {
Write-Info "Docker Compose is already installed"
}
return
}
Write-Info "Installing Docker Compose..."
try {
if (Invoke-Command "choco install docker-compose -y" "Installed Docker Compose") {
Write-Success "Docker Compose installed successfully"
} else {
throw "Chocolatey installation failed"
}
}
catch {
Write-Error "Failed to install Docker Compose: $($_.Exception.Message)"
Write-Warning "Please install Docker Compose manually from https://docs.docker.com/compose/install/"
return $false
}
}
# Install VS Code
function Install-VSCode {
if (Test-CommandExists "code") {
Write-Info "VS Code is already installed"
return
}
Write-Info "Installing VS Code..."
choco install vscode -y
Write-Success "VS Code installed successfully"
}
# Install Minikube
function Install-Minikube {
if (Test-CommandExists "minikube") {
Write-Info "Minikube is already installed"
return
}
Write-Info "Installing Minikube..."
try {
if (Invoke-Command "choco install minikube -y" "Installed Minikube") {
Write-Success "Minikube installed successfully"
} else {
throw "Chocolatey installation failed"
}
}
catch {
Write-Error "Failed to install Minikube: $($_.Exception.Message)"
Write-Warning "Please install Minikube manually from https://minikube.sigs.k8s.io/docs/start/"
return $false
}
}
# Install Ansible
function Install-Ansible {
if (Test-CommandExists "ansible") {
Write-Info "Ansible is already installed"
return
}
Write-Info "Installing Ansible..."
choco install ansible -y
Write-Success "Ansible installed successfully"
}
# Install Terraform (basic version for learning)
function Install-Terraform {
if (Test-CommandExists "terraform") {
$tfVersion = terraform --version 2>$null
if ($tfVersion) {
$version = ($tfVersion -replace "Terraform v", "").Trim().Split("`n")[0]
Write-Info "Terraform is already installed (version: $version)"
} else {
Write-Info "Terraform is already installed"
}
return
}
Write-Info "Installing Terraform..."
try {
if (Invoke-Command "choco install terraform -y" "Installed Terraform") {
Write-Success "Terraform installed successfully"
} else {
throw "Chocolatey installation failed"
}
}
catch {
Write-Error "Failed to install Terraform: $($_.Exception.Message)"
Write-Warning "Please install Terraform manually from https://www.terraform.io/downloads"
return $false
}
}
# Install kubectl
function Install-Kubectl {
if (Test-CommandExists "kubectl") {
$kubectlVersion = kubectl version --client 2>$null
if ($kubectlVersion) {
$match = $kubectlVersion | Select-String "GitVersion.*v([0-9.]+)"
if ($match) {
$version = $match.Matches[0].Groups[1].Value
Write-Info "kubectl is already installed (version: $version)"
} else {
Write-Info "kubectl is already installed"
}
} else {
Write-Info "kubectl is already installed"
}
return
}
Write-Info "Installing kubectl..."
try {
if (Invoke-Command "choco install kubernetes-cli -y" "Installed kubectl") {
Write-Success "kubectl installed successfully"
} else {
throw "Chocolatey installation failed"
}
}
catch {
Write-Error "Failed to install kubectl: $($_.Exception.Message)"
Write-Warning "Please install kubectl manually from https://kubernetes.io/docs/tasks/tools/"
return $false
}
}
# Install AWS CLI
function Install-AWSCLI {
if (Test-CommandExists "aws") {
Write-Info "AWS CLI is already installed"
return