Reputation: 985
Is it possible to filter EC2 Instances by machine hostname? I am trying to find an internal instance but I don't have the IP address or the instanceId. I can't find any examples but I am thinking something this.
$instanceName = "MYMACHINEHOSTNAME"
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "Hostname"
$filter.Value = "$instanceName"
$ec2Instances = (Get-EC2Instance -Region us-west-2 -Filter $filter).Instances
Has anyone done anything like this?
Thanks,
Rhonda
Upvotes: 3
Views: 8867
Reputation: 26023
Get-EC2Instance
doesn't know about OS-level details like that, but you might be able to get what you want from Get-EC2ConsoleOutput
. This will output the system log, and I believe that by default, Amazon-owned Windows AMIs RDPCERTIFICATE-SUBJECTNAME
will usually match the windows hostname.
Give this a try, I just wrote it to print a collection of InstanceId, Windows Hostname pairs for this case of EC2 Instances based on Amazon-owned Windows AMIs:
# Note: This is designed to work with default Windows AMIs that Amazon supplies.
function Get-EC2InstanceWindowsHostNames
{
# Filter to use only windows instances
$instanceIds = (Get-EC2Instance -Filter @(@{name="platform";value="windows"})).Instances.InstanceId
$instanceIds | % {
$consoleOutput = Get-EC2ConsoleOutput -InstanceId $_
# Convert from Base 64 string
$bytes = [System.Convert]::FromBase64String($consoleOutput.Output)
$string = [System.Text.Encoding]::UTF8.GetString($bytes)
# If the string contains RDPCERTIFICATE-SUBJECTNAME, we can extract the hostname
if($string -match 'RDPCERTIFICATE-SUBJECTNAME: .*') {
$windowsHostName = $matches[0] -replace 'RDPCERTIFICATE-SUBJECTNAME: '
# Write resulting obj to stdout
[pscustomobject]@{InstanceID=$($consoleOutput.InstanceId);HostName=$($windowsHostName.Trim())}
}
}
}
InstanceID HostName
---------- --------
i-abcdefgh EC2AMAZ-ABCDE
i-12345678 WIN-1ABCD2EFG
From there, you can simply match the output of that cmdlet to filter for your hostname:
@(Get-EC2InstanceWindowsHostNames) | ? { $_.HostName -eq 'WIN-1ABCD2EFG' }
InstanceID HostName
---------- --------
i-12345678 WIN-1ABCD2EFG
Upvotes: 2