-
Notifications
You must be signed in to change notification settings - Fork 112
/
Suppress-Recommendation.ps1
263 lines (231 loc) · 8.75 KB
/
Suppress-Recommendation.ps1
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
param(
[Parameter(Mandatory = $true)]
[String] $RecommendationId
)
$ErrorActionPreference = "Stop"
function Test-IsGuid
{
[OutputType([bool])]
param
(
[Parameter(Mandatory = $true)]
[string]$ObjectGuid
)
# Define verification regex
[regex]$guidRegex = '(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$'
# Check guid against regex
return $ObjectGuid -match $guidRegex
}
if (-not(Test-IsGuid -ObjectGuid $RecommendationId))
{
Write-Host "The provided recommendation Id is invalid. Must be a valid GUID." -ForegroundColor Red
Exit
}
$databaseConnectionSettingsPath = ".\database-connection-settings.json"
$dbConnectionSettings = @{}
if (Test-Path -Path $databaseConnectionSettingsPath)
{
$dbSettings = Get-Content -Path $databaseConnectionSettingsPath | ConvertFrom-Json
Write-Host $dbSettings -ForegroundColor Green
$dbSettingsReuse = Read-Host "Found existing database connection settings. Do you want to reuse them (Y/N)?"
if ("Y", "y" -contains $dbSettingsReuse)
{
foreach ($property in $dbSettings.PSObject.Properties)
{
$dbConnectionSettings[$property.Name] = $property.Value
}
}
}
if (-not($dbConnectionSettings["DatabaseServer"]))
{
$databaseServer = Read-Host "Please, enter the AOE Azure SQL server hostname (e.g., xpto.database.windows.net)"
$dbConnectionSettings["DatabaseServer"] = $databaseServer
}
else
{
$databaseServer = $dbConnectionSettings["DatabaseServer"]
}
if (-not($dbConnectionSettings["DatabaseName"]))
{
$databaseName = Read-Host "Please, enter the AOE Azure SQL Database name (e.g., azureoptimization)"
$dbConnectionSettings["DatabaseName"] = $databaseName
}
else
{
$databaseName = $dbConnectionSettings["DatabaseName"]
}
if (-not($dbConnectionSettings["DatabaseUser"]))
{
$databaseUser = Read-Host "Please, enter the AOE database user name"
$dbConnectionSettings["DatabaseUser"] = $databaseUser
}
else
{
$databaseUser = $dbConnectionSettings["DatabaseUser"]
}
$sqlPass = Read-Host "Please, input the password for the $databaseUser SQL user" -AsSecureString
$sqlPassPlain = (New-Object PSCredential "user", $sqlPass).GetNetworkCredential().Password
$sqlPassPlain = $sqlPassPlain.Replace("'", "''")
$SqlTimeout = 120
$recommendationsTable = "Recommendations"
$suppressionsTable = "Filters"
Write-Host "Opening connection to the database..." -ForegroundColor Green
$tries = 0
$connectionSuccess = $false
do {
$tries++
try {
$Conn = New-Object System.Data.SqlClient.SqlConnection("Server=tcp:$databaseServer,1433;Database=$databaseName;User ID=$databaseUser;Password='$sqlPassPlain';Trusted_Connection=False;Encrypt=True;Connection Timeout=$SqlTimeout;")
$Conn.Open()
$Cmd=new-object system.Data.SqlClient.SqlCommand
$Cmd.Connection = $Conn
$Cmd.CommandTimeout = $SqlTimeout
$Cmd.CommandText = "SELECT * FROM [dbo].[$recommendationsTable] WHERE RecommendationId = '$RecommendationId'"
$sqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$sqlAdapter.SelectCommand = $Cmd
$controlRows = New-Object System.Data.DataTable
$sqlAdapter.Fill($controlRows) | Out-Null
$connectionSuccess = $true
}
catch {
Write-Host "Failed to contact SQL at try $tries." -ForegroundColor Yellow
Write-Host $Error[0] -ForegroundColor Yellow
Write-Output "Waiting $($tries * 20) seconds..."
Start-Sleep -Seconds ($tries * 20)
}
} while (-not($connectionSuccess) -and $tries -lt 3)
if (-not($connectionSuccess))
{
throw "Could not establish connection to SQL."
}
$Conn.Close()
$Conn.Dispose()
if (-not($controlRows.RecommendationId))
{
Write-Host "The provided recommendation Id was not found. Please, try again with a valid GUID." -ForegroundColor Red
Exit
}
Write-Host "You are suppressing the recommendation with the below details" -ForegroundColor Green
Write-Host "Recommendation: $($controlRows.RecommendationDescription)" -ForegroundColor Blue
Write-Host "Recommendation sub-type id: $($controlRows.RecommendationSubTypeId)" -ForegroundColor Blue
Write-Host "Category: $($controlRows.Category)" -ForegroundColor Blue
Write-Host "Instance Name: $($controlRows.InstanceName)" -ForegroundColor Blue
Write-Host "Resource Group: $($controlRows.ResourceGroup)" -ForegroundColor Blue
Write-Host "Subscription Id: $($controlRows.SubscriptionGuid)" -ForegroundColor Blue
Write-Host "Please, choose the suppression type" -ForegroundColor Green
Write-Host "[E]xclude - this recommendation type will be completely excluded from the engine and will no longer be generated for any resource" -ForegroundColor Green
Write-Host "[D]ismiss - this recommendation will be dismissed for the scope to be chosen next (instance, resource group or subscription)" -ForegroundColor Green
Write-Host "[S]nooze - this recommendation will be postponed for the duration (in days) and scope to be chosen next (instance, resource group or subscription)" -ForegroundColor Green
Write-Host "[C]ancel - no action will be taken" -ForegroundColor Green
$suppOption = Read-Host "Enter your choice (E, D, S or C)"
if ("E", "e" -contains $suppOption)
{
$suppressionType = "Exclude"
}
elseif ("D", "d" -contains $suppOption)
{
$suppressionType = "Dismiss"
}
elseif ("S", "s" -contains $suppOption)
{
$suppressionType = "Snooze"
}
else
{
Write-Host "Cancelling.. No action will be taken." -ForegroundColor Green
Exit
}
if ($suppressionType -in ("Dismiss", "Snooze"))
{
Write-Host "Please, choose the scope for the suppression" -ForegroundColor Green
Write-Host "[S]ubscription ($($controlRows.SubscriptionGuid))" -ForegroundColor Green
Write-Host "[R]esource Group ($($controlRows.ResourceGroup))" -ForegroundColor Green
Write-Host "[I]nstance ($($controlRows.InstanceName))" -ForegroundColor Green
$scopeOption = Read-Host "Enter your choice (S, R, or I)"
if ("S", "s" -contains $scopeOption)
{
$scope = $controlRows.SubscriptionGuid
}
elseif ("R", "r" -contains $scopeOption)
{
$scope = $controlRows.ResourceGroup
}
elseif ("I", "i" -contains $scopeOption)
{
$scope = $controlRows.InstanceId
}
else
{
Write-Host "Wrong input. No action will be taken." -ForegroundColor Red
Exit
}
}
$snoozeDays = 0
if ($suppressionType -eq "Snooze")
{
Write-Host "Please, enter the number of days the recommendation will be snoozed" -ForegroundColor Green
$snoozeDays = Read-Host "Number of days (min. 14)"
if (-not($snoozeDays -ge 14))
{
Write-Host "Wrong snooze days. No action will be taken." -ForegroundColor Red
Exit
}
}
$author = Read-Host "Please enter your name"
$notes = Read-Host "Please enter a reason for this suppression"
Write-Host "You are about to suppress this recommendation" -ForegroundColor Yellow
Write-Host "Recommendation: $($controlRows.RecommendationDescription)" -ForegroundColor Blue
Write-Host "Suppression type: $suppressionType" -ForegroundColor Blue
if ($suppressionType -in ("Dismiss", "Snooze"))
{
Write-Host "Scope: $scope" -ForegroundColor Blue
}
if ($suppressionType -eq "Snooze")
{
Write-Host "Snooze days: $snoozeDays" -ForegroundColor Blue
}
Write-Host "Author: $author" -ForegroundColor Blue
Write-Host "Reason: $notes" -ForegroundColor Blue
$continueInput = Read-Host "Do you want to continue (Y/N)?"
if ("Y", "y" -contains $continueInput)
{
if ($scope)
{
$scope = "'$scope'"
}
else
{
$scope = "NULL"
}
if ($snoozeDays -ge 14)
{
$now = (Get-Date).ToUniversalTime()
$endDate = "'$($now.Add($snoozeDays).ToString("yyyy-MM-ddTHH:mm:00Z"))'"
}
else {
$endDate = "NULL"
}
$sqlStatement = "INSERT INTO [$suppressionsTable] VALUES (NEWID(), '$($controlRows.RecommendationSubTypeId)', '$suppressionType', $scope, GETDATE(), $endDate, '$author', '$notes', 1)"
$Conn2 = New-Object System.Data.SqlClient.SqlConnection("Server=tcp:$databaseServer,1433;Database=$databaseName;User ID=$databaseUser;Password='$sqlPassPlain';Trusted_Connection=False;Encrypt=True;Connection Timeout=$SqlTimeout;")
$Conn2.Open()
$Cmd=new-object system.Data.SqlClient.SqlCommand
$Cmd.Connection = $Conn2
$Cmd.CommandText = $sqlStatement
$Cmd.CommandTimeout=120
try
{
$Cmd.ExecuteReader()
}
catch
{
Write-Output "Failed statement: $sqlStatement"
throw
}
$Conn2.Close()
Write-Host "Suppression sucessfully added." -ForegroundColor Green
}
else
{
Write-Host "No action was taken." -ForegroundColor Green
}
$dbConnectionSettings | ConvertTo-Json | Out-File -FilePath $databaseConnectionSettingsPath -Force