/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.CostExplorer;
using Amazon.CostExplorer.Model;
namespace Amazon.PowerShell.Cmdlets.CE
{
///
/// Retrieves cost and usage metrics with resources for your account. You can specify
/// which cost and usage-related metric, such as BlendedCosts
or UsageQuantity
,
/// that you want the request to return. You can also filter and group your data by various
/// dimensions, such as SERVICE
or AZ
, in a specific time range.
/// For a complete list of valid dimensions, see the GetDimensionValues
/// operation. Management account in an organization in Organizations have access to all
/// member accounts. This API is currently available for the Amazon Elastic Compute Cloud
/// – Compute service only.
///
///
/// This is an opt-in only feature. You can enable this feature from the Cost Explorer
/// Settings page. For information about how to access the Settings page, see Controlling
/// Access for Cost Explorer in the Billing and Cost Management User Guide.
///
This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration.
///
[Cmdlet("Get", "CECostAndUsageWithResource")]
[OutputType("Amazon.CostExplorer.Model.GetCostAndUsageWithResourcesResponse")]
[AWSCmdlet("Calls the AWS Cost Explorer GetCostAndUsageWithResources API operation.", Operation = new[] {"GetCostAndUsageWithResources"}, SelectReturnType = typeof(Amazon.CostExplorer.Model.GetCostAndUsageWithResourcesResponse))]
[AWSCmdletOutput("Amazon.CostExplorer.Model.GetCostAndUsageWithResourcesResponse",
"This cmdlet returns an Amazon.CostExplorer.Model.GetCostAndUsageWithResourcesResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class GetCECostAndUsageWithResourceCmdlet : AmazonCostExplorerClientCmdlet, IExecutor
{
#region Parameter Filter
///
///
/// Filters Amazon Web Services costs by different dimensions. For example, you can specify
/// SERVICE
and LINKED_ACCOUNT
and get the costs that are associated
/// with that account's usage of that service. You can nest Expression
objects
/// to define any combination of dimension filters. For more information, see Expression.
/// The GetCostAndUsageWithResources
operation requires that you either group
/// by or filter by a ResourceId
. It requires the Expression"SERVICE = Amazon Elastic Compute Cloud - Compute"
in the filter.Valid values for MatchOptions
for Dimensions
are EQUALS
/// and CASE_SENSITIVE
.Valid values for MatchOptions
for CostCategories
and Tags
/// are EQUALS
, ABSENT
, and CASE_SENSITIVE
. Default
/// values are EQUALS
and CASE_SENSITIVE
.
///
///
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public Amazon.CostExplorer.Model.Expression Filter { get; set; }
#endregion
#region Parameter Granularity
///
///
/// Sets the Amazon Web Services cost granularity to MONTHLY
, DAILY
,
/// or HOURLY
. If Granularity
isn't set, the response object
/// doesn't include the Granularity
, MONTHLY
, DAILY
,
/// or HOURLY
.
///
///
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[AWSConstantClassSource("Amazon.CostExplorer.Granularity")]
public Amazon.CostExplorer.Granularity Granularity { get; set; }
#endregion
#region Parameter GroupBy
///
///
/// You can group Amazon Web Services costs using up to two different groups: DIMENSION
,
/// TAG
, COST_CATEGORY
.
///
///
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public Amazon.CostExplorer.Model.GroupDefinition[] GroupBy { get; set; }
#endregion
#region Parameter Metric
///
///
/// Which metrics are returned in the query. For more information about blended and unblended
/// rates, see Why
/// does the "blended" annotation appear on some line items in my bill?. Valid values are AmortizedCost
, BlendedCost
, NetAmortizedCost
,
/// NetUnblendedCost
, NormalizedUsageAmount
, UnblendedCost
,
/// and UsageQuantity
. If you return the UsageQuantity
metric, the service aggregates all usage
/// numbers without taking the units into account. For example, if you aggregate usageQuantity
/// across all of Amazon EC2, the results aren't meaningful because Amazon EC2 compute
/// hours and data transfer are measured in different units (for example, hour or GB).
/// To get more meaningful UsageQuantity
metrics, filter by UsageType
/// or UsageTypeGroups
. Metrics
is required for GetCostAndUsageWithResources
requests.
///
///
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("Metrics")]
public System.String[] Metric { get; set; }
#endregion
#region Parameter TimePeriod
///
///
/// Sets the start and end dates for retrieving Amazon Web Services costs. The range must
/// be within the last 14 days (the start date cannot be earlier than 14 days ago). The
/// start date is inclusive, but the end date is exclusive. For example, if start
/// is 2017-01-01
and end
is 2017-05-01
, then the
/// cost and usage data is retrieved from 2017-01-01
up to and including
/// 2017-04-30
but not including 2017-05-01
.
///
///
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public Amazon.CostExplorer.Model.DateInterval TimePeriod { get; set; }
#endregion
#region Parameter NextPageToken
///
///
/// The token to retrieve the next set of results. Amazon Web Services provides the token
/// when the response from a previous call has more results than the maximum page size.
///
///
///
Note: This parameter is only used if you are manually controlling output pagination of the service API call.
///
In order to manually control output pagination, use '-NextPageToken $null' for the first call and '-NextPageToken $AWSHistory.LastServiceResponse.NextPageToken' for subsequent calls.
///
///
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("NextToken")]
public System.String NextPageToken { get; set; }
#endregion
#region Parameter Select
///
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CostExplorer.Model.GetCostAndUsageWithResourcesResponse).
/// Specifying the name of a property of type Amazon.CostExplorer.Model.GetCostAndUsageWithResourcesResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
///
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
///
/// Changes the cmdlet behavior to return the value passed to the TimePeriod parameter.
/// The -PassThru parameter is deprecated, use -Select '^TimePeriod' instead. This parameter will be removed in a future version.
///
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^TimePeriod' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter NoAutoIteration
///
/// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple
/// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextPageToken
/// as the start point.
///
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter NoAutoIteration { get; set; }
#endregion
protected override void ProcessRecord()
{
this._AWSSignerType = "v4";
base.ProcessRecord();
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.TimePeriod;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.Filter = this.Filter;
#if MODULAR
if (this.Filter == null && ParameterWasBound(nameof(this.Filter)))
{
WriteWarning("You are passing $null as a value for parameter Filter which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.Granularity = this.Granularity;
#if MODULAR
if (this.Granularity == null && ParameterWasBound(nameof(this.Granularity)))
{
WriteWarning("You are passing $null as a value for parameter Granularity which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
if (this.GroupBy != null)
{
context.GroupBy = new List(this.GroupBy);
}
if (this.Metric != null)
{
context.Metric = new List(this.Metric);
}
context.NextPageToken = this.NextPageToken;
context.TimePeriod = this.TimePeriod;
#if MODULAR
if (this.TimePeriod == null && ParameterWasBound(nameof(this.TimePeriod)))
{
WriteWarning("You are passing $null as a value for parameter TimePeriod which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
// create request and set iteration invariants
var request = new Amazon.CostExplorer.Model.GetCostAndUsageWithResourcesRequest();
if (cmdletContext.Filter != null)
{
request.Filter = cmdletContext.Filter;
}
if (cmdletContext.Granularity != null)
{
request.Granularity = cmdletContext.Granularity;
}
if (cmdletContext.GroupBy != null)
{
request.GroupBy = cmdletContext.GroupBy;
}
if (cmdletContext.Metric != null)
{
request.Metrics = cmdletContext.Metric;
}
if (cmdletContext.TimePeriod != null)
{
request.TimePeriod = cmdletContext.TimePeriod;
}
// Initialize loop variant and commence piping
var _nextToken = cmdletContext.NextPageToken;
var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextPageToken));
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
do
{
request.NextPageToken = _nextToken;
CmdletOutput output;
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
if (!useParameterSelect)
{
pipelineOutput = cmdletContext.Select(response, this);
}
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
_nextToken = response.NextPageToken;
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
ProcessOutput(output);
} while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken));
if (useParameterSelect)
{
WriteObject(cmdletContext.Select(null, this));
}
return null;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.CostExplorer.Model.GetCostAndUsageWithResourcesResponse CallAWSServiceOperation(IAmazonCostExplorer client, Amazon.CostExplorer.Model.GetCostAndUsageWithResourcesRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Cost Explorer", "GetCostAndUsageWithResources");
try
{
#if DESKTOP
return client.GetCostAndUsageWithResources(request);
#elif CORECLR
return client.GetCostAndUsageWithResourcesAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public Amazon.CostExplorer.Model.Expression Filter { get; set; }
public Amazon.CostExplorer.Granularity Granularity { get; set; }
public List GroupBy { get; set; }
public List Metric { get; set; }
public System.String NextPageToken { get; set; }
public Amazon.CostExplorer.Model.DateInterval TimePeriod { get; set; }
public System.Func Select { get; set; } =
(response, cmdlet) => response;
}
}
}