如何从ec2实例中找到ec2实例的实例id ?


当前回答

在围棋中,你可以使用goamz包。

import (
    "github.com/mitchellh/goamz/aws"
    "log"
)

func getId() (id string) {
    idBytes, err := aws.GetMetaData("instance-id")
    if err != nil {
        log.Fatalf("Error getting instance-id: %v.", err)
    }

    id = string(idBytes)

    return id
}

下面是GetMetaData源代码。

其他回答

如果你想在python中获取所有实例id列表,下面是代码:

import boto3

ec2=boto3.client('ec2')
instance_information = ec2.describe_instances()

for reservation in instance_information['Reservations']:
   for instance in reservation['Instances']:
      print(instance['InstanceId'])

对于powershell用户:

(New-Object System.Net.WebClient).DownloadString("http://169.254.169.254/latest/meta-data/instance-id")

如果您还需要查询实例ID以外的其他信息,请使用/dynamic/instance-identity/document URL。

wget -q - o - http://169.254.169.254/latest/dynamic/instance-identity/document

这将为您提供这样的JSON数据——只需要一个请求。

{
    "devpayProductCodes" : null,
    "privateIp" : "10.1.2.3",
    "region" : "us-east-1",
    "kernelId" : "aki-12345678",
    "ramdiskId" : null,
    "availabilityZone" : "us-east-1a",
    "accountId" : "123456789abc",
    "version" : "2010-08-31",
    "instanceId" : "i-12345678",
    "billingProducts" : null,
    "architecture" : "x86_64",
    "imageId" : "ami-12345678",
    "pendingTime" : "2014-01-23T45:01:23Z",
    "instanceType" : "m1.small"
}

简单的一行

猫/ sys /设备/虚拟/ dmi / id / board_asset_tag

or

Curl_cli -s http://169.254.169.254/latest/meta-data/instance-id

来源:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html

类型:

ec2metadata --instance-id