GuestConfigurationTroubleshooter.psm1

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
<#
.SYNOPSIS

Gets the properties of the GuestConfig Extension on a specified VM
    
.DESCRIPTION

This script gets and prints the properties of the GuestConfig Extension on a specified windows
or linux vm.

.PARAMETER ResourceGroupName
The Resource Group the VM is in

.PARAMETER VMName
The VM to get the GuestConfig Extension from

.EXAMPLE

PS> Get-VmGuestConfigExtensionProperties -ResourceGroupName "MyResourceGroup" -VMName "MyVM"
Checking AzurePolicyforWindows...
The extension AzurePolicyforWindows was deployed successfully
Provisioning succeeded
#>

function Get-VmGuestConfigExtensionProperties
{
    [CmdletBinding()]
    param(
        [parameter(Mandatory=$true)][String]$ResourceGroupName,
        [parameter(Mandatory=$true)][String]$VMName
    )

    #Get the VM to check whether it is linux or windows
    $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -ErrorAction SilentlyContinue

    if(-not($vm))
    {
        throw "The given VM could not be found in that Resource Group"
    }

    #If it is a windows machine
    if($vm.OSProfile.WindowsConfiguration)
    {
        #Get the extension
        $ext = Get-AzVMExtension -ResourceGroupName $ResourceGroupName -VMName $VMName -Name "AzurePolicyforWindows" -ErrorAction SilentlyContinue

    }
    #Otherwise if it is a linux machine
    elseif($vm.OSProfile.LinuxConfiguration)
    {
        #Get the extension
        $ext = Get-AzVMExtension -ResourceGroupName $ResourceGroupName -VMName $VMName -Name "AzurePolicyforLinux" -ErrorAction SilentlyContinue
    }
    else
    {
        Write-Warning "That VM's OS is not supported by Guest Configuration"
        return $false
    }

    Write-Host ("Checking for extension `"" + $ext.Name + "`"...")

    #If the extension is deployed
    if($ext)
    {
        Write-Host ("The extension `"" + $ext.Name + "`" was deployed successfully")

        #Check the provisioning state
        if($ext.ProvisioningState -eq "Succeeded")
        {
            Write-Host "Provisioning succeeded"
        }
        else
        {
            $warningString = "Provisioning did not succeed, provisioning state is: " + $ext.ProvisioningState
            Write-Warning $warningString

            if($ext.ProvisioningState -eq "Not Started" -or $ext.ProvisioningState -eq "In Progress" -or $ext.ProvisioningState -eq "Updating")
            {
                Write-Warning "Deployment for this extension is still in progress, wait for a couple minutes"
            }
            elseif($ext.ProvisioningState -eq "Failed")
            {
                Write-Warning "Provisioning for this extension has failed, try running a remediation task"
            }

            return $false
        }


    }
    else
    {
        $warningString = "The extension `"" + $ext.Name + "was not deployed successfully or was not deployed at all"
        Write-Warning $warningString
        Write-Warning "Check if any DeployIfNotExists Policies are assigned to this scope"
        return $false
    }

    return $true

}

<#
.SYNOPSIS

Gets the MSI Status of a VM
    
.DESCRIPTION

This script gets and prints the MSI Status of a specified VM in a specified Resource Group

.PARAMETER ResourceGroupName
The Resource Group the VM is in

.PARAMETER VMName
The VM to check the MSI status of

.EXAMPLE

PS> Get-VmMSIEnabled -ResourceGroupName "MyResourceGroup" -VMName "MyVM"
MSI is enabled on this VM
#>

