Today we found ourselves in a position where we had a Windows server – with only the Server Core experience installed – somewhere in EC2 but we could not figure out what AWS account it actually lived in. This meant that we were limiting to finding the missing EC2 instance in AWS using just the command line.
Most cloud providers offer an instance metadata endpoint that you can query to get some basic info about the instance itself. It usually operates on
http://169.254.169.254 (that IP is not a placeholder, it’s literally the IP you query) and AWS is no different. As per the AWS documentation, if you hit
http://169.254.169.254/latest/meta-data/ you can get some information about the running instance which was exactly what we needed.
The first thing we knew is that we needed to be in PowerShell, since the basic Windows command line doesn’t have an HTTP client.
Microsoft Windows [Version 10.0.20348.1070]
(c) Microsoft Corporation. All rights reserved.
Copyright (C) Microsoft Corporation. All rights reserved.
Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows
Next, we tried to use the
Invoke-WebRequest cmdlet, except being Server Core, it did not have the Internet Explorer (lol) components installed that this cmdlet apparently needs.
Thinking on our feet, we considered that maybe the
Invoke-RestMethod cmdlet didn’t have the IE dependency since it was strictly used for REST-based calls and may have be implemented without any IE components. Success.
PS C:\Users\nexxai>Invoke-RestMethod -Uri http://169.254.169.254/latest/meta-data/
We tried a couple of different endpoints, but then saw the
iam entry and gave it a shot.
PS C:\Users\nexxai>Invoke-RestMethod -Uri http://169.254.169.254/latest/meta-data/iam/
Then naturally we checked out
PS C:\Users\nexxai>Invoke-RestMethod -Uri http://169.254.169.254/latest/meta-data/iam/info
I can’t share the results of this command for obvious reasons, but contained within the results was the ARN of the IAM role that the EC2 instance was associated with, which – and here’s the important part – includes the account number! Yes!
After some more digging, it turns if you have the AWS CLI installed on the VM (unsure if this is installed by default), you can also run
aws sts get-caller-identity which will show the account the instance is running in.
Once we were able to get the account number, we were quickly able to locate the rogue instance and deal with the original problem we were searching it out for. I hope you never have to try and find a missing EC2 instance using just the command line, but if so, hopefully we’ve just made it a little easier to do so.