如何从该 EC2 实例中获取 AWS EC2 实例 ID?

发布于 2024-07-14 22:06:31 字数 47 浏览 6 评论 0原文

如何从 ec2 实例中找到 ec2 实例的实例 ID

How can I find out the instance id of an ec2 instance from within the ec2 instance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

安人多梦 2024-07-21 22:06:32

您只需通过传递元数据参数发出 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

很乐意提供帮助..:)

You can just make a HTTP request to GET any Metadata by passing the your metadata parameters.

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

or

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

You won't be billed for HTTP requests to get Metadata and Userdata.

Else

You can use EC2 Instance Metadata Query Tool which is a simple bash script that uses curl to query the EC2 instance Metadata from within a running EC2 instance as mentioned in documentation.

Download the tool:

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

now run command to get required data.

$ec2metadata -i

Refer:

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

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

Happy To Help.. :)

旧街凉风 2024-07-21 22:06:32

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

FWIW I wrote a FUSE filesystem to provide access to the EC2 metadata service: https://github.com/xdgc/ec2mdfs .
I run this on all custom AMIs; it allows me to use this idiom: cat /ec2/meta-data/ami-id

格子衫的從容 2024-07-21 22:06:32

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

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

示例< /strong>:

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

//Response
ami-123abc

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

  1. ami-id
  2. ami-launch-index
  3. ami-manifest-path 块
  4. 设备
  5. 映射
  6. 事件
  7. 休眠
  8. 主机名
  9. iam
  10. 身份凭证
  11. 实例操作
  12. 实例 ID
  13. 实例类型
  14. 本地主机名
  15. 本地 ipv4
  16. mac
  17. 指标
  18. 网络
  19. 布置配置
  20. 文件
  21. 预留 ID
  22. 安全组
  23. 服务

Motivation: User would like to Retrieve aws instance metadata.

Solution:
The IP address 169.254.169.254 is a link-local address (and is valid only from the instance) aws gives us link with dedicated Restful API for Retrieving metadata of our running instance (Note that you are not billed for HTTP requests used to retrieve instance metadata and user data) . for Additional Documentation

Example:

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

//Response
ami-123abc

You able to get additional metadata labels of your instance using this link http://169.254.169.254/latest/meta-data/<metadata-field> just choose the right tags:

  1. ami-id
  2. ami-launch-index
  3. ami-manifest-path
  4. block-device
  5. mapping
  6. events
  7. hibernation
  8. hostname
  9. iam
  10. identity-credentials
  11. instance-action
  12. instance-id
  13. instance-type
  14. local-hostname
  15. local-ipv4
  16. mac
  17. metrics
  18. network
  19. placement
  20. profile
  21. reservation-id
  22. security-groups
  23. services
饮湿 2024-07-21 22:06:32

最简单的方法是使用 aws cli 和 sts get-caller-identity

INSTANCE_ID=$(aws sts get-caller-identity --query UserId --output text | cut -d : -f 2)

  • 这样您就不需要手动对元数据端点进行授权。
  • 与仅适用于 amazon Linux AMI 的 ec2-metadata 命令相比,它适用于任何 unix AMI

Most simple approach is to use aws cli and sts get-caller-identity.

INSTANCE_ID=$(aws sts get-caller-identity --query UserId --output text | cut -d : -f 2)

  • This way you don't need to authorize against metadata endpoint manually.
  • It works on any unix AMI in contrast to ec2-metadata command that is only available for amazon linux AMIs
终止放荡 2024-07-21 22:06:32

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

对于Node开发人员来说,

var meta  = new AWS.MetadataService();

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

In the question you have mentioned the user as root, one thing I should mention is that the instance ID is not dependent on the user.

For Node developers,

var meta  = new AWS.MetadataService();

meta.request("/latest/meta-data/instance-id", function(err, data){
    console.log(data);
});
错々过的事 2024-07-21 22:06:32

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

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

To get the instance metadata use

wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
半山落雨半山空 2024-07-21 22:06:32

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

For a Windows instance:

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

or