function Get-VmMSIEnabled
{
    [CmdletBinding()]
    param(
        [parameter(Mandatory=$true)][String]$ResourceGroupName,
        [parameter(Mandatory=$true)][String]$VMName
    )

    #Get the VM to check MSI status
    $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -ErrorAction SilentlyContinue

    #Check if the VM was found
    if(-not($vm))
    {
        throw "The given VM could not be found in that Resource Group"
    }

    if($vm.Identity.Type -eq "SystemAssigned")
    {
        Write-Host "MSI is enabled on this VM"
        return $true
    }
    else
    {
        Write-Warning "MSI is not enabled on this VM"
        Write-Warning "Enabling System Managed Identity is needed for Guest Configuration Policy scenarios"
        return $false
    }


}


<#
.SYNOPSIS

Prints warnings and errors for any Guest Configuration policies that were assigned incorrectly
    
.DESCRIPTION

This script checks all Guest Configuration policies in a given resource group
and prints warnings and errors if any of them were assigned incorrectly

.PARAMETER ResourceGroupName
The Resource Group to check policies in

.PARAMETER Subscription
Switch parameter that allows you to check the policy assignments in the current subscription
(Context based)

.EXAMPLE

PS> Get-GuestConfigPolicyErrors -ResourceGroupName "MyResourceGroup"

.EXAMPLE

PS> Get-GuestConfigPolicyErrors -Subscription
#>

function Get-GuestConfigPolicyErrors
{
    [CmdletBinding()]
    param(
        [parameter(ParameterSetName = "ResourceGroup", Mandatory=$true)][String]$ResourceGroupName,
        [parameter(ParameterSetName = "Subscription", Mandatory=$true)][Switch]$CurrentSubscription
    )

    if(-not($CurrentSubscription))
    {
        $rg = Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue

        if(-not($rg))
        {
            throw "The given Resource Group could not be found"
        }

        #Get all policies in the resource group
        $assignments = Get-AzPolicyAssignment -Scope $rg.ResourceId
    }
    else
    {
        $assignments = Get-AzPolicyAssignment
    }

    #for tracking status
    $success = $true
    $totalErrors = 0
    $guestConfigCount = 0

    #If there are any policies
    if($assignments.Count -gt 0)
    {
        
        #Loop through each policy
        foreach($assignment in $assignments)
        {
            #Get the policies definition
            $id = $assignment.Properties.policyDefinitionId

            $verboseMessage = "Checking policy assignment `"" + $assignment.Properties.displayName + "`""

            Write-Verbose $verboseMessage

            #Check if there is an id
            if($id)
            {
                
                $def = Get-AzPolicyDefinition -Id $id

                #Check if it is a Guest Configuration Policy
                if($def.Properties.metadata.category -eq "Guest Configuration")
                {

                    Write-Verbose "Found Guest Configuration policy"
                    $guestConfigCount += 1

                    #Check if the policy is in an initiative
                    if($def.Properties.policyDefinitions)
                    {
                        Write-Verbose "Policy was in an initiative"
                    }
                    else
                    {
                        #If it's not in an initiative, print information
                        $warningString = "The policy `"" + $def.Properties.displayName + "`" is not in an initiative"
                        Write-Warning $warningString
                        
                        $success = $false

                        $totalErrors += 1

                        if($def.Properties.policyRule.then.effect -eq "deployIfNotExists")
                        {
                            Write-Warning "It is recommended that the DeployIfNotExists Policy be in an initiative with its corresponding Audit Policy"
                            Write-Warning "The corresponding Audit Policy is missing" 
                        }
                        elseif($def.Properties.policyRule.then.effect -eq "audit")
                        {
                             
                            Write-Warning "It is recommended that the Audit Policy be in an initiative with its corresponding DeployIfNotExists Policy"
                            Write-Warning "The corresponding DeployIfNotExists Policy is missing"
                        }

                        #to separate policies
                        Write-Host ""
                    }
                }
            }
        }
    }

    #Write information about the total amount of errors
    if($guestConfigCount -eq 0)
    {
        Write-Host "There are no Guest Configuration Policies assigned to this scope"
    }
    elseif($totalErrors -gt 0)
    {
        Write-Host "Total Guest Config Policy errors:" $totalErrors -ForegroundColor Red
    }
    else
    {
        Write-Host "Total Guest Config Policy errors:" $totalErrors -ForegroundColor Green
    }

    return $success

}

