简体   繁体   English

通过PHP获取Amazon EC2实例ID

[英]Get Amazon EC2 Instance ID via PHP

I'm looking to create a PHP script that will echo the unique ID of an Amazon EC2 instance. 我正在寻找创建一个PHP脚本,它将回显Amazon EC2实例的唯一ID。 Anyone know how to do this? 有人知道怎么做吗?

Found a way via command line: http://af-design.com/blog/2010/07/27/testing-your-aws-elastic-load-balancer/ 通过命令行找到方法: http//af-design.com/blog/2010/07/27/testing-your-aws-elastic-load-balancer/

Can I just use PHP w/ CURL to submit the query? 我可以使用PHP w / CURL提交查询吗?

If the entire goal of your PHP script is to run another command, why not just run the other command directly? 如果PHP脚本的整个目标是运行另一个命令,为什么不直接运行另一个命令? Why wrap it in PHP? 为什么用PHP包装?

If you need to use PHP for some reason (eg, to do something with the instance id other than to echo it out, you could improve performance by using PHP's built in HTTP ability instead of running another process: 如果由于某种原因需要使用PHP(例如,除了回应它之外,还要使用实例id做某事),可以通过使用PHP的内置HTTP功能而不是运行其他进程来提高性能:

#!/usr/bin/php
<?php
$instance_id = file_get_contents("http://instance-data/latest/meta-data/instance-id");
echo $instance_id, "\n";
?>

If you can get the instance id via the command line, you can get the results of the latter in PHP using the PHP's exec function. 如果您可以通过命令行获取实例ID,则可以使用PHP的exec函数在PHP中获取后者的结果。 When you get the result, just echo it. 当你得到结果时,只需回应它。

$instance_id = exec([your command here]);
echo $instance_id;

Alternatively, after reading the post you linked to, you can also do it this way: 或者,在阅读您链接的帖子后,您也可以这样做:

$instance_id = file_get_contents(
     "http://169.254.169.254/latest/meta-data/instance-id");
echo $instance_id;

You can use shell_exec to get the instance-id if you are using Amazon Linux AMI. 如果您使用的是Amazon Linux AMI,则可以使用shell_exec获取instance-id。

$instance_id = shell_exec('ec2-metadata --instance-id 2> /dev/null | cut -d " " -f 2');
// if its not set make it 0
if (empty($instance_id)) {
    $instance_id = 0;
}
echo $instance_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM