SuperAPI AI Directory

aliyun-instance-bill

General & other

View repository

Updated 10-16 09:28

About this skill

Alibaba Cloud Instance Bill Query

Via the Python SDK alibabacloud_bssopenapi20171214 call the Alibaba Cloud BSS OpenAPI to query instance-level bills under the current account.

Prerequisite Check (Must Be Performed First)

Before executing any query, you must first confirm that AK/SK has been configured.

From the current working directory's .env file read:

Check whether the following exists in the current working directory: .env file:

find . -maxdepth 1 -name ".env" -exec cat {} \;

.env File format:

ALIBABA_CLOUD_ACCESS_KEY_ID=your-access-key-id
ALIBABA_CLOUD_ACCESS_KEY_SECRET=your-access-key-secret

Load in Python code:

from dotenv import load_dotenv
import os

load_dotenv()  # 从当前工作目录的 .env 文件加载

access_key_id = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID")
access_key_secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET")

Or via environment variables:

export ALIBABA_CLOUD_ACCESS_KEY_ID="your-access-key-id"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="your-access-key-secret"

If the credential check is not passed, the query steps should not continue.

Install Dependencies

pip install alibabacloud_bssopenapi20171214 alibabacloud_credentials alibabacloud_tea_openapi alibabacloud_tea_util python-dotenv

Request Parameters

Required Parameters

Parameter Type Description
BillingCycle string Billing period, in YYYY-MM format, only the most recent 18 months are supported, e.g. 2024-03

Optional Parameters (Filter Conditions)

Parameter Type Description
ProductCode string Product code, e.g. rds、ecs
ProductType string Product type, required when ProductCode is a cloud marketplace product
SubscriptionType string Subscription type:Subscription(prepaid) / PayAsYouGo(postpaid)
IsBillingItem boolean Whether to pull by billing item dimension, default false
Granularity string Bill granularity:MONTHLY(monthly) / DAILY(daily), BillingDate must be specified when DAILY is selected
BillingDate string Billing date, in YYYY-MM-DD format, required only when Granularity=DAILY
IsHideZeroCharge boolean Whether to hide zero-cost bills, default false
BillOwnerId integer Resource owner account ID

Pagination Parameters (SDK uses NextToken method)

Parameter Type Description
MaxResults integer Number per page, maximum 300
NextToken string Next page token, empty for the first request, subsequently use the NextToken from the previous response

Response Structure

response.body.data = {
    "NextToken": "xxx",         # 下一页的令牌(如果没有更多数据则不返回)
    "MaxResults": 300,          # 每页数量
    "TotalCount": 100,          # 总记录数
    "BillingCycle": "2024-03",
    "Items": {
        "Item": [...]           # 账单详情列表
    }
}

Paginate to Retrieve Complete Data

Pagination logic must be implemented, because a single API call returns at most 300 records.

Pagination Rules

  1. First request: do not specify NextToken or set it to an empty string
  2. Subsequent requests: use the response.body.data.next_token value from the previous response
  3. Termination condition: the response's next_token is empty or does not exist (indicating all data has been retrieved)

Pagination Retrieval Example Code

def fetch_all_bills(client, billing_cycle, max_results=300, **filter_kwargs):
    """获取指定账期的所有账单记录(自动分页)"""
    all_items = []
    next_token = None

    while True:
        request = bss_open_api_20171214_models.DescribeInstanceBillRequest(
            billing_cycle=billing_cycle,
            max_results=max_results,
            next_token=next_token,
            **filter_kwargs
        )
        response = client.describe_instance_bill_with_options(request, util_models.RuntimeOptions())

        if not response.body.success or not response.body.data.items.item:
            break

        items = response.body.data.items
        all_items.extend(items)

        # 判断是否还有更多数据
        next_token = getattr(response.body.data, 'next_token', None)
        if not next_token:
            break

    return all_items

DescribeInstanceBill Usage

Core Process:

  1. From environment variables (or the current working directory's .env) read ALIBABA_CLOUD_ACCESS_KEY_ID / ALIBABA_CLOUD_ACCESS_KEY_SECRET
  2. Create BssOpenApi20171214Client
  3. Build request parameters based on query conditions (including filter conditions and pagination parameters)
  4. Implement pagination logic, call in a loop until complete data is retrieved
  5. Aggregate and process all bill records

Reference Implementation

reference/ The directory contains Agent reference samples, not directly runnable scripts. Agents using this skill should refer to the structure and API call methods of this code to generate an implementation suitable for their own context.

Agent Usage:

  1. Read reference/describe_instance_bill.py to understand the API calling pattern
  2. Generate the corresponding implementation code based on the current project structure
  3. Do not copy and run it directly; use it as a reference template

Core API calling pattern:

from alibabacloud_bssopenapi20171214.client import Client as BssOpenApi20171214Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_bssopenapi20171214 import models as bss_open_api_20171214_models

# 1. 创建客户端
config = open_api_models.Config(
    access_key_id=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"),
    access_key_secret=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
)
config.endpoint = 'business.aliyuncs.com'
client = BssOpenApi20171214Client(config)

# 2. 调用 API(单次调用,带分页参数)
request = bss_open_api_20171214_models.DescribeInstanceBillRequest(
    billing_cycle="2024-03",
    max_results=300,
    next_token=None,  # 首次请求设为 None,后续使用响应中的 next_token
    product_code="ecs",  # 可选筛选条件
)
response = client.describe_instance_bill_with_options(request, util_models.RuntimeOptions())

Common query scenarios

Scenario 1: Query all bills for a certain month

all_items = fetch_all_bills(client, billing_cycle="2024-03", max_results=300)

Scenario 2: Query bills for a specified product

all_items = fetch_all_bills(
    client,
    billing_cycle="2024-03",
    max_results=300,
    product_code="rds"
)

Scenario 3: Query postpaid product bills

all_items = fetch_all_bills(
    client,
    billing_cycle="2024-03",
    max_results=300,
    subscription_type="PayAsYouGo"
)

Scenario 4: Query bills by day

all_items = fetch_all_bills(
    client,
    billing_cycle="2024-03",
    max_results=300,
    granularity="DAILY",
    billing_date="2024-03-15"
)

Error handling suggestions

  • 401/403: AK/SK is invalid, not configured, or RAM permissions are insufficient
  • InvalidAccessKeyId: AccessKeyId is incorrect
  • SignatureDoesNotMatch: AccessKeySecret is incorrect or the signature is inconsistent
  • If the exception contains the Recommend field, prioritize troubleshooting according to the diagnostic link

Usage process

  1. Check the .env file or environment variables in the current working directory to confirm that AK/SK is configured
  2. Install dependencies
  3. Read reference/describe_instance_bill.pyto understand the API calling pattern
  4. Build request parameters according to the query requirements (filter conditions + pagination parameters)
  5. Implement the pagination loopto obtain complete bill data
  6. Aggregate and process all bill records

Notes

  • BillingCycle The parameter format is YYYY-MM(such as 2024-03), and it must be provided when calling
  • Pagination logic must be implemented; a single call returns at most 300 records
  • Pagination uses the NextToken method: the first request uses next_token=None, and subsequent requests use the next_token value from the response
  • Pagination termination condition: next_token in the response is empty or does not exist
  • Filter conditions:product_code、subscription_type、granularity , etc. can effectively reduce the amount of returned data
  • The reference code is a sample to help the agent understand how to call the API
  • The agent should generate code according to actual requirements, including error handling, parameter passing, etc.