Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter EC2 Instance with "DescribeInstanceStatus" routine - AWS SDK

I'm trying to filter EC2 instances using the AWS SDK in .NET and, although I have seen inumerous threads on SO and on other websites of people resolving this issue, nothing I've tried on my end worked.

So, as a last resource, I'm coming to you guys for help. Can anyone shed some light on what I'm missing ? I know it's very likely that I'm doing something stupid, but I can't afford to waste too much time solving this issue.

This is the chunk of code I'm using to filter an EC2 instance (get it's metadata) by it's tag name:

DescribeInstanceStatusRequest req = new DescribeInstanceStatusRequest ();
req.Filters.Add (new Filter() { Name = "tag:Name", Values = new List <string> () { "some_random_name" } });

// Executing request & fetching response
DescribeInstanceStatusResponse resp = m_ec2Client.DescribeInstanceStatus (req);

But I keep on running into this exception:

The filter 'tag:Name' is invalid

I have replaced the filter name ("tag:Name" in the example) by several filters listed in the documentation (e.g. "tag-key", "tag-value", "tag:key=value"), but nothing works.

Thank you all in advance :)

like image 455
ErickR Avatar asked Apr 01 '16 00:04

ErickR


Video Answer


2 Answers

After a more thorough research, I found out that the "DescribeInstanceStatus" routine doesn't support searching by tag, but I found a somewhat "simple" way of doing so. I'll post it in here in case anyone goes through the same situation.

Here's how:

DescribeInstancesRequest req = new DescribeInstancesRequest ();
req.Filters.Add (new Filter () { Name = "tag-value", Values = new List <string> () { "something" }});

// Executing request & fetching response
DescribeInstancesResponse resp = m_ec2Client.DescribeInstances (req);

return resp.Reservations.SelectMany (x => x.Instances).Where (y => y.State.Name == InstanceStateName.Pending || y.State.Name == InstanceStateName.Running).ToList (); {code}

In theory, with this routine you can use any of the filters listed under the "Supported Filters" table in the documentation.

like image 200
ErickR Avatar answered Nov 11 '22 03:11

ErickR


Getting Number of running instance from AWS EC2

DescribeInstancesRequest req = new DescribeInstancesRequest();
req.Filters.Add(new Filter { 
    Name = "instance-state-name", 
    Values = new List<string>() { "running" } 
}); 

DescribeInstancesResponse resp = _amazonEC2Client.DescribeInstances(req);
like image 27
vivek soni Avatar answered Nov 11 '22 01:11

vivek soni