كيفية الحصول على معرف المثيل من داخل مثيل ec2؟
-
05-07-2019 - |
سؤال
كيف يمكنني معرفة instance id
لمثيل ec2 من داخل مثيل ec2؟
المحلول
الوثائق EC2 حول هذا الموضوع أ >.
وتشغيل:
wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
إذا كنت بحاجة إلى الوصول إلى programatic معرف مثيل من داخل النص،
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: $?\"`"
ومثال على استخدام أكثر تقدما (استرداد معرف مثيل وكذلك منطقة توافر والمنطقة، الخ.):
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
، اعتمادا على ما هو مثبت على النظام الأساسي الخاص بك.
نصائح أخرى
في الأمازون لينكس بعثة الاتحاد الأفريقي يمكنك القيام به:
$ 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 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
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 لينكس:
و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")
هذا المنصب - نلاحظ أن عنوان IP في URL معين هو ثابت (التي الخلط لي في البداية)، ولكن البيانات التي تم إرجاعها غير محددة بمثيل
وهناك حل أكثر معاصرة.
ومن الأمازون لينكس تثبيت الأمر EC2 الفوقية بالفعل.
ومن محطة
ec2-metadata -help
هل تعطيك الخيارات المتاحة
ec2-metadata -i
وسيعود
instance-id: yourid
مجرد نوع:
ec2metadata --instance-id
لكافة الأجهزة EC2، مثيل معرف يمكن العثور عليها في الملف:
/var/lib/cloud/data/instance-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]
وA C # .NET الطبقة كتبت عن التعريف EC2 من المعهد HTTP. سأبني هذا الامر مع وظائف حسب الحاجة. يمكنك تشغيل مع ذلك إذا كنت ترغب في ذلك.
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
*************************************************************/
}
}
وأحدث جافا SDK لديها EC2MetadataUtils
:
في جاوة:
import com.amazonaws.util.EC2MetadataUtils;
String myId = EC2MetadataUtils.getInstanceId();
في سكالا:
import com.amazonaws.util.EC2MetadataUtils
val myid = EC2MetadataUtils.getInstanceId
لسي ++ (باستخدام الضفيرة):
#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
إذا كنت ترغب في الحصول على كل ما هو متاح لائحة المثال معرف باستخدام بيثون هنا هو رمز:
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 كتبت نظام الملفات FUSE لتوفير الوصول إلى خدمة الفوقية EC2: https://bitbucket.org/dgc / ec2mdfs . I تشغيل هذا على كل بعثة الاتحاد الأفريقي مخصص؛ فإنه يتيح لي الفرصة لاستخدام هذا المصطلح: القط / EC2 / البيانات الفوقية / عامي معرف
في العودة يمكنك استخدام 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
، ينبغي أن نشير إلى /var/lib/cloud/instances/{instance-id}
حيث {instance_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
ولن يتم محاسبتك لطلبات HTTP للحصول على معلومات تقنية وبيانات المستخدمين.
وعدا ذلك
ويمكنك استخدام EC2 مثيل أداة استعلام الفوقية التي هو السيناريو باش بسيط يستخدم حليقة للاستعلام عن بيانات ميتا المثال EC2 من داخل مثيل EC2 تشغيل كما هو مذكور في الوثائق.
وتحميل الأداة:
$ wget http://s3.amazonaws.com/ec2metadata/ec2-metadata
والآن تشغيل الأمر للحصول على البيانات المطلوبة.
$ec2metadata -i
وراجع:
HTTP: //docs.aws.amazon كوم / AWSEC2 / احدث / دليل المستخدم / EC2 مثيل-metadata.html
https://aws.amazon.com/items/1825؟externalID=1825
وسعيد للمساعدة ..:)
لقد ذكرت في السؤال المستخدم كجذر، وهناك شيء واحد يجب أن أذكره وهو أن معرف المثيل لا يعتمد على المستخدم.
ل العقدة المطورين,
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);
سيوفر ذلك الكثير من البيانات حول المثيل، وكلها معبأة بشكل جيد في مصفوفة، ولا توجد تبعيات خارجية.نظرًا لأنه طلب لم يفشل أو يتأخر أبدًا بالنسبة لي، فيجب أن يكون من الآمن القيام بذلك بهذه الطريقة، وإلا فإنني سأختار cur()
ل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/
وسوف تكون قادرا على رؤية أنواع مختلفة من الصفات التي يتم توفيرها من قبل أوس.
يمكن الوصول إلى جميع البيانات التعريفية المتعلقة بمورد EC2 بواسطة مثيل EC2 نفسه بمساعدة الأمر التالي الذي يتم تنفيذه:
لفة :
http://169.254.169.254/<api-version>/meta-data/<metadata-requested>
لحالتك:"طلب البيانات الوصفية" يجب ان يكون معرف المثيل , "نسخة واجهة برمجة التطبيقات" عادة أحدث ذلك يمكن استخدامه.
مذكرة إضافية:يمكنك أيضًا الحصول على معلومات تتعلق بسمات EC2 أدناه باستخدام الأمر أعلاه.
عامي معرف ، مؤشر إطلاق عامي ، عامي واضح المسار ، كتلة تعيين الجهاز / ، اسم المضيف, IAM/, مثال العمل, معرف المثيل, نوع المثيل, اسم المضيف المحلي ، المحلية-IPv4, الماك المقاييس/ شبكة/ التنسيب/ ملف تعريف اسم المضيف العام ، العامة-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
لمثيل ويندوز:
(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 مرنة شجرة الفاصولياء EB CLI تشغيل eb tags --list