如何在ec2实例中找到ec2实例的 instance id

有帮助吗?

解决方案

请参阅有关该主题的EC2文件

执行命令

wget -q -O - http://169.254.169.254/latest/meta-data/instance-id

如果您需要从脚本中以编程方式访问实例ID,

die() { status=$1; shift; echo "FATAL: $*"; exit $status; }
EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"

更高级用法的示例(检索实例ID以及可用区和区域等):

EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"
test -n "$EC2_INSTANCE_ID" || die 'cannot obtain instance-id'
EC2_AVAIL_ZONE="`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone || die \"wget availability-zone has failed: $?\"`"
test -n "$EC2_AVAIL_ZONE" || die 'cannot obtain availability-zone'
EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"

您也可以使用 curl 代替 wget ,具体取决于您平台上安装的内容。

其他提示

在Amazon Linux AMI上,你可以这样做:

$ ec2-metadata -i
instance-id: i-1234567890abcdef0

或者,在Ubuntu和其他一些Linux风格上, ec2metadata --instance-id (默认情况下,这个命令可能不会安装在ubuntu上,但你可以用 sudo apt-添加它get install cloud-utils

顾名思义,您也可以使用该命令获取其他有用的元数据。

在Ubuntu上你可以:

sudo apt-get install cloud-utils

然后你可以:

EC2_INSTANCE_ID=$(ec2metadata --instance-id)

您可以通过以下方式获取与实例关联的大部分元数据:

ec2metadata --help
Syntax: /usr/bin/ec2metadata [options]

Query and display EC2 metadata.

If no options are provided, all options will be displayed

Options:
    -h --help               show this help

    --kernel-id             display the kernel id
    --ramdisk-id            display the ramdisk id
    --reservation-id        display the reservation id

    --ami-id                display the ami id
    --ami-launch-index      display the ami launch index
    --ami-manifest-path     display the ami manifest path
    --ancestor-ami-ids      display the ami ancestor id
    --product-codes         display the ami associated product codes
    --availability-zone     display the ami placement zone

    --instance-id           display the instance id
    --instance-type         display the instance type

    --local-hostname        display the local hostname
    --public-hostname       display the public hostname

    --local-ipv4            display the local ipv4 ip address
    --public-ipv4           display the public ipv4 ip address

    --block-device-mapping  display the block device id
    --security-groups       display the security groups

    --mac                   display the instance mac address
    --profile               display the instance profile
    --instance-action       display the instance-action

    --public-keys           display the openssh public keys
    --user-data             display the user data (not actually metadata)

如果您还需要查询的不仅仅是实例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"
}

对于 .NET 人员:

string instanceId = new StreamReader(
      HttpWebRequest.Create("http://169.254.169.254/latest/meta-data/instance-id")
      .GetResponse().GetResponseStream())
    .ReadToEnd();
AWS Linux上的

ec2-metadata --instance-id |切-d“ " -f 2

输出:

<代码> I-33400429

在变量中使用:

ec2InstanceId=$(ec2-metadata --instance-id | cut -d " " -f 2);
ls "log/${ec2InstanceId}/";

对于Python:

import boto.utils
region=boto.utils.get_instance_metadata()['local-hostname'].split('.')[1]

归结为单行:

python -c "import boto.utils; print boto.utils.get_instance_metadata()['local-hostname'].split('.')[1]"

您也可以使用public_hostname或:

,而不是local_hostname
boto.utils.get_instance_metadata()['placement']['availability-zone'][:-1]

对于powershell人:

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

请参阅此帖子 - 请注意,给定URL中的IP地址是不变的(最初让我感到困惑),但返回的数据特定于您的实例。

更现代的解决方案。

从Amazon Linux中已经安装了ec2-metadata命令。

从终端

ec2-metadata -help

会为您提供可用的选项

ec2-metadata -i

将返回

instance-id: yourid

只需输入:

ec2metadata --instance-id

对于所有ec2机器,可以在文件中找到instance-id:

    /var/lib/cloud/data/instance-id

您还可以通过运行以下命令来获取实例ID:

    ec2metadata --instance-id

你可以试试这个:

