Capability Overview
Directory Structure
aliyun-oss-skills/
├── SKILL.md
├── .env.example
├── reference/ # API 定义(YML),含入参与返回值说明
│ ├── list_buckets.yml
│ ├── put_bucket.yml
│ ├── put_bucket_acl.yml
│ └── put_object.yml
└── scripts/
├── oss_util.py # 凭证与 Client 构造(供脚本复用)
├── list_buckets.py
├── put_bucket.py
├── put_bucket_acl.py
├── put_object.py
└── requirements.txt
- reference/: Stores API-related information (YML snippets), for consulting parameter and response meanings.
- scripts/: Runnable examples (for example, execute in this skill directory
python scripts/list_buckets.py); you can also read the implementation and modify it. - Dependencies:
pip install -r aliyun-oss-skills/scripts/requirements.txt。
This skill provides the followingindependent capabilities, which can be used individually or in combination as needed:
| Capability | API | Purpose | Use Case |
|---|---|---|---|
| List Buckets | ListBuckets(GetService) | List the storage spaces under the current account | Asset inventory, filter buckets by prefix/tag |
| Create Bucket | PutBucket | Create a new storage space in a specified region | New environment initialization, automated provisioning |
| Set Bucket ACL | PutBucketAcl | Overwrite the bucket access permission (private/public-read/public-read-write) | Tighten or adjust bucket visibility, compliance remediation |
| Upload Object | PutObject | Upload a local file as an object | Deploy static resources, back up files |
Notes:
- Each capability is independent, with no fixed call order.
- PutBucket / PutBucketAcl / PutObject are write operations: Before execution, confirm the bucket name, region, ACL value (
public-read/public-read-writeis high risk), and whether to overwrite an object with the same name; avoid misoperations on production buckets. - The query/header names in the REST documentation (such as
max-keys) may differ from the Python SDK field names,refer to the Request class parameters inalibabacloud_oss_v2.modelsSubject to the Request class parameters(for example,max_keys)。
Pre-checks (must be performed first)
Before calling OSS, confirm that access credentials are configured.
Check Order
1. Check environment variables first
echo "AK_ID: ${ALIBABA_CLOUD_ACCESS_KEY_ID:+已设置}"
echo "AK_SECRET: ${ALIBABA_CLOUD_ACCESS_KEY_SECRET:+已设置}"
2. If not set, check the current working directory's .env
find . -maxdepth 1 -name ".env" -exec cat {} \;
.env For examples, see .env.example。
3. Credential variable conventions (priority)
- Recommended:
ALIBABA_CLOUD_ACCESS_KEY_ID、ALIBABA_CLOUD_ACCESS_KEY_SECRET(consistent with other Alibaba Cloud skills in this repository). For temporary credentials, you can additionally setALIBABA_CLOUD_SECURITY_TOKEN(orOSS_SESSION_TOKEN)。 - Alternative:
OSS_ACCESS_KEY_ID、OSS_ACCESS_KEY_SECRET(consistent with the official OSS Python SDK examples); for STS, you can setOSS_SESSION_TOKEN。
Script logic:If ALIBABA_CLOUD_* is configured, use static credentials; otherwise use the OSS_* environment variable credential provider。
4. Loading in Python (consistent with scripts behavior)
from dotenv import load_dotenv
import os
access_key_id = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID", "").strip()
access_key_secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "").strip()
if not access_key_id or not access_key_secret:
load_dotenv()
access_key_id = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID", "").strip()
access_key_secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "").strip()
# 若仍无 ALIBABA_CLOUD_*,可回退检查 OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET
If the credential check is not passed, you should not continue calling OSS.
Install Dependencies
pip install -r aliyun-oss-skills/scripts/requirements.txt
Or install manually:
pip install alibabacloud_oss_v2 python-dotenv
List Buckets (ListBuckets)
Via alibabacloud_oss_v2 list the buckets under the current account. The SDK uses region to configure the client (default cn-hangzhou); the specific Endpoint is resolved by the SDK according to the region.
Common Request Parameters (Summary)
| Parameter (YML / Concept) | SDK Field (Python) | Description |
|---|---|---|
| prefix | prefix |
Name prefix filter |
| marker | marker |
Pagination start point |
| max-keys | max_keys |
Maximum number of entries per request (1–1000) |
| x-oss-resource-group-id | resource_group_id |
Resource group |
| tag-key / tag-value | tag_key / tag_value |
Filter by tag |
| tagging | tagging |
Tag list expression; mutually exclusive with tag-key/tag-value |
For the complete fields, see reference/list_buckets.yml。
RAM permission note
Listing buckets requires account-level read permission, for example, include in the policy oss:ListBuckets(refer to the console/documentation for the specific policy).
Core workflow
- Configure credentials (environment variables or
.env) Config(credentials_provider=..., region=...)+Client(config)- Build
ListBucketsRequest, set optional filter conditions - Call
client.list_buckets(request) - Parse the returned
ListBucketsResult(includingbuckets、is_truncated、next_marker, etc.)
Example script:scripts/list_buckets.py
Command-line example
cd aliyun-oss-skills
python scripts/list_buckets.py --region cn-hangzhou
python scripts/list_buckets.py --prefix myapp- --max-keys 50
Create a bucket (PutBucket)
Under the specified region create a bucket;bucket the name must globally comply with OSS naming rules (lowercase letters, digits, hyphens, 3–63 characters, etc.).
Common request parameters (summary)
| Parameter | SDK field | Description |
|---|---|---|
| bucket(host) | bucket |
Required |
| x-oss-acl | acl |
private / public-read / public-read-write |
| x-oss-resource-group-id | resource_group_id |
Optional |
| x-oss-bucket-tagging | bucket_tagging |
e.g. k1=v1&k2=v2 |
For the complete description, see reference/put_bucket.yml。
RAM permission note
Creating a bucket requires oss:PutBucket and other write permissions; there is an upper limit on the number of buckets that can be created by the same account in the same region (see the official documentation).
Core workflow
- Confirm the region and bucket name
- Build
PutBucketRequest(bucket=..., acl=..., ...) - Call
client.put_bucket(request)
Example script:scripts/put_bucket.py
Command-line example
python scripts/put_bucket.py --bucket my-unique-bucket-name --region cn-hangzhou
python scripts/put_bucket.py --bucket my-unique-bucket-name --region cn-hangzhou --acl private
Set bucket ACL (PutBucketAcl)
Foran existingbucket overwriteset the access permission (ACL). On REST this corresponds to PUT /?acl, request header x-oss-acl; the SDK uses PutBucketAclRequest the acl field.
Common request parameters (summary)
| Parameter | SDK field | Description |
|---|---|---|
| bucket(host) | bucket |
Required, target bucket name |
| x-oss-acl | acl |
Required:private、public-read、public-read-write(be cautious with public read/write) |
For the complete description and API behavior, see reference/put_bucket_acl.yml。
Behavior and notes
- Overwrite semantics: the new ACL overwrites the original ACL, it is not merged.
- Permission: the requester needs permission to write the bucket ACL; the policy usually includes
oss:PutBucketAcl(refer to the console/documentation). - Bucket does not exist: the contract states that if the specified bucket does not exist, calling this APIwill create a new bucket; for production automation it is still recommended to explicitly create it first with PutBucket, and not rely on this side effect.
RAM permission note
Requires ACL write permission for the target bucket, for example oss:PutBucketAcl。
Core workflow
- Confirm the bucket's
region, the target ACL value (preferprivate) Config+Client(same region as other scripts)- Build
PutBucketAclRequest(bucket=..., acl=...) - Call
client.put_bucket_acl(request)
Example script:scripts/put_bucket_acl.py(SDK-generated skeleton; before running, set in the request bucket and acl, or with scripts/oss_util.py the create_client method, then call it after alignment).
Code Example
from alibabacloud_oss_v2 import models as oss_models
req = oss_models.PutBucketAclRequest(
bucket="examplebucket",
acl="private", # 或 public-read、public-read-write(慎用)
)
resp = client.put_bucket_acl(req)
Upload Object (PutObject)
Upload alocal fileas an Object under the specified Bucket.By default, overwritingObjects with the same name is allowed; you can use --forbid-overwrite to prohibit overwriting (for behavior in versioning-enabled Buckets, refer to the official documentation).
Common Request Parameters (Summary)
| Parameter | SDK Field | Description |
|---|---|---|
| bucket | bucket |
Required |
| key | key |
Full path of the Object |
| body | body |
Binary content (the script reads from --file ) |
| Content-Type | content_type |
Optional; the script can infer it by file extension |
| x-oss-forbid-overwrite | forbid_overwrite |
Prohibit overwriting |
For limits such as single file size, see reference/put_object.yml。
RAM Permission Notes
Write permission for the target Bucket is required, for example oss:PutObject。
Core Workflow
- Confirm the Bucket's
region, targetkey - Read the local file as
bytes - Build
PutObjectRequest(bucket=..., key=..., body=..., content_type=...) - Call
client.put_object(request)
Example script:scripts/put_object.py
Command-line example
python scripts/put_object.py --bucket my-bucket --key path/to/object.bin --file ./local.bin --region cn-hangzhou
python scripts/put_object.py --bucket my-bucket --key index.html --file ./index.html --content-type text/html --region cn-hangzhou
Error Handling Recommendations
The script prints readable information for exceptions; for nested errors it will attempt to use unwrap to output the inner message. If the exception object contains an OpenAPI-style data and has Recommend, it will also be printed.
Common cases:
- 403 AccessDenied: Invalid AK/SK, insufficient RAM policy, or Resource mismatch.
- 404 NoSuchBucket: Bucket does not exist or region is incorrect.
- 409 BucketAlreadyExists etc.: The Bucket name is already taken or there is a conflict.
For OSS Python SDK exception types, see alibabacloud_oss_v2.exceptions(such as ServiceError)。
Usage Workflow Summary
- Check environment variables or
.env, and confirm that credentials are configured. - Install
scripts/requirements.txt。 - Choose ListBuckets / PutBucket / PutBucketAcl / PutObject according to the scenario, and construct the request against the Request fields in the YML and
models. - Call the corresponding
clientmethod, and parse the JSON output or Result object.
Notes
- reference/ The YML inscripts/ is used to look up the contract;
- is used to verify the environment and call chain. If the business behavior differs from the example, the official OSS Developer Documentation
- and the SDK source code shall prevail.
is_truncatedIf the listing result hasnext_markerto continue the request for pagination.