当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何从ec2实例中获取实例ID?》经验,为你挑选了16个好方法。

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



1> vladr..:

请参阅有关该主题的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根据平台上安装的内容.


您可以使用`http:// instance-data /`而不是`169.254.169.254`来消除幻数
我在2016-02-04检查了这个.我发现"instance-data"主机名是(a)未在该文档中列出,并且(b)在新的EC2主机上不起作用(对我而言).文档 - http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html - 仅提及169.254地址,并未提及"instance-data"主机名.即使用http://169.254.169.254/latest/meta-data/instance-id
instance-data hostname对我不起作用.
在Java SDK中怎么样?有没有办法得到这个而不必在该网址上进行GET?如果它不在SDK中,似乎很奇怪

2> James..:

在Amazon Linux AMI上,您可以:

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

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

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


在ubuntu上,命令是`ec2metadata --instance-id`
如果你正在考虑使用它,[本文](http://www.spinellis.gr/blog/20120601/)值得一读(tldr:是命令行工具是java,java的启动时间很长)
我认为您的意思是ec2-metadata --instance-id
该命令在不同的Linux上是不同的:在Amazon Linux上是`ec2-metadata`,在Ubuntu上似乎是`ec2metadata`。

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


默认情况下,cloud-utils软件包包含在Ubuntu 12.04.1 LTS Cluster Compute AMI中.

4> Konrad Kiss..:

/dynamic/instance-identity/document如果您还需要查询的不仅仅是实例ID,请使用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"
}



5> Mehdi LAMRAN..:

对于.NET人民:

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



6> 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}/";



7> 小智..:

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


inst_id = boto.utils.get_instance_metadata()['instance-id']
对于任何想知道的人,这是在博托但尚未在boto3.有关使用urllib的变通方法,请参见http://stackoverflow.com/a/33733852.在https://github.com/boto/boto3/issues/313 FWIW上有一个开放的功能请求,JS SDK也有这个:http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MetadataService. html使用`new AWS.MetadataService().request('instance-id',function(error,data){myInstanceId = data;})`

8> 小智..:

对于powershell人:

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


只是不同的commandet:`$实例Id =(调用-的WebRequest -uri 'http://169.254.169.254/latest/meta-data/instance-id').Content`

9> gareth_bowle..:

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



10> 小智..:

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

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

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

    ec2metadata --instance-id



11> Kevin Meyer..:

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


抱歉.不知道怎么说"这是一个很好的编辑.我是OP.接受这个".

12> DetDev..:

更现代的解决方案.

在Amazon Linux中,已经安装了ec2-metadata命令.

从终端

ec2-metadata -help

将为您提供可用的选项

ec2-metadata -i

将返回

instance-id: yourid


在Ubuntu映像中,命令是"ec2metadata --instance-id",并且只返回实例id值

13> 小智..:

只需输入:

ec2metadata --instance-id


显然这是亚马逊AMI的命令,你应该更新你的答案

14> 小智..:

你可以试试这个:

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



15> 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);
        }

        /// 
        /// 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
        /// 
        /// The service we are seeking (such as ec2, rds etc)
        /// Each AWS service has a different endpoint url for each region
        /// True if the operation was succesful, otherwise false
        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 [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;
        }
        /// 
        /// Downloads instance metadata
        /// 
        /// True if the operation was successful, false otherwise
        /// The operation will be unsuccessful if the machine running this code is not an AWS EC2 machine.
        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
*************************************************************/
    }
}



16> Scott Smith..:

最新的Java SDK具有EC2MetadataUtils:

在Java中:

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

在斯卡拉:

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

推荐阅读
360691894_8a5c48
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有