Skip to content

Instantly share code, notes, and snippets.

@matejskubic
Created March 20, 2012 10:30
Show Gist options
  • Save matejskubic/2133982 to your computer and use it in GitHub Desktop.
Save matejskubic/2133982 to your computer and use it in GitHub Desktop.
Maps Elastic IP from AWS EC2 tag AutoMapElasticIP to current instance
<?php
/*
//Required Permissions for IAM
{
"Statement": [
{
"Action": [
"ec2:AssociateAddress",
"ec2:DescribeAddresses",
"ec2:DescribeTags"
],
"Effect": "Allow",
"Resource": [
"*"
]
}
]
}
*/
error_reporting(-1);
$instanceId=exec('ec2metadata --instance-id');
print_r($instanceId);
require_once 'AWSSDKforPHP/sdk.class.php';
$ec2 = new AmazonEC2();
$ec2->set_region(AmazonEC2::REGION_EU_W1);
//$ec2->hostname = 'ec2.eu-west-1.amazonaws.com';
echo("\nUsing hostname: ".$ec2->hostname);
//$r=$ec2->describe_addresses();
//print_r($r->body->addressesSet);
$tagResponse = $ec2->describe_tags(array(
'Filter'=>array(
'Name' => 'key',
'Value' => 'AutoMapElasticIP',
),
)
);
print_r($tagResponse->body);
$tagItem = $tagResponse->body->tagSet->item;
if(!$tagItem)
{
echo 'Tag with name "AutoMapElasticIP" does not exists';
exit(1);
}
$addrResponse=$ec2->describe_addresses(
array(
'PublicIp' => $tagItem->value,
)
);
print_r($addrResponse->body);
$addrItem = $addrResponse->body->addressesSet->item;
if($tagItem->resourceId==$instanceId && $addrItem->instanceId==$instanceId)
{
echo "\nIP ".$tagItem->value." is already mapped to ".$instanceId.".\n";
exit(0);
}
$assocResponse=$ec2->associate_address($instanceId,$tagItem->value);
print_r($assocResponse->body);
echo "\n\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment