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