I would like to get the instance metadata (like AZ) for the current EC2, using AWS SDK.
I was able to find an alternative solution, but it is not using the SDK just a file_get_contents
How is it possible with the SDK?
CodePudding user response:
By current EC2 instance, are you referring to PHP code running on an EC2, and you would like to inject that metadata into some variables for use?
Or do you mean you have an object created with the PHP SDK such as with something like:
$ec2Client = new Aws\Ec2\Ec2Client([
'region' => 'us-east-1',
'version' => 'latest'
]);
If you mean the second way, you can access that data through describeInstances
like this:
$result = $ec2Client->describeInstances();
echo "Instances: \n";
foreach ($result['Reservations'] as $reservation) {
foreach ($reservation['Instances'] as $instance) {
echo "InstanceId: {$instance['InstanceId']} - {$instance['State']['Name']} \n";
echo "Availability Zone: {$instance['Placement']['AvailabilityZone']} \n";
}
echo "\n";
}
You can also filter by adding parameters to the method call such as by type or instanceId.
If you're just running PHP code on the EC2 instance and you want that info, you can check out this page for some options: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
CodePudding user response:
I don't think this is possible at all. IMDSv2 info like AZ, instance-id, instance-type, etc is readable via https://169.254.169.254 and if you look into the source code for the SDK, it only pulls temporary credentials via IMDSv2 (https://github.com/aws/aws-sdk-php/search?q=169.254) and does not allow arbitrary IMDSv2 queries.
Unless I'm missing something, you need to pull this data yourself or use some 3rd-party library which does that for you in PHP.