#!/bin/bash
aws_instance=$(wget -q -O- http://169.254.169.254/latest/meta-data/instance-id)
aws_region=$(wget -q -O- http://169.254.169.254/latest/meta-data/hostname)
aws_region=${aws_region#*.}
aws_region=${aws_region%%.*}
aws_zone=`ec2-describe-instances $aws_instance --region $aws_region`
aws_zone=`expr match "$aws_zone" ".*\($aws_region[a-z]\)"`

对于Ruby:

require 'rubygems'
require 'aws-sdk'
require 'net/http'

metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )

ec2 = AWS::EC2.new()
instance = ec2.instances[instance_id]

我为http api编写的EC2元数据的c#.net类。 我将根据需要使用功能构建它。如果你愿意,你可以随身携带。

using Amazon;
using System.Net;

namespace AT.AWS
{
    public static class HttpMetaDataAPI
    {
        public static bool TryGetPublicIP(out string publicIP)
        {
            return TryGetMetaData("public-ipv4", out publicIP);
        }
        public static bool TryGetPrivateIP(out string privateIP)
        {
            return TryGetMetaData("local-ipv4", out privateIP);
        }
        public static bool TryGetAvailabilityZone(out string availabilityZone)
        {
            return TryGetMetaData("placement/availability-zone", out availabilityZone);
        }

        /// <summary>
        /// Gets the url of a given AWS service, according to the name of the required service and the AWS Region that this machine is in
        /// </summary>
        /// <param name="serviceName">The service we are seeking (such as ec2, rds etc)</param>
        /// <remarks>Each AWS service has a different endpoint url for each region</remarks>
        /// <returns>True if the operation was succesful, otherwise false</returns>
        public static bool TryGetServiceEndpointUrl(string serviceName, out string serviceEndpointStringUrl)
        {
            // start by figuring out what region this instance is in.
            RegionEndpoint endpoint;
            if (TryGetRegionEndpoint(out endpoint))
            {
                // now that we know the region, we can get details about the requested service in that region
                var details = endpoint.GetEndpointForService(serviceName);
                serviceEndpointStringUrl = (details.HTTPS ? "https://" : "http://") + details.Hostname;
                return true;
            }
            // satisfy the compiler by assigning a value to serviceEndpointStringUrl
            serviceEndpointStringUrl = null;
            return false;
        }
        public static bool TryGetRegionEndpoint(out RegionEndpoint endpoint)
        {
            // we can get figure out the region end point from the availability zone
            // that this instance is in, so we start by getting the availability zone:
            string availabilityZone;
            if (TryGetAvailabilityZone(out availabilityZone))
            {
                // name of the availability zone is <nameOfRegionEndpoint>[a|b|c etc]
                // so just take the name of the availability zone and chop off the last letter
                var nameOfRegionEndpoint = availabilityZone.Substring(0, availabilityZone.Length - 1);
                endpoint = RegionEndpoint.GetBySystemName(nameOfRegionEndpoint);
                return true;
            }
            // satisfy the compiler by assigning a value to endpoint
            endpoint = RegionEndpoint.USWest2;
            return false;
        }
        /// <summary>
        /// Downloads instance metadata
        /// </summary>
        /// <returns>True if the operation was successful, false otherwise</returns>
        /// <remarks>The operation will be unsuccessful if the machine running this code is not an AWS EC2 machine.</remarks>
        static bool TryGetMetaData(string name, out string result)
        {
            result = null;
            try { result = new WebClient().DownloadString("http://169.254.169.254/latest/meta-data/" + name); return true; }
            catch { return false; }
        }

/************************************************************
 * MetaData keys.
 *   Use these keys to write more functions as you need them
 * **********************************************************
ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
hostname
instance-action
instance-id
instance-type
local-hostname
local-ipv4
mac
metrics/
network/
placement/
profile
public-hostname
public-ipv4
public-keys/
reservation-id
security-groups
*************************************************************/
    }
}

最新的Java SDK具有 EC2MetadataUtils

在Java中:

import com.amazonaws.util.EC2MetadataUtils;
String myId = EC2MetadataUtils.getInstanceId();

在Scala中:

import com.amazonaws.util.EC2MetadataUtils
val myid = EC2MetadataUtils.getInstanceId

对于C ++ (使用cURL):

    #include <curl/curl.h>

    //// cURL to string
    size_t curl_to_str(void *contents, size_t size, size_t nmemb, void *userp) {
        ((std::string*)userp)->append((char*)contents, size * nmemb);
        return size * nmemb;
    };

    //// Read Instance-id 
    curl_global_init(CURL_GLOBAL_ALL); // Initialize cURL
    CURL *curl; // cURL handler
    CURLcode res_code; // Result
    string response;
    curl = curl_easy_init(); // Initialize handler
    curl_easy_setopt(curl, CURLOPT_URL, "http://169.254.169.254/latest/meta-data/instance-id");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_to_str);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    res_code = curl_easy_perform(curl); // Perform cURL
    if (res_code != CURLE_OK) { }; // Error
    curl_easy_cleanup(curl); // Cleanup handler
    curl_global_cleanup(); // Cleanup cURL

如果您希望使用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'])

FWIW我写了一个FUSE文件系统来提供对EC2元数据服务的访问: https://bitbucket.org/dgc / ec2mdfs 。 我在所有自定义AMI上运行它;它允许我使用这个成语:cat / ec2 / meta-data / ami-id

在Go中,您可以使用 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来源。

只需检查 var / lib / cloud / instance 符号链接,它应该指向 / var / lib / cloud / instances / {instance-id} 其中 {instance_id} 是您的实例ID。

您可以通过传递元数据参数来发出HTTP请求以获取任何元数据。

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

wget -q -O - http://169.254.169.254/latest/meta-data/instance-id

您不需要为获取元数据和用户数据的HTTP请求付费。

否则

您可以使用EC2实例元数据查询工具,这是一个简单的bash脚本,它使用curl从正在运行的EC2实例中查询EC2实例元数据,如文档中所述。

下载该工具:

$ wget http://s3.amazonaws.com/ec2metadata/ec2-metadata

现在运行命令以获取所需数据。

$ec2metadata -i

参见:

http://docs.aws.amazon的.com / AWSEC2 /最新/ UserGuide / EC2-实例metadata.html

https://aws.amazon.com/items/1825?externalID=1825

乐意帮助.. :)

