Skip to content

Instantly share code, notes, and snippets.

@mlabouardy
Created February 25, 2020 15:36
Show Gist options
  • Save mlabouardy/e16fe90bf5348cc6e38f0025bb4d7291 to your computer and use it in GitHub Desktop.
Save mlabouardy/e16fe90bf5348cc6e38f0025bb4d7291 to your computer and use it in GitHub Desktop.
func getDailyCost(dependency Dependency) (map[time.Time]float64, error) {
currentTime := time.Now().Local()
start := currentTime.AddDate(0, 0, -7).Format("2006-01-02")
end := currentTime.Format("2006-01-02")
layoutISO := "2006-01-02"
datapoints := make(map[time.Time]float64, 0)
filter := costexplorer.Expression{}
if len(dependency.Name) != 0 {
filter = costexplorer.Expression{
And: []costexplorer.Expression{
costexplorer.Expression{
Dimensions: &costexplorer.DimensionValues{
Key: costexplorer.DimensionService,
Values: []string{dependency.Service},
},
},
costexplorer.Expression{
Tags: &costexplorer.TagValues{
Key: aws.String(dependency.Tag),
Values: []string{dependency.Name},
},
},
},
}
} else {
filter = costexplorer.Expression{
Dimensions: &costexplorer.DimensionValues{
Key: costexplorer.DimensionService,
Values: []string{dependency.Service},
},
}
}
req := svc.GetCostAndUsageRequest(&costexplorer.GetCostAndUsageInput{
TimePeriod: &costexplorer.DateInterval{
Start: &start,
End: &end,
},
Granularity: costexplorer.GranularityDaily,
Metrics: []string{"BlendedCost"},
GroupBy: []costexplorer.GroupDefinition{
costexplorer.GroupDefinition{
Key: aws.String("SERVICE"),
Type: costexplorer.GroupDefinitionTypeDimension,
},
},
Filter: &filter,
})
resp, err := req.Send(context.Background())
if err != nil {
return map[time.Time]float64{}, err
}
for _, period := range resp.ResultsByTime {
t, _ := time.Parse(layoutISO, *period.TimePeriod.End)
if len(period.Groups) == 0 {
datapoints[t] = 0
} else {
value, _ := strconv.ParseFloat(*period.Groups[0].Metrics["BlendedCost"].Amount, 64)
datapoints[t] = value
}
}
return datapoints, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment