search

Home  >  Q&A  >  body text

How to get instance metadata using PHP AWS SDK

<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粉032649413P粉032649413533 days ago729

reply all(1)I'll reply

  • P粉360266095

    P粉3602660952023-08-28 00:00:45

    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";

    reply
    0
  • Cancelreply