How to get instance metadata using PHP AWS SDK
P粉032649413
2023-08-27 11:20:25
<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>
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:
You only need to extract the information you need. You can also request unique information using a more specific URL, such as instance ID: