7

I need a function wich tells me the instanceID, I was searching here for a function, but you always need the id... Yeah and this is the problem.

I'm not allowed to use the console, need to find it out via a script.

I saw the AWS.MetadataService documentation, but I can't handle it. I just can see single pieces but I don't know how to match them right, to geht what I want. At the moment I have this

var meta  = new AWS.MetadataService();

meta.request("http://169.254.169.254/latest/meta-data/", function(err, data){
    console.log(data);
});

But ofc this dont works... What needs to be in the path parameter?

nova
  • 313
  • 6
  • 19
  • 1
    Is your script running on the instance for which you need the ID? If so, I think you're looking for `AWS.MetadataService` – Mark B May 20 '16 at 15:44
  • 1
    Possible duplicate of [Find out the instance id from within an ec2 machine](http://stackoverflow.com/questions/625644/find-out-the-instance-id-from-within-an-ec2-machine) – Anthony Neace May 20 '16 at 16:10
  • yes I saw the AWS MetadataService but I have no clue how to use it, I'll edit my question to show you my struggles – nova May 23 '16 at 06:51

2 Answers2

21

If your script is running on the EC2 instance for which you want the ID, you can get the EC2 instance ID from the instance meta-data. This command will give you the EC2 instance ID (eg. i-12345678):

curl http://169.254.169.254/latest/meta-data/instance-id

Full docs for the meta-data can be found here:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

Update:

For something in Node, try this:

var meta  = new AWS.MetadataService();

meta.request("/latest/meta-data/instance-id", function(err, data){
    console.log(data);
});

Don't include the http:// and host parts. Just the final path.

Matt Houser
  • 33,983
  • 6
  • 70
  • 88
0

If you're looking from ec2 api you can use the aws ec2 describe-XXX command for example

[xxx@IP-xxxx ~]# aws ec2 describe-addresses
{
    "Addresses": [
        {
            "Domain": "vpc",
            "InstanceId": "i-YOUR INSTANCE ID",
            "NetworkInterfaceId": "eni-xxxx",
            "AssociationId": "eipassoc-xxxx",
            "NetworkInterfaceOwnerId": "xxxx",
            "PublicIp": "xxxx",
            "AllocationId": "eipalloc-xxxx",
            "PrivateIpAddress": "xxxx"
        }
    ]
}

you can also use aws ec2 describe-instances its pretty complete and return all info about the instance include the InstanceId

Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
  • already tried this but i get `{ [MissingParameter: The request must contain the parameter instance id] message: 'The request must contain the parameter instance id',` So as I said, the instanceId is always needed – nova May 23 '16 at 07:08
  • If you run it from the instance, it works - I've used it many times and I put an example from a running instance – Frederic Henri May 23 '16 at 07:12