ChatGPT解决这个技术问题 Extra ChatGPT

如何从 ec2 实例中获取实例 ID?

如何从 ec2 实例中找出 ec2 实例的 instance id


T
The-Big-K

请参阅the EC2 documentation on the subject

跑:

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,具体取决于您的平台上安装的内容。


在 Java SDK 中呢?有什么方法可以得到这个而不必在那个 url 上做一个 GET ?如果它不在 SDK 中,这似乎很奇怪
很有帮助,谢谢。对于其他试图找出最后一行中的正则表达式的人,这是我想出的:在行尾 ($),找到一个或多个数字后跟一个或多个小写字母。仅用数字替换。 (反斜杠 + 括号告诉 sed 记住一个子字符串,用 \1 调用它。)我发现这更容易阅读——唯一的反斜杠是 sed 需要的那些:EC2_REGION="$(echo "$EC2_AVAIL_ZONE" | sed -e 's:\([0-9][0-9]*\)[a-z]*$:\1:')"
您可以使用 http://instance-data/ 而不是 169.254.169.254 来消除幻数
我在 2016 年 2 月 4 日检查了这个。我发现“instance-data”主机名(a)未在该文档中列出,并且(b)在新的 EC2 主机上(对我而言)不起作用。文档——docs.aws.amazon.com/AWSEC2/latest/UserGuide/…——只提到了 169.254 地址,没有提到“instance-data”主机名。即使用169.254.169.254/latest/meta-data/instance-id
instance-data 仅在您使用 Amazon DNS 解析器时可用 - 如果您不使用,它将不可用。它解析为 169.254.169.254。
J
James

在 Amazon Linux AMI 上,您可以执行以下操作:

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

或者,在 Ubuntu 和其他一些 linux 版本上,ec2metadata --instance-id(这个命令可能不会默认安装在 ubuntu 上,但您可以使用 sudo apt-get install cloud-utils 添加它)

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


最佳答案
@Marc 不。 ec2 之后没有 -。它是 ec2metadata --instance-id
该命令在不同的 Linux 上有所不同:在 Amazon Linux 上是 ec2-metadata,在 Ubuntu 上似乎是 ec2metadata
@Cerin 不,这个命令在 Amazon Linux 2 上仍然是正确的。[ec2-user@ip-10-1-1-1 ~]$ ec2-metadata -i \ instance-id: <redacted> \ [ec2-user@ip-10-1-1-1 ~]$ ec2metadata \ -bash: ec2metadata: command not found
@Cerin 也许您使用的是不同的 Linux 发行版?此命令在 Amazon Linux 上。
r
rhunwicks

在 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)

在 Ubuntu lucid apt-get install 下检索不包含此实用程序的版本 0.11-0ubuntu1。它已添加到包 just afterwards
cloud-utils 软件包默认包含在 Ubuntu 12.04.1 LTS 集群计算 AMI 中。
cloud-utils 似乎也在 RHEL/CentOS 中
c
chicks

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

+1 用于在一个简单的调用中显示所有详细信息,包括 instanceType
+1 具有相当标准的(仅限 wget)和工作线(实例数据 url 在 amazon linux 上对我不起作用),而无需为这个简单的任务安装额外的软件包。
g
gpupo

在 AWS Linux 上:

ec2-metadata --instance-id | cut -d " " -f 2

输出:

i-33400429

在变量中使用:

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

简洁明了的方式。开箱即用的 Ubuntu 14 实例。
A
Aman

对于所有 ec2 机器,可以在文件中找到实例 ID:

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

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

    ec2metadata --instance-id

这是一个非常干净的解决方案,不需要 HTTP 请求。
实际上最好的答案
很好的答案,但我在文档中找不到这方面的参考。请问你的参考资料是什么?问题是,如果我们要在生产环境中运行这段代码,我们怎么知道它在未来不会改变?
也许是所有 linux ec2 机器,但绝对不是 all ec2 机器。 Windows 上没有这样的文件。 C:\ProgramData\Amazon\EC2-Windows\Launch\Log\Ec2Launch.log 包含实例 ID,但也有很多其他垃圾。
r
rae1

对于 .NET 人:

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

T
Taryn

对于 powershell 人:

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

只是不同的命令:$instanceId=(Invoke-WebRequest -Uri 'http://169.254.169.254/latest/meta-data/instance-id').Content
在使用 ssm send-command(或 Send-SSMCommand)在所述 EC2 实例上运行脚本时,Invoke-WebRequest 并不总是有效。 docs 中并没有真正说明。可能它不是异步的......这会很奇怪。但到目前为止,stefancaunter 的选择没有任何问题。
b
benlast

对于 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]"

除了 local_hostname,您还可以使用 public_hostname,或者:

boto.utils.get_instance_metadata()['placement']['availability-zone'][:-1]

