-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathsetUp.ps1
More file actions
758 lines (620 loc) · 21.7 KB
/
setUp.ps1
File metadata and controls
758 lines (620 loc) · 21.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
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
#Requires -Version 5.1
<#
.SYNOPSIS
setUp.ps1 - Sets up Azure Dev Box environment with GitHub integration
.DESCRIPTION
Automates the setup of an Azure Developer CLI (azd) environment for Dev Box,
handles GitHub authentication, and provisions required Azure resources.
This script follows Azure best practices for security, error handling,
and resource management.
.PARAMETER EnvName
Name of the Azure environment to create
.PARAMETER SourceControl
Source control platform (github or adogit)
.PARAMETER Help
Show this help message
.EXAMPLE
.\setUp.ps1 -EnvName "prod" -SourceControl "github"
# Creates a "prod" environment with GitHub
.EXAMPLE
.\setUp.ps1 -EnvName "dev" -SourceControl "adogit"
# Creates a "dev" environment with Azure DevOps
.NOTES
Requirements:
- Azure CLI (az)
- Azure Developer CLI (azd)
- GitHub CLI (gh) [if using GitHub]
- Valid authentication for chosen platform
Author: DevExp Team
Last Updated: 2025-09-03
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]$EnvName,
[Parameter(Mandatory = $false)]
[ValidateSet("github", "adogit", "")]
[string]$SourceControl,
[Parameter(Mandatory = $false)]
[switch]$Help
)
# Script Configuration
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
# Global Variables
$Script:ScriptDir = $PSScriptRoot
$Script:TimestampFormat = "yyyy-MM-dd HH:mm:ss"
# Unicode icons
$Script:InfoIcon = "ℹ️"
$Script:WarningIcon = "⚠️"
$Script:ErrorIcon = "❌"
$Script:SuccessIcon = "✅"
# Global variables for script state
$Script:GitHubToken = ""
$Script:AdoToken = ""
#######################################
# Helper Functions
#######################################
function Write-LogMessage {
<#
.SYNOPSIS
Logging function with different levels and colors.
.DESCRIPTION
Writes formatted log messages with timestamps and colored output
based on the message severity level.
.PARAMETER Message
The message text to log.
.PARAMETER Level
The severity level of the message. Valid values: Info, Warning, Error, Success.
.EXAMPLE
Write-LogMessage -Message "Operation completed" -Level "Success"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Message,
[Parameter(Mandatory = $false)]
[ValidateSet("Info", "Warning", "Error", "Success")]
[string]$Level = "Info"
)
$timestamp = Get-Date -Format $Script:TimestampFormat
switch ($Level) {
"Error" {
Write-Host "$Script:ErrorIcon " -ForegroundColor Red -NoNewline
Write-Host "[$timestamp] $Message" -ForegroundColor Red
}
"Warning" {
Write-Host "$Script:WarningIcon " -ForegroundColor Yellow -NoNewline
Write-Host "[$timestamp] $Message" -ForegroundColor Yellow
}
"Success" {
Write-Host "$Script:SuccessIcon " -ForegroundColor Green -NoNewline
Write-Host "[$timestamp] $Message" -ForegroundColor Green
}
default {
Write-Host "$Script:InfoIcon " -ForegroundColor Cyan -NoNewline
Write-Host "[$timestamp] $Message" -ForegroundColor Cyan
}
}
}
function Test-CommandAvailability {
<#
.SYNOPSIS
Check if a command is available in PATH.
.DESCRIPTION
Verifies that the specified command or tool is available
for execution in the current environment.
.PARAMETER Command
The name of the command to check.
.OUTPUTS
System.Boolean - True if command exists, False otherwise.
.EXAMPLE
if (Test-CommandAvailability -Command "az") { Write-Host "Azure CLI is available" }
#>
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory = $true)]
[string]$Command
)
$commandPath = Get-Command $Command -ErrorAction SilentlyContinue
if (-not $commandPath) {
Write-LogMessage "Required command '$Command' was not found. Please install it before continuing." "Error"
return $false
}
return $true
}
function Show-Help {
<#
.SYNOPSIS
Show help message
#>
$helpText = @"
setUp.ps1 - Sets up Azure Dev Box environment with source control integration
USAGE:
.\setUp.ps1 -EnvName ENV_NAME -SourceControl PLATFORM
PARAMETERS:
-EnvName ENV_NAME Name of the Azure environment to create
-SourceControl PLATFORM Source control platform (github or adogit)
-Help Show this help message
EXAMPLES:
.\setUp.ps1 -EnvName "prod" -SourceControl "github"
.\setUp.ps1 -EnvName "dev" -SourceControl "adogit"
REQUIREMENTS:
- Azure CLI (az)
- Azure Developer CLI (azd)
- GitHub CLI (gh) [if using GitHub]
- Valid authentication for chosen platform
"@
Write-Host $helpText
}
function Test-SourceControlValidation {
<#
.SYNOPSIS
Validates the source control platform parameter.
.DESCRIPTION
Checks if the specified platform is a valid source control option.
.PARAMETER Platform
The source control platform to validate (github, adogit, or empty).
.OUTPUTS
System.Boolean - True if valid, False otherwise.
.EXAMPLE
if (Test-SourceControlValidation -Platform "github") { Write-Host "Valid platform" }
#>
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$Platform
)
if ($Platform -in @("github", "adogit", "")) {
return $true
}
else {
Write-LogMessage "Invalid source control platform: $Platform" "Error"
Write-LogMessage "Valid platforms: github, adogit" "Info"
return $false
}
}
#######################################
# Authentication Functions
#######################################
function Test-AzureAuthentication {
<#
.SYNOPSIS
Tests Azure CLI authentication status.
.DESCRIPTION
Verifies that the user is logged into Azure CLI and the current
subscription is in an enabled state.
.OUTPUTS
System.Boolean - True if authenticated with valid subscription, False otherwise.
.EXAMPLE
if (Test-AzureAuthentication) { Write-Host "Ready to use Azure" }
#>
[CmdletBinding()]
[OutputType([bool])]
param()
Write-LogMessage "Verifying Azure authentication..." "Info"
try {
$azContext = az account show 2>$null | ConvertFrom-Json
if (-not $azContext) {
Write-LogMessage "Not logged into Azure. Please run 'az login' first." "Error"
return $false
}
# Check if subscription is enabled (Azure best practice)
if ($azContext.state -ne "Enabled") {
Write-LogMessage "Current subscription '$($azContext.name)' is not in 'Enabled' state." "Error"
return $false
}
# Output subscription details for verification
Write-LogMessage "Using Azure subscription: $($azContext.name) (ID: $($azContext.id))" "Info"
return $true
}
catch {
Write-LogMessage "Failed to verify Azure authentication: $($_.Exception.Message)" "Error"
return $false
}
}
function Test-AdoAuthentication {
<#
.SYNOPSIS
Tests Azure DevOps authentication status.
.DESCRIPTION
Verifies that the Azure DevOps CLI extension is configured
and the user is authenticated.
.OUTPUTS
System.Boolean - True if authenticated, False otherwise.
.EXAMPLE
if (Test-AdoAuthentication) { Write-Host "Ready to use Azure DevOps" }
#>
[CmdletBinding()]
[OutputType([bool])]
param()
Write-LogMessage "Verifying Azure DevOps authentication..." "Info"
try {
$null = az devops configure --list 2>$null
if ($LASTEXITCODE -ne 0) {
Write-LogMessage "Not logged into Azure DevOps. Please run 'az devops login' first." "Error"
return $false
}
Write-LogMessage "Azure DevOps authentication verified successfully" "Success"
return $true
}
catch {
Write-LogMessage "Failed to verify Azure DevOps authentication: $($_.Exception.Message)" "Error"
return $false
}
}
function Test-GitHubAuthentication {
<#
.SYNOPSIS
Tests GitHub CLI authentication status.
.DESCRIPTION
Verifies that the user is authenticated with GitHub CLI.
.OUTPUTS
System.Boolean - True if authenticated, False otherwise.
.EXAMPLE
if (Test-GitHubAuthentication) { Write-Host "Ready to use GitHub" }
#>
[CmdletBinding()]
[OutputType([bool])]
param()
Write-LogMessage "Verifying GitHub authentication..." "Info"
try {
$null = gh auth status 2>$null
if ($LASTEXITCODE -ne 0) {
Write-LogMessage "Not logged into GitHub. Please run 'gh auth login' first." "Error"
return $false
}
Write-LogMessage "GitHub authentication verified successfully" "Success"
return $true
}
catch {
Write-LogMessage "Failed to verify GitHub authentication: $($_.Exception.Message)" "Error"
return $false
}
}
function Get-SecureGitHubToken {
<#
.SYNOPSIS
Retrieves the GitHub token securely.
.DESCRIPTION
Gets the GitHub authentication token either from an environment
variable or by using the GitHub CLI.
.OUTPUTS
System.Boolean - True if token retrieved successfully, False otherwise.
.EXAMPLE
if (Get-SecureGitHubToken) { Write-Host "Token available" }
#>
[CmdletBinding()]
[OutputType([bool])]
param()
Write-LogMessage "Retrieving GitHub token..." "Info"
# Check if KEY_VAULT_SECRET environment variable is already set
if ($env:KEY_VAULT_SECRET) {
Write-LogMessage "Using existing KEY_VAULT_SECRET from environment" "Info"
$Script:GitHubToken = $env:KEY_VAULT_SECRET
}
else {
try {
# Retrieve GitHub token using gh CLI
$Script:GitHubToken = gh auth token 2>$null
if ($LASTEXITCODE -ne 0 -or -not $Script:GitHubToken) {
Write-LogMessage "Failed to retrieve GitHub token" "Error"
return $false
}
# Export as environment variable for future use
$env:KEY_VAULT_SECRET = $Script:GitHubToken
}
catch {
Write-LogMessage "Failed to retrieve GitHub token: $($_.Exception.Message)" "Error"
return $false
}
}
if (-not $Script:GitHubToken) {
Write-LogMessage "Failed to retrieve GitHub token" "Error"
return $false
}
Write-LogMessage "GitHub token retrieved and stored securely" "Success"
return $true
}
function Get-SecureAdoGitToken {
<#
.SYNOPSIS
Retrieves the Azure DevOps PAT securely.
.DESCRIPTION
Gets the Azure DevOps Personal Access Token either from an
environment variable or by prompting the user securely.
.OUTPUTS
System.Boolean - True if token retrieved successfully, False otherwise.
.EXAMPLE
if (Get-SecureAdoGitToken) { Write-Host "Token available" }
#>
[CmdletBinding()]
[OutputType([bool])]
param()
Write-LogMessage "Retrieving Azure DevOps token..." "Info"
# Try to get PAT from environment variable first
if ($env:KEY_VAULT_SECRET) {
$Script:AdoToken = $env:KEY_VAULT_SECRET
Write-LogMessage "Azure DevOps PAT retrieved from Key Vault" "Success"
}
else {
Write-LogMessage "Azure DevOps PAT not found in environment variables." "Warning"
Write-LogMessage "Please enter your PAT securely." "Warning"
# Prompt for PAT securely (no echo)
$secureString = Read-Host "Enter your Azure DevOps Personal Access Token" -AsSecureString
$Script:AdoToken = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString))
# Configure Azure DevOps defaults
try {
$null = az devops configure --defaults organization=https://dev.azure.com/contososa2 project=DevExp-DevBox 2>$null
if ($LASTEXITCODE -ne 0) {
Write-LogMessage "Azure DevOps organization and project not set. Please configure them first." "Error"
return $false
}
}
catch {
Write-LogMessage "Failed to configure Azure DevOps defaults: $($_.Exception.Message)" "Error"
return $false
}
}
if (-not $Script:AdoToken) {
Write-LogMessage "Failed to retrieve Azure DevOps PAT" "Error"
return $false
}
# Export the token to environment variable
$env:AZURE_DEVOPS_EXT_PAT = $Script:AdoToken
Write-LogMessage "Azure DevOps PAT retrieved and stored securely" "Success"
return $true
}
#######################################
# Azure Configuration Functions
#######################################
function Initialize-AzdEnvironment {
<#
.SYNOPSIS
Initializes the Azure Developer CLI environment.
.DESCRIPTION
Sets up the azd environment with appropriate tokens based on the
selected source control platform.
.OUTPUTS
System.Boolean - True if initialization succeeded, False otherwise.
.EXAMPLE
if (Initialize-AzdEnvironment) { Write-Host "Environment ready" }
#>
[CmdletBinding()]
[OutputType([bool])]
param()
Write-LogMessage "Initializing Azure Developer CLI environment..." "Info"
$pat = ""
$tokenType = ""
# Get appropriate token based on source control platform
switch ($SourceControl) {
"github" {
Write-LogMessage "Retrieving GitHub token for environment initialization..." "Info"
if (-not (Get-SecureGitHubToken)) {
Write-LogMessage "Unable to retrieve GitHub token. Aborting environment initialization." "Error"
return $false
}
$pat = $Script:GitHubToken
$tokenType = "GitHub"
}
"adogit" {
Write-LogMessage "Retrieving Azure DevOps token for environment initialization..." "Info"
if (-not (Get-SecureAdoGitToken)) {
Write-LogMessage "Unable to retrieve Azure DevOps token. Aborting environment initialization." "Error"
return $false
}
$pat = $Script:AdoToken
$tokenType = "Azure DevOps"
}
default {
Write-LogMessage "Unsupported source control platform: $SourceControl" "Error"
return $false
}
}
# Mask most of the token for security best practices
if ($pat.Length -ge 8) {
$maskedToken = $pat.Substring(0, 4) + "****" + $pat.Substring($pat.Length - 2)
}
else {
$maskedToken = "****"
}
Write-LogMessage "🔐 $tokenType token stored securely in memory. Masked: $maskedToken" "Success"
# Azure best practice: Verify environment exists or use existing
Write-LogMessage "Using Azure Developer CLI environment: '$EnvName'" "Info"
# Prepare environment file path
$envDir = ".\.azure\$EnvName"
$envFile = "$envDir\.env"
if (-not (Test-Path $envDir)) {
New-Item -ItemType Directory -Path $envDir -Force | Out-Null
}
# Azure best practice: Use environment-specific configuration
Write-LogMessage "Configuring environment variables in $envFile" "Info"
# Append to existing file or create if it doesn't exist
Add-Content -Path $envFile -Value "KEY_VAULT_SECRET='$pat'"
Add-Content -Path $envFile -Value "SOURCE_CONTROL_PLATFORM='$SourceControl'"
# Show current configuration for verification
Write-LogMessage "Current Azure Developer CLI configuration:" "Info"
azd config show
Write-LogMessage "Azure Developer CLI environment '$EnvName' initialized successfully." "Success"
return $true
}
function Start-AzureProvisioning {
<#
.SYNOPSIS
Starts Azure resource provisioning.
.DESCRIPTION
Initiates the Azure Developer CLI provisioning process for
the configured environment.
.OUTPUTS
System.Boolean - True if provisioning succeeded, False otherwise.
.EXAMPLE
if (Start-AzureProvisioning) { Write-Host "Resources provisioned" }
#>
[CmdletBinding()]
[OutputType([bool])]
param()
Write-LogMessage "Starting Azure resource provisioning with azd..." "Info"
try {
azd provision -e $EnvName
if ($LASTEXITCODE -ne 0) {
Write-LogMessage "Azure provisioning failed with exit code $LASTEXITCODE" "Error"
Write-LogMessage "This might be a quota or permissions issue. Check your Azure subscription limits and role assignments." "Warning"
return $false
}
Write-LogMessage "Azure provisioning completed successfully" "Success"
return $true
}
catch {
Write-LogMessage "Azure provisioning failed: $($_.Exception.Message)" "Error"
return $false
}
}
function Select-SourceControlPlatform {
<#
.SYNOPSIS
Provides interactive source control platform selection.
.DESCRIPTION
Prompts the user to select their source control platform
when not specified via parameter.
.EXAMPLE
Select-SourceControlPlatform
#>
[CmdletBinding()]
param()
Write-LogMessage "Please select your source control platform:" "Info"
Write-Host ""
Write-Host " " -NoNewline
Write-Host "1. Azure DevOps Git (adogit)" -ForegroundColor Yellow
Write-Host " " -NoNewline
Write-Host "2. GitHub (github)" -ForegroundColor Yellow
Write-Host ""
$validSelection = $false
while (-not $validSelection) {
$selection = Read-Host "Enter your choice (1 or 2)"
switch ($selection) {
"1" {
$Script:SourceControl = "adogit"
Write-LogMessage "Selected: Azure DevOps Git" "Success"
$validSelection = $true
}
"2" {
$Script:SourceControl = "github"
Write-LogMessage "Selected: GitHub" "Success"
$validSelection = $true
}
default {
Write-LogMessage "Invalid selection. Please enter 1 or 2." "Warning"
}
}
}
}
#######################################
# Main Script Logic
#######################################
function Test-Arguments {
<#
.SYNOPSIS
Validates and processes command line arguments.
.DESCRIPTION
Checks for help flag, validates required parameters, and prompts
for source control selection if not provided.
.EXAMPLE
Test-Arguments
#>
[CmdletBinding()]
param()
# Show help if requested
if ($Help) {
Show-Help
exit 0
}
# Validate required parameters
if (-not $EnvName) {
Write-LogMessage "Environment name is required. Use -EnvName parameter." "Error"
Show-Help
exit 1
}
# If source control not provided, prompt for it
if (-not $SourceControl) {
Select-SourceControlPlatform
}
# Validate parameters
if (-not (Test-SourceControlValidation $SourceControl)) {
exit 1
}
}
function Invoke-Main {
<#
.SYNOPSIS
Main execution function for the setup script.
.DESCRIPTION
Orchestrates the complete setup process including argument validation,
tool verification, authentication checks, and environment initialization.
.EXAMPLE
Invoke-Main
#>
[CmdletBinding()]
param()
$requiredTools = @("az", "azd")
# Process arguments
Test-Arguments
# Script header with basic information
Write-LogMessage "Starting Dev Box environment setup" "Info"
Write-LogMessage "Environment name: $EnvName" "Info"
Write-LogMessage "Source control platform: $SourceControl" "Info"
# Add GitHub CLI to required tools if using GitHub
if ($SourceControl -eq "github") {
$requiredTools += "gh"
}
# Verify required tools - Azure best practice for dependency validation
Write-LogMessage "Checking required tools..." "Info"
foreach ($tool in $requiredTools) {
if (-not (Test-CommandAvailability $tool)) {
Write-LogMessage "Missing required tools. Please install them and retry." "Error"
exit 1
}
}
Write-LogMessage "All required tools are available" "Success"
# Verify Azure authentication - Azure security best practice
if (-not (Test-AzureAuthentication)) {
exit 1
}
# Verify source control authentication
switch ($SourceControl) {
"github" {
if (-not (Test-GitHubAuthentication)) {
exit 1
}
}
"adogit" {
if (-not (Test-AdoAuthentication)) {
exit 1
}
}
}
# Initialize azd environment
if (-not (Initialize-AzdEnvironment)) {
Write-LogMessage "Failed to initialize Azure Developer CLI environment. Exiting." "Error"
exit 1
}
# Success message with environment details
Write-LogMessage "Dev Box environment '$EnvName' setup successfully" "Success"
Write-LogMessage "Access your Dev Center from the Azure portal" "Info"
Write-LogMessage "Use 'azd env get-values' to view environment settings" "Info"
}
# Set up error handling and cleanup
trap {
Write-LogMessage "Script interrupted by user" "Warning"
exit 130
}
# Execute main function
try {
Invoke-Main
}
catch {
Write-LogMessage "Script execution failed: $($_.Exception.Message)" "Error"
exit 1
}