-
Notifications
You must be signed in to change notification settings - Fork 399
/
AzureResourceInventory.psm1
380 lines (327 loc) · 16.3 KB
/
AzureResourceInventory.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
<#
.SYNOPSIS
This script creates Excel file to Analyze Azure Resources inside a Tenant
.DESCRIPTION
Do you want to analyze your Azure Advisories in a table format? Document it in xlsx format.
.PARAMETER TenantID
Specify the tenant ID you want to create a Resource Inventory.
>>> IMPORTANT: YOU NEED TO USE THIS PARAMETER FOR TENANTS WITH MULTI-FACTOR AUTHENTICATION. <<<
.PARAMETER SubscriptionID
Use this parameter to collect a specific Subscription in a Tenant
.PARAMETER ManagementGroup
Use this parameter to collect a all Subscriptions in a Specific Management Group in a Tenant
.PARAMETER Lite
Use this parameter to use only the Import-Excel module and don't create the charts (using Excel's API)
.PARAMETER SecurityCenter
Use this parameter to collect Security Center Advisories
.PARAMETER SkipAdvisory
Use this parameter to skip the capture of Azure Advisories
.PARAMETER SkipPolicy
Use this parameter to skip the capture of Azure Policies
.PARAMETER QuotaUsage
Use this parameter to include Quota information
.PARAMETER IncludeTags
Use this parameter to include Tags of every Azure Resources
.PARAMETER Debug
Output detailed debug information.
.EXAMPLE
Default utilization. Read all tenants you have privileges, select a tenant in menu and collect from all subscriptions:
PS C:\> Invoke-ARI
Define the Tenant ID:
PS C:\> Invoke-ARI -TenantID <your-Tenant-Id>
Define the Tenant ID and for a specific Subscription:
PS C:\> Invoke-ARI -TenantID <your-Tenant-Id> -SubscriptionID <your-Subscription-Id>
.NOTES
AUTHORS: Claudio Merola and Renato Gregio | Azure Infrastucture/Automation/Devops/Governance
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
.LINK
Official Repository: https://github.com/microsoft/ARI
#>
Function Invoke-ARI {
param ([ValidateSet('AzureCloud', 'AzureUSGovernment','AzureChinaCloud')]
$AzureEnvironment = 'AzureCloud',
[ValidateSet(1, 2, 3)]
$Overview = 1,
$TenantID,
$AppId,
$Secret,
[String[]]$SubscriptionID,
$ManagementGroup,
[string[]]$ResourceGroup,
$TagKey,
$TagValue,
[switch]$SecurityCenter,
[switch]$Heavy,
[switch]$SkipAdvisory,
[switch]$SkipPolicy,
[switch]$SkipAPIs,
[switch]$IncludeTags,
[switch]$QuotaUsage,
[switch]$SkipDiagram,
[switch]$Automation,
$StorageAccount,
$StorageContainer,
[switch]$Lite,
[switch]$Debug,
[switch]$Help,
[switch]$DeviceLogin,
[switch]$DiagramFullEnvironment,
$ReportName = 'AzureResourceInventory',
$ReportDir)
if ($Debug.IsPresent)
{
$DebugPreference = 'Continue'
$ErrorActionPreference = 'Continue'
}
else
{
$ErrorActionPreference = "silentlycontinue"
}
Write-Debug ((get-date -Format 'yyyy-MM-dd_HH_mm_ss')+' - '+'Debbuging Mode: On. ErrorActionPreference was set to "Continue", every error will be presented.')
if ($IncludeTags.IsPresent) { $InTag = $true } else { $InTag = $false }
if ($Lite.IsPresent -or $Automation.IsPresent) { $RunLite = $true }else { $RunLite = $false }
if ($DiagramFullEnvironment.IsPresent) {$FullEnv = $true}else{$FullEnv = $false}
<######################################################### Help ######################################################################>
Function Get-UsageMode() {
Write-Host ""
Write-Host "Parameters"
Write-Host ""
Write-Host " -TenantID <ID> : Specifies the Tenant to be inventoried. "
Write-Host " -SubscriptionID <ID> : Specifies Subscription(s) to be inventoried. "
Write-Host " -ResourceGroup <NAME>: Specifies one (or more) unique Resource Group to be inventoried, This parameter requires the -SubscriptionID to work. "
Write-Host " -TagKey <NAME> : Specifies the tag key to be inventoried, This parameter requires the -SubscriptionID to work. "
Write-Host " -TagValue <NAME> : Specifies the tag value be inventoried, This parameter requires the -SubscriptionID to work. "
Write-Host " -SkipAdvisory : Do not collect Azure Advisory. "
Write-Host " -SkipPolicy : Do not collect Azure Policies. "
Write-Host " -SecurityCenter : Include Security Center Data. "
Write-Host " -IncludeTags : Include Resource Tags. "
Write-Host " -Online : Use Online Modules. "
Write-Host " -Debug : Run in a Debug mode. "
Write-Host " -AzureEnvironment : Change the Azure Cloud Environment. "
Write-Host " -ReportName : Change the Default Name of the report. "
Write-Host " -ReportDir : Change the Default Path of the report. "
Write-Host ""
Write-Host ""
Write-Host ""
Write-Host "Usage Mode and Examples: "
Write-Host "If you do not specify Resource Inventory will be performed on all subscriptions for the selected tenant. "
Write-Host "e.g. /> Invoke-ARI"
Write-Host ""
Write-Host "To perform the inventory in a specific Tenant and subscription use <-TenantID> and <-SubscriptionID> parameter "
Write-Host "e.g. /> Invoke-ARI -TenantID <Azure Tenant ID> -SubscriptionID <Subscription ID>"
Write-Host ""
Write-Host "Including Tags:"
Write-Host " By Default Azure Resource inventory do not include Resource Tags."
Write-Host " To include Tags at the inventory use <-IncludeTags> parameter. "
Write-Host "e.g. /> Invoke-ARI -TenantID <Azure Tenant ID> -IncludeTags"
Write-Host ""
Write-Host "Skipping Azure Advisor:"
Write-Host " By Default Azure Resource inventory collects Azure Advisor Data."
Write-Host " To ignore this use <-SkipAdvisory> parameter. "
Write-Host "e.g. /> Invoke-ARI -TenantID <Azure Tenant ID> -SubscriptionID <Subscription ID> -SkipAdvisory"
Write-Host ""
Write-Host "Using the latest modules :"
Write-Host " You can use the latest modules. For this use <-Online> parameter."
Write-Host " It's a pre-requisite to have internet access for ARI GitHub repo"
Write-Host "e.g. /> Invoke-ARI -TenantID <Azure Tenant ID> -Online"
Write-Host ""
Write-Host "Running in Debug Mode :"
Write-Host " To run in a Debug Mode use <-Debug> parameter."
Write-Host ".e.g. /> Invoke-ARI -TenantID <Azure Tenant ID> -Debug"
Write-Host ""
}
$TotalRunTime = Measure-Command -Expression {
if ($Help.IsPresent) {
Get-UsageMode
Break
}
else {
if ($PlatOS -ne 'Azure CloudShell' -and !$Automation.IsPresent)
{
Write-Host ('Checking for Powershell Module Updates..')
Update-Module -Name AzureResourceInventory -AcceptLicense
}
$PlatOS = Test-ARIPS -Debug $Debug
if ($PlatOS -ne 'Azure CloudShell' -and !$Automation.IsPresent)
{
$TenantID = Connect-ARILoginSession -AzureEnvironment $AzureEnvironment -TenantID $TenantID -SubscriptionID $SubscriptionID -DeviceLogin $DeviceLogin -AppId $AppId -Secret $Secret -Debug $Debug
}
elseif ($Automation.IsPresent)
{
try {
$AzureConnection = (Connect-AzAccount -Identity).context
Set-AzContext -SubscriptionName $AzureConnection.Subscription -DefaultProfile $AzureConnection
}
catch {
Write-Output "Failed to set Automation Account requirements. Aborting."
exit
}
}
if ($StorageAccount)
{
$StorageContext = New-AzStorageContext -StorageAccountName $StorageAccount -UseConnectedAccount
}
$Subscriptions = Get-ARISubscriptions -TenantID $TenantID -SubscriptionID $SubscriptionID
if ($PlatOS -eq 'Azure CloudShell')
{
$DefaultPath = if($ReportDir) {$ReportDir} else {"$HOME/AzureResourceInventory/"}
$DiagramCache = if($ReportDir) {$ReportDir} else {"$HOME/AzureResourceInventory/DiagramCache/"}
if($ReportDir)
{
try
{
Resolve-Path $ReportDir -ErrorAction STOP
if ($ReportDir -notmatch '/$')
{
$ReportDir = $ReportDir + '/'
}
}
catch
{
Write-Output "ReportDir Parameter must contain the full path."
Exit
}
}
}
elseif ($PlatOS -eq 'PowerShell Unix')
{
$DefaultPath = if($ReportDir) {$ReportDir} else {"$HOME/AzureResourceInventory/"}
$DiagramCache = if($ReportDir) {$ReportDir} else {"$HOME/AzureResourceInventory/DiagramCache/"}
if($ReportDir)
{
try
{
Resolve-Path $ReportDir -ErrorAction STOP
if ($ReportDir -notmatch '/$')
{
$ReportDir = $ReportDir + '/'
}
}
catch
{
Write-Output "ReportDir Parameter must contain the full path."
Exit
}
}
}
elseif ($PlatOS -eq 'PowerShell Desktop')
{
$DefaultPath = if($ReportDir) {$ReportDir} else {"C:\AzureResourceInventory\"}
$DiagramCache = if($ReportDir) {($ReportDir+'DiagramCache\')} else {"C:\AzureResourceInventory\DiagramCache\"}
if($ReportDir)
{
try
{
Resolve-Path $ReportDir -ErrorAction STOP
if ($ReportDir -notlike '*\')
{
$ReportDir = $ReportDir + '\'
}
}
catch
{
Write-Output "ReportDir Parameter must contain the full path."
Exit
}
}
}
Write-Debug ((get-date -Format 'yyyy-MM-dd_HH_mm_ss')+' - '+'Checking report folder: ' + $DefaultPath )
if ((Test-Path -Path $DefaultPath -PathType Container) -eq $false) {
New-Item -Type Directory -Force -Path $DefaultPath | Out-Null
}
if ((Test-Path -Path $DiagramCache -PathType Container) -eq $false) {
New-Item -Type Directory -Force -Path $DiagramCache | Out-Null
}
Write-Host "Starting Resource Extraction.."
$ExtractionData = Start-AzureResourceDataPull -ManagementGroup $ManagementGroup -Subscriptions $Subscriptions -SubscriptionID $SubscriptionID -ResourceGroup $ResourceGroup -SecurityCenter $SecurityCenter -SkipAdvisory $SkipAdvisory -IncludeTags $IncludeTags -QuotaUsage $QuotaUsage -TagKey $TagKey -TagValue $TagValue -Debug $Debug
$ExtractionRuntime = $ExtractionData.ExtractionRunTime
$Resources = $ExtractionData.Resources
$ResourceContainers = $ExtractionData.ResourceContainers
$Advisories = $ExtractionData.Advisories
$Security = $ExtractionData.Security
$Retirements = $ExtractionData.Retirements
Clear-Variable -Name ExtractionData
$ResourcesCount = [string]$Resources.Count
$advco = [string]$Advisories.Count
$Secadvco = [string]$Security.Count
if(!$SkipAPIs.IsPresent)
{
$APIResults = Get-ARIAPIResources -Subscriptions $Subscriptions -AzureEnvironment $AzureEnvironment -SkipPolicy $SkipPolicy -Debug $Debug
$Resources += $APIResults.ResourceHealth
$Resources += $APIResults.SupportTickets
$Resources += $APIResults.ManagedIdentities
$Resources += $APIResults.AdvisorScore
$Resources += $APIResults.ReservationRecomen
$PolicyAssign = $APIResults.PolicyAssign
$PolicyDef = $APIResults.PolicyDef
$PolicySetDef = $APIResults.PolicySetDef
}
$polco = [string]$PolicyAssign.policyAssignments.Count
#### Creating Excel file variable:
if ($StorageAccount)
{
$Date = get-date -Format "yyyy-MM-dd_HH_mm"
if($ReportName -eq 'AzureResourceInventory')
{
$File = ("ARI_Automation_Report_"+$Date+".xlsx")
}
else
{
$File = ($ReportName+'_'+$Date+'.xlsx')
}
}
else
{
$File = ($DefaultPath + $ReportName + "_Report_" + (get-date -Format "yyyy-MM-dd_HH_mm") + ".xlsx")
#$Global:DFile = ($DefaultPath + $Global:ReportName + "_Diagram_" + (get-date -Format "yyyy-MM-dd_HH_mm") + ".vsdx")
$DDFile = ($DefaultPath + $ReportName + "_Diagram_" + (get-date -Format "yyyy-MM-dd_HH_mm") + ".xml")
}
Write-Debug ((get-date -Format 'yyyy-MM-dd_HH_mm_ss')+' - '+'Excel file: ' + $File)
Write-Debug ((get-date -Format 'yyyy-MM-dd_HH_mm_ss')+' - '+'Starting Default Jobs.')
Start-ARIExtraJobs -SkipDiagram $SkipDiagram -SkipAdvisory $SkipAdvisory -SkipPolicy $SkipPolicy -SecurityCenter $Security -Subscriptions $Subscriptions -Resources $Resources -Advisories $Advisories -DDFile $DDFile -DiagramCache $DiagramCache -FullEnv $FullEnv -ResourceContainers $ResourceContainers -Security $Security -PolicyAssign $PolicyAssign -PolicySetDef $PolicySetDef -PolicyDef $PolicyDef -Automation $Automation -Debug $Debug
Write-Debug ((get-date -Format 'yyyy-MM-dd_HH_mm_ss')+' - '+'Starting Resources Report Function.')
Build-AzureResourceReport -Subscriptions $Subscriptions -DefaultPath $DefaultPath -ExtractionRunTime $ExtractionRuntime -Resources $Resources -Retirements $Retirements -SecurityCenter $SecurityCenter -File $File -DDFile $DDFile -Heavy $Heavy -SkipDiagram $SkipDiagram -RunLite $RunLite -PlatOS $PlatOS -InTag $InTag -SkipPolicy $SkipPolicy -SkipAdvisory $SkipAdvisory -Automation $Automation -SkipAPIs $SkipAPIs, -Overview $Overview -Debug $Debug
if ($StorageAccount)
{
Set-AzStorageBlobContent -File $File -Container $StorageContainer -Context $StorageContext | Out-Null
}
}
}
$Measure = $TotalRunTime.Totalminutes.ToString('#######.##')
Write-Host ('Report Complete. Total Runtime was: ') -NoNewline
Write-Host $Measure -NoNewline -ForegroundColor Cyan
Write-Host (' Minutes')
Write-Host ('Total Resources: ') -NoNewline
Write-Host $ResourcesCount -ForegroundColor Cyan
if (!$SkipAdvisory.IsPresent)
{
Write-Host ('Total Advisories: ') -NoNewline
write-host $advco -ForegroundColor Cyan
}
if (!$SkipPolicy.IsPresent -and !$SkipAPIs.IsPresent)
{
Write-Host ('Total Policies: ') -NoNewline
write-host $polco -ForegroundColor Cyan
}
if ($SecurityCenter.IsPresent)
{
Write-Host ('Total Security Advisories: ' + $Secadvco)
}
Write-Host ''
Write-Host ('Excel file saved at: ') -NoNewline
write-host $File -ForegroundColor Cyan
Write-Host ''
if(!$SkipDiagram.IsPresent)
{
Write-Host ('Draw.io Diagram file saved at: ') -NoNewline
write-host $DDFile -ForegroundColor Cyan
Write-Host ''
}
}