Home » Php » php – How to programmatically get public dns of an instance?

php – How to programmatically get public dns of an instance?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is there a way to get the public DNS of an EC2 instance using PHP amazon SDK (or amazon’s API command line tools)?

I tried this PHP code (among others) but it won’t work:

require_once '/full/path/sdk.class.php';
$ec2      = new AmazonEC2();
$response = $ec2->describe_regions();
print_r($response);

and also

require_once '/full/path/sdk.class.php';
$ec2      = new AmazonEC2();
$response = $ec2->describe_instances(array(
    'Filter' => array(
        array('Name' => 'availability-zone', 'Value' => 'eu-west-1')
    )
));

print_r($response);

but I can’t see the public dns in the response

How to&Answers:

Apparently you’d like to retrieve your Amazon EC2 instance in region eu-west-1 (which isn’t a correct value for ‘availability-zone’ btw.). However, you are not specifying any region and all services default to the US-East region, see the AWS team response to the related question describeInstances() is only giving me instances in us-east:

While you can’t grab data for all regions in a single call, you can
call the describe_instances() method in each region.

$ec2 = new AmazonEC2();
$ec2->set_region(AmazonEC2::REGION_US_W1); // US-West 1

$response = $ec2->describe_instances();

Using this code with the appropriate constant for your region of choice (e.g. AmazonEC2::REGION_EU_W1) should yield the desired result.

Answer:

If you’re running this on the instance itself, you can hit AWS’s internal metadata endpoint:

$hostname = file_get_contents('http://169.254.169.254/latest/meta-data/public-hostname');

http://169.254.169.254/latest/meta-data/ will give you a list of the various metadata available to you. Currently:

ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
hostname
instance-action
instance-id
instance-type
kernel-id
local-hostname
local-ipv4
mac
metrics/
network/
placement/
profile
public-hostname
public-ipv4
public-keys/
reservation-id
security-groups