PHP and AWS - Get an EC2 Instance Using a Tag

I am trying to get EC2 instances by tag via PHP. I can create servers with tags, I can get servers with tag data, but if what I want to do is get one of these tags, I can’t find examples.

It works:

if ($server_group != '') $filter[] = array('Name' => 'tag-value','Value' => $server_group); $response = $ec2->describe_instances(array('Filter' => $filter)); 

However, the problem is that it will find any tag with the value that I assigned to the $ server_group variable, whether the tag is correct or not. I can, of course, just be careful about how I assign tag values, but this is not bullet proof.

Alternative syntax is explained in the docs:

Example. To specify only those resources to which the Navalue = X tag has been assigned, specify:

 Filter.1.Name=tag:Purpose Filter.1.Value.1=X 

However, they do not give examples. I thought it would be:

 $filter[] = array('Filter.1.Name','Value' => 'tag:Group'); $filter[] = array('Name' => 'Filter.1.Value.1','Value' => $server_group); 

However, this does not seem to work - I received nothing.

Has anyone done this? Is there a working example that they can use? Perhaps I did not ask the right questions on Google - there are many examples of how to create tags, but not how to get them.

+4
source share
1 answer

We recently needed to write a script to easily close all EC2 instances in our QA environment. We have an environment tag that stands for DEV, PRD, or QA. Here is a code snippet demonstrating how we filtered through the API:

 <?php $aws = \Aws\Common\Aws::factory(array( 'key' => $key, 'secret' => $secret, 'region' => $region )); $ec2 = $aws->get('ec2'); $args = array( 'Filters' => array( array('Name' => 'tag:Environment', 'Values' => array('QA') ) ) ); $results = $ec2->describeInstances($args); $reservations = $results['Reservations']; foreach ($reservations as $reservation) { $instances = $reservation['Instances']; foreach ($instances as $instance) { $instanceName = ''; foreach ($instance['Tags'] as $tag) { if ($tag['Key'] == 'Name') { $instanceName = $tag['Value']; } } if ($instance['State']['Name'] == \Aws\Ec2\Enum\InstanceStateName::RUNNING){ $shutdownInstances['InstanceIds'][] = $instance['InstanceId']; } } } $results = $ec2->stopInstances($shutdownInstances); $hipURL = "http://api.hipchat.com/v1/rooms/message?auth_token=$token&room_id=$roomId&from=$from&message=QA%20has%20been%20told%20to%20shutdown."; $result = file_get_contents($hipURL); 

We use this in the cron job to ensure that QA shuts down every night, since no one uses it overnight, and it saves us a few dollars so it doesn't work.

To rewrite your search filter for all target tags with an X value:

 'Filters' => array( array('Name' => 'tag:Purpose', 'Values' => array('X') ) ) 
+4
source

All Articles