문제

어떻게 알 수 있습니까? instance id EC2 인스턴스 내에서 EC2 인스턴스의?

도움이 되었습니까?

해결책

보다 주제에 대한 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 Amis에서는 다음을 수행 할 수 있습니다.

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

사용 /dynamic/instance-identity/document 인스턴스 ID 이상의 쿼리가 필요한 경우 URL.

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

이것은 당신을 얻을 것입니다 JSON 이와 같은 데이터 - a 단일 요청.

{
    "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 | cut -d " " -f 2

산출:

i-33400429

변수 사용 :

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

파이썬의 경우 :

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]

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 시스템의 경우 인스턴스 -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]\)"`

루비를 위해 :

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

스칼라 :

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

C ++의 경우 (컬 사용) :

    #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 나는 EC2 메타 데이터 서비스에 대한 액세스를 제공하기 위해 Fuse FileSystem을 작성했습니다. https://bitbucket.org/dgc/ec2mdfs . 나는 이것을 모든 맞춤형 amis에서 실행합니다. 이 관용구를 사용할 수 있습니다 : cat/ec2/meta-data/ami-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 소스.

간단히 확인하십시오 var/lib/cloud/instance Symlink, 가리 켜야합니다 /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

메타 데이터 및 userData를 얻기위한 HTTP 요청에 대해서는 청구되지 않습니다.

또 다른

CURL을 사용하여 Documentation에서 언급 된 EC2 인스턴스 내에서 EC2 인스턴스 메타 데이터를 쿼리하는 간단한 bash 스크립트 인 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

도와 줄 수있어서 기뻐.. :)

질문에서 사용자를 루트로 언급 한 것은 인스턴스 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);

이는 인스턴스에 대한 많은 데이터를 제공 할 것입니다. 모든 배열에 잘 포장되어 있으며 외부 종속성이 없습니다. 나에게 실패하거나 지연되지 않은 요청이므로 그렇게하는 것이 안전해야합니다. 그렇지 않으면 Curl ()로 갈 것입니다.

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 인스턴스 자체에서 다음 명령을 실행하여 액세스 할 수 있습니다.

곱슬 곱슬하다 :

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

당신의 경우 : "메타 데이터 요청" 해야한다 인스턴스 -ID , "Api-Version"보통입니다 최신 사용할 수 있습니다.

추가 참고 : 위 명령을 사용하여 아래 EC2 속성과 관련된 정보를 얻을 수도 있습니다.

amiid, ami-launch-index, ami-manifest-path, block-device-mapping/, hostname, iam/, instance-action, 인스턴스 -ID, 인스턴스 유형, 로컬-호스트 이름, 로컬 -IPV4, Mac, 메트릭/, 네트워크/, 배치/, 프로파일, 공공 호스트 이름, 공공 -IPV4, 공공-키/, 예약, 보안 그룹, 서비스/,

자세한 내용은이 링크를 참조하십시오. 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 Elastic Beanstalk eb Cli Run의 경우 eb tags --list

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top