EsxiInventoryTools.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 |
$CachedTokenPath = "$env:localappdata\esxiinventorytools_cached_token.dat" function Publish-EsxiInventory { <# .SYNOPSIS Command to Publish ESXiInventory to a URI location, such as Eagles Nest. .DESCRIPTION Publish-ESXiInventory does the following in the following order: -Gets Token from locally encrypted dat file. This encrypted dat file is set by Initialize-ESXiInventoryTools. -Accesses the secret from Vault using the Token -Connects to VI server and gathers Host inventory -Submits the Host inventory to the PublishURI location .PARAMETER VIServer The VIServer to connect to gather inventory. .PARAMETER PublishURI The URI to publish to. .PARAMETER Vault_Full_Address The full hashicorp vault address from where to obtain the vault_key from .PARAMETER Vault_Key The vault key used to obtain the value .EXAMPLE Publish-ESXiInventory This example publishes the ESXi Inventory. #> [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [string]$VIServer, [Parameter(Mandatory=$true)] [string]$PublishURI, [Parameter(Mandatory=$true)] [string]$Vault_Full_Address, [Parameter(Mandatory=$true)] [string]$Vault_Key ) $InformationPreference='Continue' #Begin Try { $ErrorActionPreference = 'Stop' $GetValueParams = @{ Vault_Full_Address = $Vault_Full_Address Vault_SavedTokenPath = $CachedTokenPath Vault_Key = $Vault_Key } $PUBLISH_API_KEY = Get-VaultValue @GetValueParams Write-Information "Retrieved Api Key from Vault" #Connect to VIServer $ConnectParams = @{ Server = $VIServer Protocol = 'https' } Connect-VIServer @ConnectParams | Out-Null Write-Information "Connected to VIServer $VIServer" #Get Hosts from VIServer - Specify Get-VMHost from Vmware module [ValidateNotNullOrEmpty()]$ESXiHosts = Vmware.VimAutomation.Core\Get-VMHost $ESXiHostCount = ($ESXiHosts | Measure-Object).Count Write-Information "Retrieved $ESXiHostCount Hosts from VIServer" #Custom Inventory Object class ESXiItem { #Instance Properties [string]$Serial_Number [string]$Asset_Name [string]$Manufacturer [string]$Model [string]$Operating_System [string]$OS_Version [string]$IP_Address [string]$MAC_Address [string]$UpdateTime #Constructor - required properties ESXiItem ($VMHostImpl) { $this.Asset_Name=$VMHostImpl.Name $this.Serial_Number=(Vmware.VimAutomation.Core\Get-VMHostHardware -VMHost $VMHostImpl.Name).SerialNumber $this.Manufacturer=$VMHostImpl.Manufacturer $this.Model=$VMHostImpl.Model $this.Operating_System=(Vmware.VimAutomation.Core\Get-View -ViewType HostSystem -Filter @{"Name" = $VMHostImpl.Name}).Config.Product.Name $this.OS_Version=(Vmware.VimAutomation.Core\Get-View -ViewType HostSystem -Filter @{"Name" = $VMHostImpl.Name}).Config.Product.Version $this.IP_Address=(Vmware.VimAutomation.Core\Get-VMHostNetworkAdapter -VMHost $VMHostImpl.Name | Where-Object {$_.Name -eq 'vmk0'}).IP $this.MAC_Address=(Vmware.VimAutomation.Core\Get-VMHostNetworkAdapter -VMHost $VMHostImpl.Name | Where-Object {$_.Name -eq 'vmk0'}).Mac $this.UpdateTime=(Get-Date).Tostring() } } } Catch { $ErrorActionPreference = 'Continue' #so error continues down pipeline for logging $PSCmdlet.WriteError($_) Break } #Process $Inventory=@() ForEach ($ESXiHost in $ESXiHosts) { Try { $ErrorActionPreference='Stop' if (Test-Connection -ComputerName $ESXiHost.Name -Quiet -Count 1) { $InventoryItem = [ESXiItem]::New($ESXiHost) $Inventory += $InventoryItem } } Catch { $ErrorActionPreference = 'Continue' #so error continues down pipeline for logging $PSCmdlet.WriteError($_) Continue #continue to next esxi host } } #End Try { $ErrorActionPreference = 'Stop' #Inventory Count $InventoryCount = ($Inventory | Measure-Object).Count Write-Information "Inventory created for $InventoryCount of $ESXiHostCount hosts" #Submit the Inventory as JSON $JSONInventory = $Inventory | ConvertTo-Json $InvokeWebRequestParams = @{ URI = $PublishURI Method = 'POST' Headers = @{"api_key" = "$PUBLISH_API_KEY";'Content-Type'='json'} Body = $JSONInventory } #Output Message $Response = Invoke-WebRequest @InvokeWebRequestParams if ($Response.StatusCode -eq '200') { Write-Information 'Content successfully submitted' } } Catch { $ErrorActionPreference = 'Continue' #so error continues down pipeline for logging $PSCmdlet.WriteError($_) } Finally { Try { $ErrorActionPreference = 'Stop' Disconnect-VIServer -Confirm:$false Write-Information "Disconnected from VIServer" } Catch { $ErrorActionPreference = 'Continue' #so error continues down pipeline for logging $PSCmdlet.WriteError($_) } } } function Register-EsxiInventoryTask { <# .SYNOPSIS Command to register EsxiInventoryTools task .DESCRIPTION sets the cached token, event log, and scheduled task .PARAMETER LdapCredential The ldap credential used to obtain a token .PARAMETER Vault_Rolename The approle which has access to the secret in vault .PARAMETER Logname The event log to use for event logging .PARAMETER Source The event log source to use for event logging .PARAMETER DailyRunTime The time to schedule the daily task for. (e.g. '9pm', '9:30am') .PARAMETER VIServer The vcenter server to connect to .PARAMETER PublishURI The server to publish the inventory to .PARAMETER Vault_Full_Address The full hashicorp vault address from where to obtain the vault_key from .PARAMETER Vault_Key The vault key used to obtain the value #> [CmdletBinding()] Param( #Token params [Parameter(Mandatory=$true)] [System.Management.Automation.PSCredential]$LdapCredential, [Parameter(Mandatory=$true)] [string]$Vault_Rolename, #ScheduledTask and EventLog params [Parameter(Mandatory=$true)] [string]$LogName, [Parameter(Mandatory=$true)] [string]$Source, #ScheduledTask params [Parameter(Mandatory=$true)] [string]$DailyRunTime, [Parameter(Mandatory=$true)] [string]$VIServer, [Parameter(Mandatory=$true)] [string]$PublishURI, [Parameter(Mandatory=$true)] [ValidateScript({$_ -match 'https'})] [string]$Vault_Full_Address, [Parameter(Mandatory=$true)] [string]$Vault_Key ) $ErrorActionPreference = 'Stop' $Verbose = $VerbosePreference -ne 'SilentlyContinue' #Token $Vault_Full_Address -match 'https://[\w\.]*' | Out-Null $Vault_Address = $Matches[0] $PublishTokenParams = @{ LdapCredential = $LdapCredential Vault_Address = $Vault_Address Vault_RoleName = $Vault_RoleName Verbose = $Verbose } Install-EsxiInventoryToken @PublishTokenParams #Install Module for writing to eventlog, then install event log Try { Install-Module -Name 'EventLogTools' -RequiredVersion '2.3' -Repository 'PSGallery' -Force New-EventLog -LogName $LogName -Source $Source -ErrorAction 'Stop' -ErrorVariable 'NewEventLog' -Verbose:$Verbose } Catch { if ($NewEventLog -notmatch 'already registered') { $PSCmdlet.WriteError($_) } } #Commands for Scheduled Job $Name = 'Publish_EsxiInventory' $RunCommand="Publish-EsxiInventory -VIServer $VIServer -PublishURI $PublishURI -Vault_Full_Address $Vault_Full_Address -Vault_Key $Vault_Key" $LogCommand=" *>&1 | Write-StreamToEventLog -AutoID 'Hash' -LogName $Logname -Source $Source" $CompleteCommand = $RunCommand + $LogCommand $ScriptBlock = [scriptblock]::Create("$CompleteCommand") #Register Scheduled Job if (Get-ScheduledJob | Where-Object {$_.Name -eq $Name}) {Unregister-ScheduledJob -Name $Name} $JobParams = @{ Name = $Name ScriptBlock = $ScriptBlock Trigger = New-JobTrigger -Daily -At $DailyRunTime ScheduledJobOption = New-ScheduledJobOption -RunElevated -RequireNetwork -MultipleInstancePolicy 'StopExisting' Credential = $LdapCredential Verbose = $Verbose } Register-ScheduledJob @JobParams | Out-Null } function Install-EsxiInventoryToken { <# .SYNOPSIS Command to setup publish token .DESCRIPTION Stores a local token used to access the Publish Api key stored in vault. The token is a representation of the secret ID for the approle used to access the Publish Api key. This command needs to be run before Publish-EsxiInventory is run on a new computer and/or when the token expires. .PARAMETER LdapCredential The ldap username and password credentials used to access $Vault_Address .PARAMETER Vault_Address The address to the hashicorp vault. Format is: 'https://myvaultaddress'. .PARAMETER Vault_Rolename The name of the approle used to access secrets stored in hashicorp vault. .EXAMPLE Install-EsxiInventoryTools -LdapCredential (Get-Credential) #> [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [System.Management.Automation.PSCredential]$LdapCredential, [Parameter(Mandatory=$true)] [ValidateScript({$_ -match 'https'})] [ValidateScript({$_ -notmatch '/$' -and $_ -notmatch '/v1$'})] [string]$Vault_Address, [Parameter(Mandatory=$true)] [string]$Vault_Rolename ) $Verbose = $VerbosePreference -ne 'SilentlyContinue' $ErrorActionPreference = 'Stop' #Save Token $Save_VaultToken_Params = @{ LdapCredential = $LdapCredential Vault_Address = $Vault_Address Vault_Rolename = $Vault_Rolename OutputPath = $CachedTokenPath Verbose = $Verbose } Save-VaultToken @Save_VaultToken_Params } |