Beispiel #1
0
        public async Task <GetCostAndUsageResponse> GetCostAndUsage(GetCostAndUsageRequest costUsageRequest)
        {
            using (var amazonCostExplorerClient = new AmazonCostExplorerClient(awsCredentials, RegionEndpoint.GetBySystemName("us-east-1")))
            {
                var response = await amazonCostExplorerClient.GetCostAndUsageAsync(costUsageRequest);

                return(response);
            }
        }
Beispiel #2
0
        //private static GetCostAndUsageRequest BuildAWSCostAndUsageRequest(object data)
        //{

        //    GetCostAndUsageRequest costAndUsageRequest = new GetCostAndUsageRequest();
        //    //string jsonString = File.ReadAllText(@"costandusageresquest.json");
        //    costAndUsageRequest = JsonConvert.DeserializeObject<GetCostAndUsageRequest>(data.ToString());
        //    return costAndUsageRequest;
        //}
        private static GetCostAndUsageResponse CallAWSCostAndUsageAPI(GetCostAndUsageRequest costAndUsageRequest)
        {
            var client = new AmazonCostExplorerClient(
                awsAccessKeyId: Environment.GetEnvironmentVariable("awsAccessKeyId"),
                awsSecretAccessKey: Environment.GetEnvironmentVariable("awsSecretAccessKey"),
                Amazon.RegionEndpoint.USEast1);

            GetCostAndUsageResponse costAndUsageResponse = client.GetCostAndUsageAsync(costAndUsageRequest).Result;

            return(costAndUsageResponse);
        }
        public async ValueTask <GetCostAndUsageResponse> GetByDate(DateTime start, DateTime end)
        {
            var client  = new AmazonCostExplorerClient();
            var request = new GetCostAndUsageRequest
            {
                TimePeriod = new DateInterval()
                {
                    Start = $"{start:yyyy-MM-dd}",
                    End   = $"{end:yyyy-MM-dd}"
                },
                Granularity = Granularity.DAILY
            };

            request.Metrics.Add("BlendedCost");
            request.GroupBy = new List <GroupDefinition>()
            {
                new GroupDefinition()
                {
                    Key = "SERVICE", Type = GroupDefinitionType.DIMENSION
                }
            };
            return(await client.GetCostAndUsageAsync(request));
        }
Beispiel #4
0
        public static void GetCostsAndUsage()
        {
            Console.WriteLine(Utils.CurrentMethod);
            GetCostAndUsageRequest request = new GetCostAndUsageRequest();

            request.TimePeriod = new DateInterval()
            {
                Start = "2019-04-01", End = "2019-05-01"
            };
            request.Granularity = Granularity.MONTHLY;
            request.Metrics     = new List <string>();
            request.Metrics.Add(Metric.AMORTIZED_COST);
            request.Metrics.Add(Metric.BLENDED_COST);
            request.Metrics.Add(Metric.NET_AMORTIZED_COST);
            request.Metrics.Add(Metric.NET_UNBLENDED_COST);
            request.Metrics.Add(Metric.NORMALIZED_USAGE_AMOUNT);
            request.Metrics.Add(Metric.UNBLENDED_COST);
            request.Metrics.Add(Metric.USAGE_QUANTITY);

            request.GroupBy = new List <GroupDefinition>();
            request.GroupBy.Add(new GroupDefinition {
                Type = GroupDefinitionType.DIMENSION, Key = Dimension.LINKED_ACCOUNT
            });
            request.GroupBy.Add(new GroupDefinition {
                Type = GroupDefinitionType.TAG, Key = "cloud-environment"
            });
//            request.GroupBy.Add(new GroupDefinition { Type = GroupDefinitionType.DIMENSION, Key = Dimension.SERVICE });

            bool keepLooking = true;
            int  callCount   = 0;

            while (keepLooking)
            {
                Task <GetCostAndUsageResponse> t = client.GetCostAndUsageAsync(request);
                t.Wait(30000);
                GetCostAndUsageResponse response = t.Result;

                string json = JsonTools.Serialize(response, true);
                Console.WriteLine(json);

                String fileName = $"/Users/guy/temp/cost-and-usage-{callCount.ToString().PadLeft(4, '0')}.json";
                File.WriteAllText(fileName, json);

                string nextPageToken = response.NextPageToken;

                if (String.IsNullOrWhiteSpace(nextPageToken))
                {
                    keepLooking = false;
                }
                else if (callCount > 100)
                {
                    keepLooking = false;
                }
                else
                {
                    request.NextPageToken = nextPageToken;
                }

                callCount++;
            }
        }
Beispiel #5
0
        public async Task <bool> FunctionHandler(ILambdaContext context)
        {
            // AWS側の集計に時間を要するため、2日前の利用量を集計する
            var start = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
            var end   = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");

            var ceRequest = new GetCostAndUsageRequest
            {
                TimePeriod = new DateInterval()
                {
                    Start = start,
                    End   = end
                },
                Granularity = "DAILY",
                Metrics     = new List <string>()
                {
                    METRICS
                },
                GroupBy = new List <GroupDefinition>()
                {
                    new GroupDefinition
                    {
                        Type = "DIMENSION",
                        Key  = "SERVICE"
                    }
                }
            };

            using var ceClient = new AmazonCostExplorerClient(region);
            var ceResponse = await ceClient.GetCostAndUsageAsync(ceRequest);

            decimal total  = 0;
            var     fields = new List <Field>();

            foreach (var result in ceResponse.ResultsByTime)
            {
                foreach (var group in result.Groups)
                {
                    var cost = Math.Round(Convert.ToDecimal(group.Metrics[METRICS].Amount) * RATE, 0);

                    fields.Add(new Field()
                    {
                        title  = group.Keys[0],
                        value  = String.Format(":moneybag: {0:#,0} 円", cost),
                        @short = true
                    });

                    total += cost;
                }
            }

            var color      = total == 0 ? "good" : "danger";
            var attachment = new Attachment()
            {
                fallback = "Required plain-text summery of the attachment.",
                color    = color,
                pretext  = String.Format("*{0} のAWS利用料は {1:#,0}円 です*", start, total),
                fields   = fields,
                channel  = SLACK_CHANNEL,
                username = "******"
            };

            var jsonSting = JsonConvert.SerializeObject(attachment);
            var content   = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "payload", jsonSting }
            });

            var webhookUrl = await GetWebhookUrl();

            try
            {
                using var httpClient = new HttpClient();
                await httpClient.PostAsync(webhookUrl, content);
            }
            catch (Exception e)
            {
                context.Logger.LogLine("Exception: " + e.Message);
            }

            return(true);
        }