在您以root身份提到用户的问题中,我应该提到的一件事是实例ID不依赖于用户。

对于节点开发人员,

var meta  = new AWS.MetadataService();

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

PHP的替代方法:

$instance = json_decode(file_get_contents('http://169.254.169.254/latest/dynamic/instance-identity/document'),true);
$id = $instance['instanceId'];
print_r($instance);

这将提供大量关于实例的数据,所有数据都很好地打包在一个数组中,没有外部依赖关系。 因为这是一个永远不会失败或延迟的请求,所以这样做应该是安全的,否则我会去卷曲()

对于PHP:

$instance = json_decode(file_get_contents('http://169.254.169.254/latest/dynamic/instance-identity/document));
$id = $instance['instanceId'];

按@John编辑

运行:

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

您将能够看到由aws提供的不同类型的属性。

使用此链接查看更多

EC2实例本身可以在执行以下命令的帮助下访问与EC2资源相关的所有元数据:

CURL:

http://169.254.169.254/<api-version>/meta-data/<metadata-requested>

对于您的情况:“请求元数据”应为 instance-id ,&quot; api-version &quot;通常最新可以使用。

附加说明:您还可以使用上述命令获取与以下EC2属性相关的信息。

AMI-ID, AMI推出指数, AMI-清单路径, 块的设备映射/, 主机名, 我是/, 例如动作, 实例的编号, 例如型, 本地主机名, 当地的IPv4, 苹果电脑, 度量/, 网络/, 放置/, 轮廓, 公共主机名, 公共IPv4中, 公共密钥/, 预约ID, 安全组, 服务/

有关详细信息,请访问以下链接: https ://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

要获取实例元数据

wget -q -O - http://169.254.169.254/latest/meta-data/instance-id

对于Windows实例:

(wget http://169.254.169.254/latest/meta-data/instance-id).Content

(ConvertFrom-Json (wget http://169.254.169.254/latest/dynamic/instance-identity/document).Content).instanceId

对于AWS弹性beanstalk eb cli运行 eb标签--list

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top