(ConvertFrom-Json (wget http://169.254.169.254/latest/dynamic/instance-identity/document).Content).instanceId
拔了角的鹿 2024-07-21 22:06:32
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 

AMI=`curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/ami-id`

echo $AMI

这应该对你有帮助,

TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 

AMI=`curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/ami-id`

echo $AMI

This should helps you,

别想她 2024-07-21 22:06:32

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

Alternative approach for PHP:

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

That will provide a lot of data about the instance, all nicely packed in an array, no external dependencies.
As it's a request that never failed or delayed for me it should be safe to do it that way, otherwise I'd go for curl()

请参阅有关该主题的 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< /code> 而不是 wget,具体取决于您的平台上安装的内容。

See the EC2 documentation on the subject.

Run:

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

If you need programmatic access to the instance ID from within a script,

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: $?\"`"

Here is an example of a more advanced use (retrieve instance ID as well as availability zone and region, etc.):

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:'`"

You may also use curl instead of wget, depending on what is installed on your platform.

十雾 2024-07-21 22:06:31

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

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

或者,在 Ubuntu 和其他一些 Linux 版本上,ec2metadata --instance-id(默认情况下,在 ubuntu 上可能不会安装此命令,但您可以使用 < code>sudo apt-get install cloud-utils)

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

On Amazon Linux AMIs you can do:

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

Or, on Ubuntu and some other linux flavours, ec2metadata --instance-id (This command may not be installed by default on ubuntu, but you can add it with sudo apt-get install cloud-utils)

As its name suggests, you can use the command to get other useful metadata too.

就是爱搞怪 2024-07-21 22:06:31

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

On Ubuntu you can:

sudo apt-get install cloud-utils

And then you can:

EC2_INSTANCE_ID=$(ec2metadata --instance-id)

You can get most of the metadata associated with the instance this way:

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)
琉璃梦幻 2024-07-21 22:06:31

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

Use the /dynamic/instance-identity/document URL if you also need to query more than just your instance ID.

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

This will get you JSON data such as this - with only a single request.

{
    "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"
}
孤云独去闲 2024-07-21 22:06:31

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

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

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

    ec2metadata --instance-id

For all ec2 machines, the instance-id can be found in file:

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

You can also get instance id by running the following command:

    ec2metadata --instance-id
云归处 2024-07-21 22:06:31

在 AWS Linux 上:

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

输出:

i-33400429

在变量中使用:

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

on AWS Linux:

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

Output:

i-33400429

Using in variables:

ec2InstanceId=$(ec2-metadata --instance-id | cut -d " " -f 2);
ls "log/${ec2InstanceId}/";
秋日私语 2024-07-21 22:06:31

对于.NET人:

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

For .NET People :

string instanceId = new StreamReader(
      HttpWebRequest.Create("http://169.254.169.254/latest/meta-data/instance-id")
      .GetResponse().GetResponseStream())
    .ReadToEnd();
╰沐子 2024-07-21 22:06:31

对于 powershell 人员:

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

For powershell people:

(New-Object System.Net.WebClient).DownloadString("http://169.254.169.254/latest/meta-data/instance-id")
人生戏 2024-07-21 22:06:31

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

For Python:

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

which boils down to the one-liner:

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

Instead of local_hostname you could also use public_hostname, or:

boto.utils.get_instance_metadata()['placement']['availability-zone'][:-1]
‖放下 2024-07-21 22:06:31

请参阅这篇文章 - 请注意给定 URL 中的 IP 地址是不变的(一开始这让我很困惑),但返回的数据特定于您的实例。

See this post - note that the IP address in the URL given is constant (which confused me at first), but the data returned is specific to your instance.

守望孤独 2024-07-21 22:06:31

只需输入:

ec2metadata --instance-id

Just Type:

ec2metadata --instance-id
旧梦荧光笔 2024-07-21 22:06:31

更现代的解决方案。

在 Amazon Linux 中,已安装 ec2-metadata 命令。

从终端

ec2-metadata -help

会给你可用的选项

ec2-metadata -i

将返回

instance-id: yourid

A more contemporary solution.

From Amazon Linux the ec2-metadata command is already installed.

From the terminal

ec2-metadata -help

Will give you the available options

ec2-metadata -i

will return

instance-id: yourid
原来是傀儡 2024-07-21 22:06:31

你可以试试这个:

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

You can try this:

#!/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]\)"`
ヅ她的身影、若隐若现 2024-07-21 22:06:31

对于红宝石:

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]

For 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]
薄荷梦 2024-07-21 22:06:31

最新的 Java SDK 具有 EC2MetadataUtils

在 Java 中:

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

在 Scala 中:

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

The latest Java SDK has EC2MetadataUtils:

In Java:

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

In Scala:

import com.amazonaws.util.EC2MetadataUtils
val myid = EC2MetadataUtils.getInstanceId
不疑不惑不回忆 2024-07-21 22:06:31

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

A c# .net class I wrote for EC2 metadata from the http api.
I will build it up with functionality as needed. You can run with it if you like it.

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
*************************************************************/
    }
}
爱你是孤单的心事 2024-07-21 22:06:31

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

Simply check the var/lib/cloud/instance symlink, it should point to /var/lib/cloud/instances/{instance-id} where {instance_id} is your instance-id.

怕倦 2024-07-21 22:06:31

简单的一行

cat /sys/devices/virtual/dmi/id/board_asset_tag

curl_cli -s http://169.254.169.254/latest/meta-data/instance-id >

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

Simple one line

cat /sys/devices/virtual/dmi/id/board_asset_tag

or

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

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

恬淡成诗 2024-07-21 22:06:31

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

For C++ (using 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
羅雙樹 2024-07-21 22:06:31

如果你想在 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'])

If you wish to get the all instances id list in python here is the code:

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'])
昔梦 2024-07-21 22:06:31

在 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 源。

In Go you can use the 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 the GetMetaData source.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文