Skip to content

Instantly share code, notes, and snippets.

@zircote
Created May 31, 2011 02:55
Show Gist options
  • Save zircote/999797 to your computer and use it in GitHub Desktop.
Save zircote/999797 to your computer and use it in GitHub Desktop.
A Zend Framework class to fetch EC2 instance meta-data
#!/usr/bin/env php
<?php
require_once 'Zircote/Service/Ec2.php';
$ec2 = new Zircote_Service_Ec2();
echo $ec2->__get($_SERVER['argv'][1]);
<?php
class Zircote_Service_Ec2
{
/**
*
* @var Zend_Http_Client
*/
protected $_httpClient;
protected $_endpoint = 'http://169.254.169.254';
protected $_methods = array(
'amiID' => '/latest/meta-data/ami-id',
'amiLaunchIndex' => '/latest/meta-data/ami-launch-index',
'amiManifestPath' => '/latest/meta-data/ami-manifest-path',
'ancestorAmiIds' => '/latest/meta-data/ancestor-ami-ids',
'blockDeviceMapping' => '/latest/meta-data/block-device-mapping/',
'hostname' => '/latest/meta-data/hostname',
'instanceAction' => '/latest/meta-data/instance-action',
'instanceId' => '/latest/meta-data/instance-id',
'instanceType' => '/latest/meta-data/instance-type',
'kernelId' => '/latest/meta-data/kernel-id',
'localHostname' => '/latest/meta-data/local-hostname',
'localIpv4' => '/latest/meta-data/local-ipv4',
'placement' => '/latest/meta-data/placement/',
'publicHostname' => '/latest/meta-data/public-hostname',
'publicIpv4' => '/latest/meta-data/public-ipv4',
'publicKeys' => '/latest/meta-data/public-keys/',
'ramdiskId' => '/latest/meta-data/ramdisk-id',
'reservationId' => '/latest/meta-data/reservation-id',
'securityGroups' => '/latest/meta-data/security-groups',
'userData' => '/latest/user-data',
);
public function __construct ()
{
require_once 'Zend/Http/Client.php';
$this->_httpClient = new Zend_Http_Client($this->_endpoint);
}
public function __get($name)
{
if(!array_key_exists($name, $this->_methods)){
throw new Exception(sprintf('value [%s] does not exist', $name));
}
$this->_httpClient->getUri()->setPath($this->_methods[$name]);
$result = $this->_httpClient->request();
if($result->getStatus() == 200){
return $result->getBody();
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment