Skip to content

Instantly share code, notes, and snippets.

@justinyoo
Created May 3, 2017 14:41
Show Gist options
  • Save justinyoo/4caea4219c67a88abee3442a47cc969f to your computer and use it in GitHub Desktop.
Save justinyoo/4caea4219c67a88abee3442a47cc969f to your computer and use it in GitHub Desktop.
Know Your Cloud Resource Costs on Azure
public async Task<IEnumerable<ResourceGroupOwner>> GetResourceGroupOwnersAsync(DateTime dateStart, DateTime dateEnd, bool runEntirePeriod, decimal threshold)
{
var costs = await this._dbContext.ResourceGroupCostHistories
.ToListAsync().ConfigureAwait(false);
...
var owners = costs.GroupBy(
p => new
{
Subscription = p.Subscription,
ResourceGroupName = p.ResourceGroupName,
Owners = p.Owners
})
.Select(
p => new ResourceGroupOwner()
{
Subscription = p.Key.Subscription,
SubscriptionId = p.OrderByDescending(q => q.DateStart).First().SubscriptionId,
ResourceGroupName = p.Key.ResourceGroupName,
Owners = p.Key.Owners,
Cost = p.Sum(q => q.Cost),
TotalSpendLimit = p.OrderByDescending(q => q.DateStart).First().TotalSpendLimit,
DailySpendLimit = p.OrderByDescending(q => q.DateStart).First().DailySpendLimit,
OverspendAction = p.OrderByDescending(q => q.DateStart).First().OverspendAction
})
.Where(p => p.Owners != null);
// Total spend limit
if (runEntirePeriod)
{
owners = owners.Where(p => p.TotalSpendLimit > 0.00M);
// Threshold
owners = threshold < 1.00M
? owners.Where(p => p.TotalSpendLimit * threshold <= p.Cost && p.Cost < p.TotalSpendLimit)
: owners.Where(p => p.Cost >= p.TotalSpendLimit * threshold);
}
else
{
// Daily spend limit
owners = owners
.Where(p => p.DailySpendLimit > 0.00M)
.Where(p => p.Cost > p.DailySpendLimit);
}
owners = owners.OrderBy(p => p.Owners)
.ThenBy(p => p.ResourceGroupName)
.ToList();
return owners;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment