Пример #1
0
        /// <summary>
        /// コスト超過しているか確認する
        /// </summary>
        /// <param name="awsAccessKey">AWSアクセスキー</param>
        /// <param name="awsSecretKey">AWSシークレットキー</param>
        /// <param name="limit">超過とみなす閾値</param>
        private static string getLimitoverCost(string awsAccessKey, string awsSecretKey, decimal limit)
        {
            AmazonCostExplorerClient client = new AmazonCostExplorerClient(awsAccessKey, awsSecretKey, RegionEndpoint.USEast1);
            GetCostAndUsageRequest   req    = new GetCostAndUsageRequest();

            req.TimePeriod       = new DateInterval();
            req.TimePeriod.Start = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd"); // 3日前~本日までチェック
            req.TimePeriod.End   = DateTime.Now.ToString("yyyy-MM-dd");
            req.Granularity      = Granularity.DAILY;
            req.Metrics          = new List <string>()
            {
                "AMORTIZED_COST"
            };

            StringBuilder           sb   = new StringBuilder(); // 超過情報
            GetCostAndUsageResponse cost = client.GetCostAndUsage(req);

            for (int i = 0; i < cost.ResultsByTime.Count; i++)
            {
                string start = cost.ResultsByTime[i].TimePeriod.Start;
                string end   = cost.ResultsByTime[i].TimePeriod.End;
                foreach (string key in cost.ResultsByTime[i].Total.Keys)
                {
                    decimal amount = decimal.Parse(cost.ResultsByTime[i].Total[key].Amount);
                    string  unit   = cost.ResultsByTime[i].Total[key].Unit;
                    if (amount > limit)  // 閾値を超えた
                    {
                        sb.Append(start + "~" + end + " Amount=" + amount + " Unit=" + unit + Environment.NewLine);
                    }
                }
            }
            return(sb.ToString());
        }
Пример #2
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonCostExplorerConfig config = new AmazonCostExplorerConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonCostExplorerClient client = new AmazonCostExplorerClient(creds, config);

            ListCostCategoryDefinitionsResponse resp = new ListCostCategoryDefinitionsResponse();

            do
            {
                ListCostCategoryDefinitionsRequest req = new ListCostCategoryDefinitionsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.ListCostCategoryDefinitions(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.CostCategoryReferences)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
Пример #3
0
        public async Task <GetRightsizingRecommendationResponse> GetRightsizingRecommendation(GetRightsizingRecommendationRequest rightsizingRecommendationRequest)
        {
            using (var amazonCostExplorerClient = new AmazonCostExplorerClient(awsCredentials, RegionEndpoint.GetBySystemName("us-east-1")))
            {
                var response = await amazonCostExplorerClient.GetRightsizingRecommendationAsync(rightsizingRecommendationRequest);

                return(response);
            }
        }
Пример #4
0
        public async Task <GetCostForecastResponse> GetCostForecast(GetCostForecastRequest costForecastRequest)
        {
            using (var amazonCostExplorerClient = new AmazonCostExplorerClient(awsCredentials, RegionEndpoint.GetBySystemName("us-east-1")))
            {
                var response = await amazonCostExplorerClient.GetCostForecastAsync(costForecastRequest);

                return(response);
            }
        }
        private static GetCostAndUsageWithResourcesResponse  CallAWSCostAndUsageAPI(GetCostAndUsageWithResourcesRequest costAndUsageWithResourcesRequest)
        {
            var client = new AmazonCostExplorerClient(
                awsAccessKeyId: Environment.GetEnvironmentVariable("awsAccessKeyId"),
                awsSecretAccessKey: Environment.GetEnvironmentVariable("awsSecretAccessKey"),
                Amazon.RegionEndpoint.USEast1);

            GetCostAndUsageWithResourcesResponse costAndUsageWithResourcesResponse = client.GetCostAndUsageWithResourcesAsync(costAndUsageWithResourcesRequest).Result;

            return(costAndUsageWithResourcesResponse);
        }
Пример #6
0
        protected IAmazonCostExplorer CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonCostExplorerConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonCostExplorerClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
        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));
        }
Пример #8
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);
        }