3

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

1 Answer 1

2

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())}
    }
  }
}

Example output

InstanceID          HostName
----------          --------
i-abcdefgh          EC2AMAZ-ABCDE
i-12345678          WIN-1ABCD2EFG

Filtering

From there, you can simply match the output of that cmdlet to filter for your hostname:

@(Get-EC2InstanceWindowsHostNames) | ? { $_.HostName -eq 'WIN-1ABCD2EFG' }

Example output

InstanceID HostName
---------- --------
i-12345678 WIN-1ABCD2EFG

Further Reading

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.