Programming

EC2 인스턴스에서 인스턴스 ID를 얻는 방법은 무엇입니까?

procodes 2020. 2. 29. 15:36
반응형

EC2 인스턴스에서 인스턴스 ID를 얻는 방법은 무엇입니까?


instance idec2 인스턴스에서 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 AMI에서 다음을 수행 할 수 있습니다.

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

또는 우분투와 다른 리눅스 풍미에서 ec2metadata --instance-id(이 명령은 우분투에는 기본적으로 설치되지 않을 수도 있지만을 사용하여 추가 할 수 있습니다 sudo apt-get install cloud-utils)

이름에서 알 수 있듯이이 명령을 사용하여 다른 유용한 메타 데이터도 얻을 수 있습니다.


우분투에서는 다음을 수행 할 수 있습니다.

sudo apt-get install cloud-utils

그리고 당신은 할 수 있습니다 :

EC2_INSTANCE_ID=$(ec2metadata --instance-id)

이 방법으로 인스턴스와 관련된 대부분의 메타 데이터를 얻을 수 있습니다.

ec2metadata --help
구문 : / usr / bin / ec2metadata [옵션]

EC2 메타 데이터를 쿼리하고 표시합니다.

옵션이 제공되지 않으면 모든 옵션이 표시됩니다

옵션 :
    -h --help이 도움말을 표시합니다

    --kernel-id 커널 ID를 표시합니다
    --ramdisk-id 램 디스크 ID를 표시합니다
    --reservation-id 예약 ID를 표시합니다

    --ami-id는 ami id를 표시합니다
    --ami-launch-index ami 실행 색인을 표시합니다
    --ami-manifest-path ami 매니페스트 경로 표시
    -조상 -ami-ids는 조상 ID를 표시합니다
    --product-codes는 ami 관련 제품 코드를 표시합니다
    --availability-zone은 ami 배치 영역을 표시합니다

    --instance-id 인스턴스 ID를 표시합니다
    -인스턴스 유형 인스턴스 유형을 표시합니다

    --local-hostname은 로컬 호스트 이름을 표시합니다
    --public-hostname은 공개 호스트 이름을 표시합니다

    --local-ipv4는 로컬 ipv4 ip 주소를 표시합니다
    --public-ipv4는 공개 ipv4 ip 주소를 표시합니다

    --block-device-mapping 블록 장치 ID를 표시합니다
    --security-groups는 보안 그룹을 표시합니다

    --mac 인스턴스 mac 주소를 표시합니다
    --profile 인스턴스 프로파일을 표시합니다
    -인스턴스 액션은 인스턴스 액션을 표시

    --public-keys는 openssh 공개 키를 표시합니다
    --user-data 사용자 데이터를 표시합니다 (실제로는 메타 데이터가 아님).

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

.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]

파워 쉘 사람들을 위해 :

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

이 게시물을 참조하십시오 -주어진 URL의 IP 주소는 일정하지만 (처음에는 혼란 스럽지만) 반환 된 데이터는 인스턴스에 따라 다릅니다.


모든 ec2 머신의 경우 instance-id는 파일에서 찾을 수 있습니다.

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

다음 명령을 실행하여 인스턴스 ID를 얻을 수도 있습니다.

    ec2metadata --instance-id

보다 현대적인 솔루션.

Amazon Linux에서 ec2-metadata 명령이 이미 설치되어 있습니다.

터미널에서

ec2-metadata -help

사용 가능한 옵션을 제공합니다

ec2-metadata -i

돌아올 것이다

instance-id: yourid

그냥 입력 :

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다음 이 있습니다 .

자바에서 :

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

스칼라에서 :

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

파이썬을 사용하여 사용 가능한 모든 인스턴스 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 메타 데이터 서비스 ( https://bitbucket.org/dgc/ec2mdfs) 에 대한 액세스를 제공하기 위해 FUSE 파일 시스템을 작성했습니다 . 모든 사용자 지정 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심볼릭 링크를 확인하면 인스턴스 ID가 /var/lib/cloud/instances/{instance-id}어디에 있는지 가리켜 야합니다 {instance_id}.


메타 데이터 매개 변수를 전달하여 메타 데이터를 GET하기 위해 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 요청에 대해서는 요금이 청구되지 않습니다.

그밖에

설명서에 언급 된대로 curl을 사용하여 실행중인 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'];

@ 존당 편집


이것을 실행하십시오 :

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

AWS에서 제공하는 다양한 유형의 속성을 볼 수 있습니다.

더 보려면이 링크를 사용하십시오


EC2 리소스와 관련된 모든 메타 데이터는 다음 명령을 실행하여 EC2 인스턴스 자체에서 액세스 할 수 있습니다.

곱슬 곱슬하다 :

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

귀하의 경우 : " 메타 데이터 요청 "은 instance-id 이어야합니다 . " api-version "은 일반적으로 사용 가능한 최신 버전 입니다.

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

ami-id, ami-launch-index, ami-manifest-path, block-device-mapping /, 호스트 이름, iam /, 인스턴스 작업, instance-id, 인스턴스 유형, 로컬 호스트 이름, local-ipv4, mac, 측정 항목 /, 네트워크 /, 게재 위치 /, 프로필, 공개 호스트 이름, 공개 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 Elastic Beanstalk eb cli run의 경우 eb tags --list

참고 URL : https://stackoverflow.com/questions/625644/how-to-get-the-instance-id-from-within-an-ec2-instance



반응형