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'])
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
*************************************************************/
}
}
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)
25 回答
对于PHP:
按@John编辑
对于Python:
归结为单线:
您也可以使用public_hostname,而不是local_hostname,而不是:
在Amazon Linux AMI上,您可以:
或者,在Ubuntu和其他一些Linux风格上,
ec2metadata --instance-id
(默认情况下,这个命令可能不会安装在ubuntu上,但你可以用sudo apt-get install cloud-utils
添加它)顾名思义,您也可以使用该命令获取其他有用的元数据 .
对于所有ec2机器,可以在文件中找到instance-id:
您还可以通过运行以下命令来获取实例ID:
更现代的解决方案 .
在Amazon Linux中,已经安装了ec2-metadata命令 .
从终端
将为您提供可用的选项
将返回
见the EC2 documentation on the subject .
跑:
如果您需要从脚本中以编程方式访问实例ID,
更高级用法的示例(检索实例ID以及可用区和区域等):
您也可以使用
curl
而不是wget
,具体取决于您平台上安装的内容 .对于Ruby:
在您提到用户为root的问题中,我应该提到的一件事是实例ID不依赖于用户 .
对于 Node 开发人员,
只需检查
var/lib/cloud/instance
符号链接,它应该指向/var/lib/cloud/instances/{instance-id}
,其中{instance_id}
是您的实例ID .在AWS Linux上:
ec2-metadata --instance-id | cut -d " " -f 2
输出:
i-33400429
在变量中使用:
请参阅this post - 请注意,给定URL中的IP地址是常量(最初使我感到困惑),但返回的数据特定于您的实例 .
你可以试试这个:
如果您希望使用python获取所有可用的实例ID列表,请输入以下代码:
FWIW我写了一个FUSE文件系统来提供对EC2元数据服务的访问:https://bitbucket.org/dgc/ec2mdfs . 我在所有自定义AMI上运行它;它允许我使用这个成语:cat / ec2 / meta-data / ami-id
您可以通过传递元数据参数来发出HTTP请求以获取任何元数据 .
要么
您不会收到HTTP请求以获取元数据和用户数据的费用 .
其他
您可以使用EC2实例元数据查询工具,这是一个简单的bash脚本,它使用curl从正在运行的EC2实例中查询EC2实例元数据,如文档中所述 .
下载工具:
现在运行命令以获取所需数据 .
参考:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
https://aws.amazon.com/items/1825?externalID=1825
乐于帮助.. :)
对
.NET
人:For C++ (使用cURL):
对于powershell人:
只需输入:
我为http api编写的EC2元数据的c#.net类 . 我将根据需要使用功能构建它 . 如果你喜欢它,你可以运行它 .
最新的Java SDK具有
EC2MetadataUtils
:在Java中:
在斯卡拉:
在Go中,您可以使用goamz package .
Here's GetMetaData源码 .
在Ubuntu上你可以:
然后你可以:
您可以通过以下方式获取与实例关联的大多数元数据:
Alternative approach for PHP:
这将提供有关该实例的大量数据,所有数据都很好地打包在一个数组中,没有外部依赖关系 . 因为这是一个永远不会失败或延迟的请求,所以这样做应该是安全的,否则我会去卷曲()
如果您还需要查询的不仅仅是实例ID,请使用
/dynamic/instance-identity/document
URL .wget -q -O - http://169.254.169.254/latest/dynamic/instance-identity/document
这样就可以得到 JSON 这样的数据 - 只有 single request .