Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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