Musings on code and life
Display Amazon Instances
We use a *lot* of AWS servers and I put together a simple Razor Webpage that would display all of the Amazon instances for a given AccessKey and SecretKey.
@using Amazon
@using Amazon.EC2.Model
@{
//NUGET: AWSSDK
var tags = new[] { "Name", "Contact", "Owner", "Use", "Note" };
var accounts = new[]
{
new { Name = "Development", AccessKey = "", SecretKey = "" },
new { Name = "Production", AccessKey = "", SecretKey = "" },
};
}
<!DOCTYPE html>
<html>
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table class="table table-striped">
@foreach (var acct in accounts)
{
<thead>
<tr>
<th colspan="@(tags.Length+4)" class="alert alert-info lead text-center"><strong>@acct.Name</strong></th>
</tr>
<tr>
<th>ReservationId</th>
<th>PublicDnsName</th>
<th>IpAddress</th>
@foreach (var key in tags)
{
<th>@key</th>
}
<th>Tags</th>
</tr>
</thead>
<tbody>
@foreach (var resv in GetReservations(acct.AccessKey, acct.SecretKey))
{
foreach (var inst in resv.Instances)
{
<tr>
<td>@resv.ReservationId</td>
<td>@inst.PublicDnsName</td>
<td>
@inst.PublicIpAddress<br />
@inst.PrivateIpAddress
</td>
@foreach (var key in tags)
{
<td>@inst.Tags.Where(x => x.Key == key).Select(x => x.Value).SingleOrDefault()</td>
}
<td>
@foreach (var tag in inst.Tags.Where(x => !tags.Contains(x.Key)))
{
<span>@tag.Key</span><text>:</text><span>@tag.Value</span><text>,</text>
}
</td>
</tr>
}
}
</tbody>
}
</table>
</body>
</html>
@functions
{
IEnumerable<Reservation> GetReservations(string accessKey, string secretKey)
{
//REF: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html
using (var ec2 = AWSClientFactory.CreateAmazonEC2Client(accessKey, secretKey, RegionEndpoint.USEast1))
{
//Create instance request
var request = new DescribeInstancesRequest();
var response = ec2.DescribeInstances(request);
return response.Reservations;
}
}
}