如何使用AWS CLI查询AWS账户每日成本,获得与Cost Explorer类似的结果
用AWS CLI查询每日消费成本的方法
完全可以通过AWS CLI调用Cost Explorer的接口拿到和Web Console完全一致的消费数据,操作方式非常简便。
前置要求
- 你使用的AWS身份(IAM用户/角色)需要拥有
ce:GetCostAndUsage权限 - 本地已经完成AWS CLI的身份认证配置(Access Key配置/SSO登录均可)
常用查询命令
查询最近7天每日总消费
macOS系统执行命令:
aws ce get-cost-and-usage --time-period Start=$(date -v-7d +%Y-%m-%d),End=$(date +%Y-%m-%d) --granularity DAILY --metrics "UnblendedCost" --output table
Linux系统执行命令:
aws ce get-cost-and-usage --time-period Start=$(date -d "-7 days" +%Y-%m-%d),End=$(date +%Y-%m-%d) --granularity DAILY --metrics "UnblendedCost" --output table
参数说明:
--granularity DAILY:按天维度聚合数据,和Cost Explorer的日维度展示规则完全一致--metrics "UnblendedCost":查询非混合成本,和Web控制台默认展示的消费金额口径相同,你也可以按需添加BlendedCost、UsageQuantity等其他指标--output table:直接在终端输出格式化表格,可读性更强,去掉该参数会返回默认JSON格式数据
查询最近7天各服务的每日消费
如果需要按服务分类统计,加上分组参数即可:
# macOS版本,Linux把date -v-7d换成date -d "-7 days" aws ce get-cost-and-usage --time-period Start=$(date -v-7d +%Y-%m-%d),End=$(date +%Y-%m-%d) --granularity DAILY --metrics "UnblendedCost" --group-by Type=DIMENSION,Key=SERVICE --output table
注意事项
Cost Explorer的数据存在最长24小时的延迟,当天的消费数据可能不全,属于官方正常机制。
内容的提问来源于stack exchange,提问作者Attila
相关产品推荐
相关产品推荐

