SuperAPI AI Directory

aliyun-billing-skills

Deployment & operations

View repository

Updated 10-16 10:04

About this skill

Alibaba Cloud instance bill query

Through 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 through 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 retrieve 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-fee bills, default false
BillOwnerId integer Resource owner account ID

Pagination parameters (SDK uses the 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": [...]           # 账单详情列表
    }
}

Retrieve complete data with pagination

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 to an empty string
  2. Subsequent requests: use the value of response.body.data.next_token from the previous response
  3. Termination condition: next_token in the response is empty or does not exist (indicating all data has been retrieved)

Example code for paginated retrieval

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 according to 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. An agent using this skill should refer to the structure and API call methods of these codes to generate an implementation suitable for its own context.

Agent usage:

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

Core API Call Patterns:

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 given 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 post-paid 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 Recommendations

  • 401/403: AK/SK is invalid, not configured, or RAM permissions are insufficient
  • InvalidAccessKeyId: AccessKeyId is incorrect
  • SignatureDoesNotMatch: AccessKeySecret is incorrect or the signature does not match
  • If the exception contains the Recommend field, troubleshoot preferentially using the diagnostic link

Usage Workflow

  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 call patterns
  4. Build request parameters according to the query requirements (filter conditions + pagination parameters)
  5. Implement the pagination loopto obtain the complete bill data
  6. Aggregate and process all bill records

Notes

  • BillingCycle The parameter format is YYYY-MM(e.g., 2024-03), and it must be provided when calling
  • Pagination logic must be implemented, and a single call returns at most 300 records
  • Pagination uses the NextToken method: for the first request use next_token=None, and subsequently 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 used 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.