-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanage-chaos-experiments.ps1
More file actions
447 lines (392 loc) · 15.1 KB
/
Copy pathmanage-chaos-experiments.ps1
File metadata and controls
447 lines (392 loc) · 15.1 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
# Chaos Experiment Management Script (PowerShell)
# Usage: .\manage-chaos-experiments.ps1 [list|create|delete|status] [experiment-name]
param(
[Parameter(Position=0)]
[ValidateSet('list', 'status', 'create', 'delete', 'sync-state', 'validate', 'help')]
[string]$Command = 'help',
[Parameter(Position=1)]
[string]$ExperimentName,
[Parameter(Position=2)]
[string]$TemplateType
)
$ResourceGroup = "eShopCleverRG"
$SubscriptionId = "5f62fee3-b00a-44d2-86e5-5cf130b28b5d"
$TerraformDir = ".\terraform-export-clean"
function Write-ColoredOutput {
param(
[string]$Message,
[string]$Color = "White"
)
switch ($Color) {
"Red" { Write-Host $Message -ForegroundColor Red }
"Green" { Write-Host $Message -ForegroundColor Green }
"Yellow" { Write-Host $Message -ForegroundColor Yellow }
"Blue" { Write-Host $Message -ForegroundColor Blue }
"Cyan" { Write-Host $Message -ForegroundColor Cyan }
default { Write-Host $Message }
}
}
function Show-Usage {
Write-Host "Usage: .\manage-chaos-experiments.ps1 [command] [options]" -ForegroundColor Cyan
Write-Host ""
Write-Host "Commands:" -ForegroundColor Yellow
Write-Host " list List all chaos experiments"
Write-Host " status [experiment-name] Show status of specific experiment"
Write-Host " create [template] Create experiment from template"
Write-Host " delete [experiment-name] Delete experiment (with confirmation)"
Write-Host " sync-state Synchronize Terraform state"
Write-Host " validate Validate all Terraform configurations"
Write-Host ""
Write-Host "Examples:" -ForegroundColor Yellow
Write-Host " .\manage-chaos-experiments.ps1 list"
Write-Host " .\manage-chaos-experiments.ps1 status eshoppodfailure"
Write-Host " .\manage-chaos-experiments.ps1 create pod-failure"
Write-Host " .\manage-chaos-experiments.ps1 delete my-experiment"
Write-Host " .\manage-chaos-experiments.ps1 sync-state"
}
function Test-Prerequisites {
Write-ColoredOutput "Checking prerequisites..." "Blue"
# Check if Azure CLI is installed
try {
$null = az --version
} catch {
Write-ColoredOutput "Error: Azure CLI is not installed" "Red"
exit 1
}
# Check if logged in to Azure
try {
$null = az account show 2>$null
} catch {
Write-ColoredOutput "Error: Not logged in to Azure. Run 'az login' first" "Red"
exit 1
}
# Check if Terraform is installed
try {
$null = terraform version
} catch {
Write-ColoredOutput "Error: Terraform is not installed" "Red"
exit 1
}
# Check if kubectl is installed
try {
$null = kubectl version --client
} catch {
Write-ColoredOutput "Error: kubectl is not installed" "Red"
exit 1
}
Write-ColoredOutput "✓ All prerequisites met" "Green"
}
function Get-ChaosExperiments {
Write-ColoredOutput "Listing all chaos experiments..." "Blue"
# List from Azure
Write-Host ""
Write-ColoredOutput "Azure Chaos Studio Experiments:" "Yellow"
try {
$azureExperiments = az rest --method GET `
--url "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Chaos/experiments?api-version=2024-01-01" `
--query "value[].{Name:name,Location:location,Status:properties.provisioningState}" `
--output table 2>$null
if ($azureExperiments) {
Write-Host $azureExperiments
} else {
Write-Host "No experiments found in Azure"
}
} catch {
Write-Host "Error retrieving experiments from Azure"
}
# List from Terraform state
Write-Host ""
Write-ColoredOutput "Terraform State Experiments:" "Yellow"
if (Test-Path $TerraformDir) {
Push-Location $TerraformDir
try {
terraform init -backend=true | Out-Null
$stateList = terraform state list | Where-Object { $_ -match "azurerm_chaos_studio_experiment" }
if ($stateList) {
$stateList | ForEach-Object { $_ -replace "azurerm_chaos_studio_experiment\.", "" }
} else {
Write-Host "No experiments found in Terraform state"
}
} catch {
Write-Host "Error reading Terraform state"
} finally {
Pop-Location
}
} else {
Write-Host "Terraform directory not found"
}
# List Terraform files
Write-Host ""
Write-ColoredOutput "Terraform Configuration Files:" "Yellow"
$configFiles = Get-ChildItem -Path $TerraformDir -Name "chaos-experiment-*.tf" -ErrorAction SilentlyContinue
if ($configFiles) {
$configFiles | ForEach-Object {
$_ -replace "chaos-experiment-", "" -replace "\.tf$", ""
}
} else {
Write-Host "No experiment configuration files found"
}
}
function Get-ExperimentStatus {
param([string]$Name)
if (-not $Name) {
Write-ColoredOutput "Error: Experiment name required" "Red"
exit 1
}
Write-ColoredOutput "Showing status for experiment: $Name" "Blue"
# Get experiment details from Azure
try {
$experimentDetails = az rest --method GET `
--url "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Chaos/experiments/$Name?api-version=2024-01-01" `
2>$null | ConvertFrom-Json
if ($experimentDetails) {
Write-Host ""
Write-ColoredOutput "✓ Experiment found in Azure" "Green"
Write-Host "Name: $($experimentDetails.name)"
Write-Host "Status: $($experimentDetails.properties.provisioningState)"
Write-Host "Location: $($experimentDetails.location)"
Write-Host "Created: $($experimentDetails.systemData.createdAt)"
Write-Host "Last Modified: $($experimentDetails.systemData.lastModifiedAt)"
# Get experiment executions
Write-Host ""
Write-ColoredOutput "Recent Executions:" "Yellow"
try {
$executions = az rest --method GET `
--url "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Chaos/experiments/$Name/executions?api-version=2024-01-01" `
--query "value[0:5].{Status:properties.status,Started:properties.startedAt,Stopped:properties.stoppedAt}" `
--output table 2>$null
if ($executions) {
Write-Host $executions
} else {
Write-Host "No executions found"
}
} catch {
Write-Host "Error retrieving executions"
}
} else {
Write-ColoredOutput "✗ Experiment not found in Azure" "Red"
}
} catch {
Write-ColoredOutput "✗ Experiment not found in Azure" "Red"
}
# Check Terraform state
if (Test-Path $TerraformDir) {
Push-Location $TerraformDir
try {
terraform init -backend=true | Out-Null
$stateShow = terraform state show "azurerm_chaos_studio_experiment.$Name" 2>$null
if ($stateShow) {
Write-Host ""
Write-ColoredOutput "✓ Experiment found in Terraform state" "Green"
$stateShow | Select-Object -First 20 | Write-Host
} else {
Write-Host ""
Write-ColoredOutput "✗ Experiment not found in Terraform state" "Red"
}
} catch {
Write-Host ""
Write-ColoredOutput "✗ Experiment not found in Terraform state" "Red"
} finally {
Pop-Location
}
}
# Check for configuration file
$configFile = Join-Path $TerraformDir "chaos-experiment-$Name.tf"
if (Test-Path $configFile) {
Write-Host ""
Write-ColoredOutput "✓ Configuration file exists: chaos-experiment-$Name.tf" "Green"
} else {
Write-Host ""
Write-ColoredOutput "✗ Configuration file not found" "Red"
}
}
function New-ExperimentTemplate {
param([string]$TemplateType)
if (-not $TemplateType) {
Write-ColoredOutput "Error: Template type required" "Red"
Write-Host "Available templates: pod-failure, cpu-stress, memory-stress, network-delay"
exit 1
}
Write-ColoredOutput "Creating experiment template: $TemplateType" "Blue"
# Generate a sample experiment name
$experimentName = "sample-$TemplateType-$(Get-Date -Format 'yyyyMMddHHmmss')"
Write-Host ""
Write-Host "Use the GitHub Actions workflow to create the experiment:"
Write-Host ""
Write-Host "1. Go to: https://github.com/CleveritDemo/AzureSREAgent/actions/workflows/provision-chaos-experiment.yml"
Write-Host "2. Click 'Run workflow'"
Write-Host "3. Fill in the parameters:"
Write-Host " - Experiment name: $experimentName"
Write-Host " - Experiment type: $TemplateType"
Write-Host " - Target namespace: eshop"
Write-Host " - Target labels: {`"app`": `"eshop-webmvc`"}"
Write-Host " - Duration: 5 minutes"
Write-Host " - Action duration: 60s"
Write-Host "4. Set 'dry_run' to true for testing"
Write-Host ""
Write-Host "Or use the GitHub CLI:"
Write-Host "gh workflow run provision-chaos-experiment.yml \"
Write-Host " --field experiment_name=`"$experimentName`" \"
Write-Host " --field experiment_type=`"$TemplateType`" \"
Write-Host " --field target_namespace=`"eshop`" \"
Write-Host " --field target_labels='{`"app`": `"eshop-webmvc`"}' \"
Write-Host " --field duration_minutes=`"5`" \"
Write-Host " --field action_duration=`"60s`" \"
Write-Host " --field dry_run=true"
}
function Remove-Experiment {
param([string]$Name)
if (-not $Name) {
Write-ColoredOutput "Error: Experiment name required" "Red"
exit 1
}
Write-ColoredOutput "⚠️ This will delete the chaos experiment: $Name" "Yellow"
Write-Host "This action will:"
Write-Host "1. Remove the experiment from Azure Chaos Studio"
Write-Host "2. Remove the resource from Terraform state"
Write-Host "3. Delete the Terraform configuration file"
Write-Host ""
$response = Read-Host "Are you sure you want to continue? (yes/no)"
if ($response -ne "yes") {
Write-Host "Operation cancelled"
exit 0
}
Write-ColoredOutput "Deleting experiment: $Name" "Blue"
# Delete from Terraform
if (Test-Path $TerraformDir) {
Push-Location $TerraformDir
try {
terraform init -backend=true | Out-Null
# Remove from state
$stateExists = terraform state show "azurerm_chaos_studio_experiment.$Name" 2>$null
if ($stateExists) {
Write-Host "Removing from Terraform state..."
terraform destroy -target="azurerm_chaos_studio_experiment.$Name" -auto-approve
}
# Remove configuration file
$configFile = "chaos-experiment-$Name.tf"
if (Test-Path $configFile) {
Write-Host "Removing configuration file..."
Remove-Item $configFile -Force
}
} catch {
Write-ColoredOutput "Error during deletion: $_" "Red"
} finally {
Pop-Location
}
}
Write-ColoredOutput "✓ Experiment deleted successfully" "Green"
}
function Sync-TerraformState {
Write-ColoredOutput "Synchronizing Terraform state..." "Blue"
if (-not (Test-Path $TerraformDir)) {
Write-ColoredOutput "Error: Terraform directory not found" "Red"
exit 1
}
Push-Location $TerraformDir
try {
# Initialize and refresh state
Write-Host "Initializing Terraform..."
terraform init -upgrade
Write-Host "Refreshing state..."
terraform refresh
Write-Host "Validating configuration..."
terraform validate
Write-Host "Planning changes..."
terraform plan -detailed-exitcode | Out-Null
$planExitCode = $LASTEXITCODE
switch ($planExitCode) {
0 {
Write-ColoredOutput "✓ No changes needed - state is in sync" "Green"
}
1 {
Write-ColoredOutput "✗ Terraform plan failed" "Red"
exit 1
}
2 {
Write-ColoredOutput "⚠️ Changes detected - run 'terraform apply' to sync" "Yellow"
}
}
} catch {
Write-ColoredOutput "Error during state sync: $_" "Red"
} finally {
Pop-Location
}
}
function Test-Configurations {
Write-ColoredOutput "Validating all Terraform configurations..." "Blue"
if (-not (Test-Path $TerraformDir)) {
Write-ColoredOutput "Error: Terraform directory not found" "Red"
exit 1
}
Push-Location $TerraformDir
try {
# Initialize
terraform init -backend=true | Out-Null
# Validate
$validation = terraform validate
if ($LASTEXITCODE -eq 0) {
Write-ColoredOutput "✓ All configurations are valid" "Green"
} else {
Write-ColoredOutput "✗ Configuration validation failed" "Red"
Write-Host $validation
exit 1
}
# Check for syntax errors in individual files
Write-Host ""
Write-ColoredOutput "Checking individual experiment files:" "Yellow"
$experimentFiles = Get-ChildItem -Name "chaos-experiment-*.tf" -ErrorAction SilentlyContinue
foreach ($file in $experimentFiles) {
Write-Host -NoNewline "Checking $file... "
try {
$validateResult = terraform validate -json | ConvertFrom-Json
if ($validateResult.valid) {
Write-ColoredOutput "✓" "Green"
} else {
Write-ColoredOutput "✗" "Red"
}
} catch {
Write-ColoredOutput "✗" "Red"
}
}
} catch {
Write-ColoredOutput "Error during validation: $_" "Red"
} finally {
Pop-Location
}
}
# Main script logic
switch ($Command) {
"list" {
Test-Prerequisites
Get-ChaosExperiments
}
"status" {
Test-Prerequisites
Get-ExperimentStatus -Name $ExperimentName
}
"create" {
New-ExperimentTemplate -TemplateType $ExperimentName
}
"delete" {
Test-Prerequisites
Remove-Experiment -Name $ExperimentName
}
"sync-state" {
Test-Prerequisites
Sync-TerraformState
}
"validate" {
Test-Prerequisites
Test-Configurations
}
"help" {
Show-Usage
}
default {
Write-ColoredOutput "Error: Unknown command '$Command'" "Red"
Write-Host ""
Show-Usage
exit 1
}
}