This is something simple, yet I thought it could be of use for someone working with Amazon's EC2 instances via PHP. It requires Amazon's AWSSDKforPHP, which is one of the best APIs for AWS to date in my humble opinion.
What this snippet does is it lists your EC2 instances with their Name tag and public dns name. It could be an example on how to iterate through the resulting object that the describe_instances method returns.
Note that for CFSimpleXML objects the children() method provides the array that can be walked using foreach. In the case of objects, it is ok to use reserved words as member variable names - hence $tag->key will work great, and we don't have to revert to something like $tag->{"key"}.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // create a new EC2 object $ec2 = new AmazonEC2(); $instances = $ec2 ->describe_instances(); if ( $instances ->isOK()) { foreach ( $instances ->body->reservationSet->children() as $reservationItem ) { foreach ( $reservationItem ->instancesSet->children() as $instanceItem ) { // only instances that are up have a public dns name // if the instance is not running, we'll assume it's down $dnsName = "down" ; if ( $instanceItem ->instanceState->name == "running" ) $dnsName = $instanceItem ->dnsName; // lets go through the tags and find the value of the one with // the key "Name" $instanceName = "" ; foreach ( $instanceItem ->tagSet->children() as $tag ) if ( $tag ->key == "Name" ) { $instanceName = $tag ->value; break ; } echo ( $instanceName . ": " . $dnsName . "\n" ); } } } |
The latest docs will be of great help if you want more information on returned data types (see Core Utilities).
No comments:
Post a Comment