Jak uzyskać id instancji z instancji ec2?
Jak mogę dowiedzieć się instance id
instancji ec2 z wnętrza instancji ec2?
30 answers
Patrz dokumentacja EC2 na ten temat .
Run:
wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
Jeśli potrzebujesz programowego dostępu do identyfikatora instancji z poziomu skryptu,
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: $?\"`"
Oto przykład bardziej zaawansowanego użycia (pobranie ID instancji, strefy dostępności i regionu itp.):
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:'`"
Możesz również użyć curl
zamiast wget
, w zależności od tego, co jest zainstalowane na twojej platformie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-18 23:37:28
Na Amazon Linux AMIs można zrobić:
$ ec2-metadata -i
instance-id: i-1234567890abcdef0
Lub, na Ubuntu i innych Linuksach, ec2metadata --instance-id
(to polecenie może nie być instalowane domyślnie na ubuntu, ale możesz dodać je za pomocą sudo apt-get install cloud-utils
)
Jak sama nazwa wskazuje, możesz użyć polecenia, aby uzyskać inne przydatne metadane.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-29 13:09:18
Na Ubuntu możesz:
sudo apt-get install cloud-utils
I wtedy możesz:
EC2_INSTANCE_ID=$(ec2metadata --instance-id)
Możesz uzyskać większość metadanych powiązanych z instancją w ten sposób:
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)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-15 12:26:16
Użyj adresu URL /dynamic/instance-identity/document
, jeśli chcesz również zadać więcej pytań niż tylko identyfikator instancji.
wget -q -O - http://169.254.169.254/latest/dynamic/instance-identity/document
Dzięki temu uzyskasz JSON takie dane - tylko z pojedynczym żądaniem .
{
"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"
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-28 00:20:10
Na AWS Linux:
ec2-metadata --instance-id | cut -d " " -f 2
Wyjście:
i-33400429
Użycie w zmiennych:
ec2InstanceId=$(ec2-metadata --instance-id | cut -d " " -f 2);
ls "log/${ec2InstanceId}/";
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-14 10:29:33
Dla .NET
Osób:
string instanceId = new StreamReader(
HttpWebRequest.Create("http://169.254.169.254/latest/meta-data/instance-id")
.GetResponse().GetResponseStream())
.ReadToEnd();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-08 20:07:43
Dla Pythona:
import boto.utils
region=boto.utils.get_instance_metadata()['local-hostname'].split('.')[1]
Co sprowadza się do jedynki:
python -c "import boto.utils; print boto.utils.get_instance_metadata()['local-hostname'].split('.')[1]"
Zamiast local_hostname można również użyć public_hostname, lub:
boto.utils.get_instance_metadata()['placement']['availability-zone'][:-1]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-20 03:48:02
Dla wszystkich maszyn ec2, instancja-id znajduje się w pliku:
/var/lib/cloud/data/instance-id
Można również uzyskać id instancji, uruchamiając następujące polecenie:
ec2metadata --instance-id
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-01 09:52:39
Dla ludzi powershell:
(New-Object System.Net.WebClient).DownloadString("http://169.254.169.254/latest/meta-data/instance-id")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-13 18:47:33
Zobacz Ten post - zauważ, że adres IP w podanym adresie URL jest stały( co na początku mnie myliło), ale zwracane dane są specyficzne dla Twojej instancji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-09 21:04:19
Dla 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]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-15 01:13:54
Bardziej współczesne rozwiązanie.
Z Amazon Linux polecenie ec2-metadata jest już zainstalowane.
Z terminala
ec2-metadata -help
Da ci dostępne opcje
ec2-metadata -i
Powróci
instance-id: yourid
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-18 10:06:03
Wpisz:
ec2metadata --instance-id
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-21 10:32:43
Możesz spróbować tego:
#!/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]\)"`
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-11 16:24:16
Najnowszy SDK Javy ma EC2MetadataUtils
:
W Języku Java:
import com.amazonaws.util.EC2MetadataUtils;
String myId = EC2MetadataUtils.getInstanceId();
W Scali:
import com.amazonaws.util.EC2MetadataUtils
val myid = EC2MetadataUtils.getInstanceId
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-18 13:12:06
Klasa c#. Net, którą napisałem dla metadanych EC2 z http api. W razie potrzeby rozbuduję go o funkcjonalność. Możesz z nim biegać, jeśli chcesz.
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
*************************************************************/
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-04 03:07:08
Dla C++ (używają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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-03 19:13:24
Po prostu sprawdź var/lib/cloud/instance
dowiązanie symboliczne, powinno wskazywać na /var/lib/cloud/instances/{instance-id}
Gdzie {instance_id}
jest Twoim ID instancji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-09 15:50:10
Jeśli chcesz uzyskać listę wszystkich instancji w Pythonie, oto kod:
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'])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-28 06:14:41
FWIW napisałem system plików FUSE, aby zapewnić dostęp do usługi metadanych EC2: https://bitbucket.org/dgc/ec2mdfs . Uruchamiam to na wszystkich niestandardowych ami; pozwala mi to używać tego idiomu: cat/ec2 / meta-data / ami-id
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-29 22:15:05
W Go możesz użyć pakietu 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
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-23 22:29:15
W pytaniu, które wspomniałeś o użytkowniku jako root, jedną rzeczą, którą powinienem wspomnieć, jest to, że identyfikator instancji nie jest zależny od użytkownika.
For Node developers,
var meta = new AWS.MetadataService();
meta.request("/latest/meta-data/instance-id", function(err, data){
console.log(data);
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-16 09:45:07
Aby uzyskać metadane instancji użyj
wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-31 10:54:34
Możesz po prostu wysłać żądanie HTTP, aby uzyskać metadane, przekazując parametry metadanych.
curl http://169.254.169.254/latest/meta-data/instance-id
Lub
wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
Nie będą naliczane opłaty za żądania HTTP w celu uzyskania metadanych i danych użytkownika.
Else
Możesz użyć narzędzia zapytań o metadane instancji EC2, które jest prostym skryptem bash, który używa curl do odpytywania metadanych instancji EC2 z uruchomionej instancji EC2, jak wspomniano w dokumentacji.
Pobierz narzędzie:
$ wget http://s3.amazonaws.com/ec2metadata/ec2-metadata
Teraz uruchom polecenie, aby uzyskać wymagane dane.
$ec2metadata -i
Zobacz:
Http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
Cieszę Się, Że Mogę Pomóc.. :)Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-10 22:52:57
Alternatywne podejście do PHP:
$instance = json_decode(file_get_contents('http://169.254.169.254/latest/dynamic/instance-identity/document'),true);
$id = $instance['instanceId'];
print_r($instance);
To dostarczy wiele danych o instancji, wszystkie ładnie zapakowane w tablicę, bez zewnętrznych zależności. Ponieważ jest to dla mnie Prośba, która nigdy nie zawiodła lub nie opóźniła, powinno być bezpiecznie zrobić to w ten sposób, w przeciwnym razie wybrałbym curl()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-06 01:44:53
Dla PHP:
$instance = json_decode(file_get_contents('http://169.254.169.254/latest/dynamic/instance-identity/document));
$id = $instance['instanceId'];
Edit per @ John
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-08 15:54:13
Uruchom to:
curl http://169.254.169.254/latest/meta-data/
Będziesz mógł zobaczyć różne typy atrybutów, które są dostarczane przez aws.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-18 11:46:45
Wszystkie metadane związane z zasobem EC2 mogą być dostępne przez samą instancję EC2 za pomocą wykonywanego polecenia:
CURL:
http://169.254.169.254/<api-version>/meta-data/<metadata-requested>
W Twoim przypadku:" metadane-requested " powinno być instance-id , "api-version " jest zwykle najnowszą , która może być użyta.
Dodatkowa uwaga: możesz również uzyskać informacje dotyczące poniższych atrybutów EC2, korzystając z powyższego dowództwo.
Ami-id, ami-launch-index, ami-manifest-path, Block-device-mapping/, Nazwa hosta, iam/, instancja-działanie, instance-id, Typ instancji, local-hostname, lokalne-ipv4, mac, metryki/, sieć/, lokata/, profil, public-hostname, public-ipv4, public-keys/, rezerwacja-id, grupy bezpieczeństwa, usługi/,
Aby uzyskać więcej informacji, kliknij ten link: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-31 10:51:08
Dla instancji Windows:
(wget http://169.254.169.254/latest/meta-data/instance-id).Content
Lub
(ConvertFrom-Json (wget http://169.254.169.254/latest/dynamic/instance-identity/document).Content).instanceId
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-29 07:54:04
Dla AWS elastic beanstalk eb CLI run eb tags --list
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-01 18:20:02