我看到的所有较新版本的 boto 都允许您直接调用密钥“instance_id”。我做了相关的建议编辑。
inst_id = boto.utils.get_instance_metadata()['instance-id']
您确实意识到这会获取实例所在的区域,而不是问题所要求的 instance-id,对吗?
对于任何想知道的人,这是在 boto 但尚未在 boto3 中。有关使用 urllib 的解决方法,请参阅 stackoverflow.com/a/33733852github.com/boto/boto3/issues/313 FWIW 有一个开放功能请求,JS SDK 也有这个:docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/… 使用 new AWS.MetadataService().request('instance-id',function(error,data) { myInstanceId = data; })
g
gareth_bowles

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


链接对我来说是 404ing
在下面查看@DEtDev 的答案;我的答案很老,看起来链接已被删除。
A
Akash Arya

只需键入:

ec2metadata --instance-id

您使用的是哪个 AMI?
显然这是亚马逊 AMI 的命令,你应该更新你的答案
@WédneyYuri 是的。
对于 alinux2 ami,我有 ec2-metadata 命令而不是 ec2metadata。不确定这是错字还是新 AMI 实例中的命令已更改。 ec2-metadata --instance-id | cut -d' ' -f2 仅作为字符串的 id
D
DetDev

更现代的解决方案。

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

从航站楼

ec2-metadata -help

将为您提供可用的选项

ec2-metadata -i

将返回

instance-id: yourid

比依赖伪ip好多了
ec2-metadata 与您的 motd 结合起来,此处的文档:coderwall.com/p/hr_9pw/motds-on-amazon-amis
在 Ubuntu 映像中,命令是“ec2metadata --instance-id”,将仅返回实例 ID 值
A
Alex Koloskov

你可以试试这个:

#!/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]\)"`

K
Kevin Meyer

对于红宝石:

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]

伙计们?!你偷了我的编辑! stackoverflow.com/review/suggested-edits/4035074
对不起。不知道怎么说“这是一个很好的编辑。我是 OP。接受这个”。
M
Mattiavelli

最新的 Java SDK 具有 EC2MetadataUtils

在 Java 中:

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

在斯卡拉:

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

b
bboyle1234

我为来自 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
*************************************************************/
    }
}

M
Medical physicist

对于 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

g
greg

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


我不会用这个。您最好使用已批准的 HTTP 请求来获取元数据。
V
Vikas Satpute

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

d
dmikalova

在 Go 中,您可以使用 goamz package

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
}

Here's GetMetaData 源。


c
codeforester

您可以通过传递元数据参数来发出 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/latest/UserGuide/ec2-instance-metadata.html

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

很高兴能帮助你.. :)


d
dgc

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


a
avivamg

动机:用户想要检索 aws 实例元数据。

解决方案: IP 地址 169.254.169.254 是一个链接本地地址(仅在实例中有效)aws 为我们提供了与专用 Restful API 的链接用于检索我们正在运行的实例的元数据(请注意,您无需为用于检索实例元数据和用户数据的 HTTP 请求付费)。 Additional Documentation

例子:

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

//Response
ami-123abc

您可以使用此链接 http://169.254.169.254/latest/meta-data/<metadata-field> 获取实例的其他元数据标签,只需选择正确的标签:

ami-id ami-launch-index ami-manifest-path 块设备映射事件 hibernation hostname iam identity-credentials instance-action instance-id instance-type local-hostname local-ipv4 mac metrics 网络放置配置文件 reservation-id security-groups服务


curl: (7) 无法连接到 IP 80 端口:连接拒绝,端口 80 已打开
要获取最新列表,请在父级 curl:http://169.254.169.254/latest/meta-data/
R
Rumesh Eranga Hapuarachchi

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

对于 Node 开发人员,

var meta  = new AWS.MetadataService();

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

i
iBug

要获取实例元数据,请使用

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

d
demonicdaron

对于 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

J
John

PHP的替代方法:

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

这将提供有关实例的大量数据,所有数据都很好地打包在一个数组中,没有外部依赖项。因为这是一个从未失败或延迟的请求,所以这样做应该是安全的,否则我会选择 curl()


B
Beachhouse

对于 PHP:

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

根据@John 编辑


但是,如果您在 PHP 中有 curl 和本机函数,为什么还要使用 GuzzeHttp 呢?
这是我的偏好。我将 guzzle 用于许多其他事情,它也是许多其他软件包的共同先决条件。
$instance = json_decode(file_get_contents('169.254.169.254/latest/dynamic/instance-identity/…); $id = $instance['instanceId']; 我知道 Guzzle 很普遍,我自己从未接触过它。对于这样一个简单的任务,我会提供最简单的方法.
C
Chinthaka Hasakelum

运行这个:

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

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

Use this link to view more


V
Vipin Sharma

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

卷曲:

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

对于您的情况:“metadata-requested”应该是 instance-id ,“api-version”通常是可以使用的最新版本。

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

ami-id、ami-launch-index、ami-manifest-path、块设备映射/、主机名、iam/、实例操作、实例 ID、实例类型、本地主机名、本地 ipv4、mac、指标/,网络/,放置/,配置文件,公共主机名,公共ipv4,公共密钥/,预留ID,安全组,服务/,

有关详细信息,请点击此链接:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html