Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically get public dns of an instance?

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

like image 736
style-sheets Avatar asked Apr 17 '12 20:04

style-sheets


People also ask

How do I find my EC2 instance metadata?

To view instance metadata, you can only use the link-local address of 169.254. 169.254 to access. Requests to the metadata via the URI are free, so there are no additional charges from AWS. Using the curl tool on Linux or the PowerShell cmdlet Invoke-WebRequest on Windows, you will first create your token.


2 Answers

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
like image 171
ceejayoz Avatar answered Nov 08 '22 10:11

ceejayoz


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.

like image 44
Steffen Opel Avatar answered Nov 08 '22 10:11

Steffen Opel