How to get instance metadata using PHP AWS SDK
P粉032649413
P粉032649413 2023-08-27 11:20:25
0
1
611
<p>I want to use the AWS SDK to get the instance metadata (eg AZ) of the current EC2 instance. I found an alternative, but it doesn't use the SDK, just <code>file_get_contents</code>. How to use SDK to implement this function? </p>
P粉032649413
P粉032649413

reply all(1)
P粉360266095

The solution proposed by JasonQ-AWS is very useful for getting the information of all instances and applications in the account. However, it does not tell you information describing the instance in which the current process is executing.

In order to achieve this, you need to use IMDSv2, which requires two CURL commands, the first to get the token and the second to get the actual metadata of the current instance.

In PHP, the code can be:

$ch = curl_init();

// 获取有效的令牌
$headers = array (
        'X-aws-ec2-metadata-token-ttl-seconds: 10' );
$url = "http://169.254.169.254/latest/api/token";

curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "PUT" );
curl_setopt( $ch, CURLOPT_URL, $url );
$token = curl_exec( $ch );

echo "<p> TOKEN :" . $token;

// 获取当前实例的元数据
$headers = array (
        'X-aws-ec2-metadata-token: '.$token );
$url = "http://169.254.169.254/latest/dynamic/instance-identity/document";

curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "GET" );
$result = curl_exec( $ch );

echo "<p> RESULT :" . $result;

You only need to extract the information you need. You can also request unique information using a more specific URL, such as instance ID:

$url = "http://169.254.169.254/latest/meta-data/instance-id";
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template