<#
.SYNOPSIS

Tests VM/ResourceGroup/Subscription for things related to Guest Configuration
    
.DESCRIPTION

This script runs the cmdlets: Get-VmGuestConfigExtensionProperties, Get-VmMSIEnabled, Get-GuestConfigPolicyErrors
and prints status information based on results

.PARAMETER ResourceGroupName
The Resource Group to run tests in

.PARAMETER VMName
The VM to run tests on

.PARAMETER CheckSubscriptionPolicies
Switch parameter that allows you to check policy assignments on a subscription level
(based on current context)

.EXAMPLE

PS> Test-GuestConfigurationPolicies -ResourceGroupName "MyResourceGroup" -VMName "MyVM"

.EXAMPLE

PS> Test-GuestConfigurationPolicies -ResourceGroupName "MyResourceGroup" -VMName "MyVM" -CheckSubscriptionPolicies
#>

function Test-GuestConfigurationPolicies
{
    [CmdletBinding()]
    param(
        [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][String]$ResourceGroupName,
        [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][String]$VMName,
        [parameter(Mandatory=$false)][switch]$CheckSubscriptionPolicies
    )

    #Check if the resource group exists (MSIEnabled and ExtensionProperties will check the VM)
    if(-not(Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue))
    {
        throw "The given Resource Group could not be found"
    }


    Write-Host ""
    
    #Check MSI on the given VM
    Write-Host "Checking if MSI is enabled on this VM"
    $status1 = Get-VmMSIEnabled -ResourceGroupName $ResourceGroupName -VMName $VMName
    if($status1 -eq $true)
    {
        Write-Host "MSI Enabled status: Success" -ForegroundColor Green
    }
    else
    {
        Write-Host "MSI Enabled status: Failed" -ForegroundColor Red
    }
    Write-Host ""


    #Check Guest Config Extension on the given VM
    Write-Host "Checking properties of Guest Configuration Extension on this VM"
    $status2 = Get-VmGuestConfigExtensionProperties -ResourceGroupName $ResourceGroupName -VMName $VMName
    if($status2 -eq $true)
    {
        Write-Host "Guest Config Extension Status: Success" -ForegroundColor Green
    }
    else
    {
        Write-Host "Guest Config Extension Status: Failed" -ForegroundColor Red
    }
    Write-Host ""


    #Check assignment errors
    Write-Host "Checking if all Guest Config policies were assigned correctly in specified scope"
    if(-not($CheckSubscriptionPolicies))
    {
        $status3 = Get-GuestConfigPolicyErrors -ResourceGroupName $ResourceGroupName
    }
    else
    {
        $status3 = Get-GuestConfigPolicyErrors -CurrentSubscription
    }

    if($status3 -eq $true)
    {
        Write-Host "Guest Config Policy Assignments: Success" -ForegroundColor Green
    }
    else
    {
        Write-Host "Guest Config Policy Assignments: Failed" -ForegroundColor Red
    }
    Write-Host ""

    #Overall status is only success if all 3 checks succeeded
    if($status1 -and $status2 -and $status3)
    {
        Write-Host "Overall status: Success" -ForegroundColor Green
    }
    else
    {
        #Print Verbose information
        if(-not($status1))
        {
            Write-Verbose "MSI: Failed"
        }
        if(-not($status2))
        {
            Write-Verbose "Guest Config Extension: Failed"
        }
        if(-not($status3))
        {
            Write-Verbose "Guest Config Policy Assignments: Failed"
        }
        Write-Host "Overall status: Failed" -ForegroundColor Red
    }
}

Export-ModuleMember -Function Get-VmGuestConfigExtensionProperties, Get-VmMSIEnabled, Get-GuestConfigPolicyErrors, Test-GuestConfigurationPolicies