cloudflare-r2 – skill Khác cho agent AI
Quản lý bucket Cloudflare R2, lifecycle và signed URL. Dùng cho lưu trữ đối tượng chi phí egress thấp và phân phối media.
Cài skill cloudflare-r2 bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/cloudflare-r2-90f8e.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /cloudflare-r2 – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/cloudflare-r2-90f8e.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $cloudflare-r2 – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/cloudflare-r2-90f8e.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /cloudflare-r2 – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/cloudflare-r2-90f8e.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /cloudflare-r2 – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
Cloudflare R2
S3-compatible object storage with zero egress fees, built on Cloudflare's global network.
When to Use
- Storing user uploads, media files, backups, or static assets.
- Replacing AWS S3 to eliminate egress costs for read-heavy workloads.
- Serving files at the edge via Workers or public bucket access.
- Building multi-cloud storage that avoids vendor lock-in (S3 API compatible).
- Storing ML model artifacts, training data, or inference results.
Object and public-access scope
Confirm account, bucket, exact keys/prefix and overwrite/delete authority before writes or lifecycle changes. R2 supports a subset of S3 behavior; verify CLI subcommands/location hints against the installed Wrangler version. Zero egress does not mean zero storage/request/infrequent-access costs. The GET fragment intentionally serves only already-approved public assets; never attach it to private uploads. Signed URLs are bearer capabilities: authorize the caller and object, encode key path segments, set explicit short expiry and method, return privately with no-store, and never print/share them in logs. CORS does not authenticate callers. See [presigned URL scope](https://developers.cloudflare.com/r2/api/s3/presigned-urls/).
Prerequisites
- Cloudflare account with R2 enabled (dashboard > R2 > subscribe).
- Wrangler CLI v3+ installed:
npm install -g wrangler. - Authenticated via
wrangler loginorCLOUDFLARE_API_TOKEN. - For S3 API access: R2 API token created under R2 > Manage R2 API Tokens.
Bucket Management with Wrangler
Create and List Buckets
# Create a new bucket
npx wrangler r2 bucket create app-assets
# Create a bucket in a specific region (hint for data locality)
npx wrangler r2 bucket create eu-uploads --location=eu
# List all buckets
npx wrangler r2 bucket list
# Delete an empty bucket
npx wrangler r2 bucket delete old-bucketObject Operations
# Upload a single file
npx wrangler r2 object put app-assets/images/logo.png --file=./logo.png
# Upload with content type
npx wrangler r2 object put app-assets/data/report.json \
--file=./report.json \
--content-type="application/json"
# Download an object
npx wrangler r2 object get app-assets/images/logo.png --file=./downloaded-logo.png
# Delete an object
npx wrangler r2 object delete app-assets/images/old-logo.png
# Get object metadata
npx wrangler r2 object head app-assets/images/logo.pngS3-Compatible API Access
R2 supports the S3 API, so existing tools (AWS CLI, boto3, s3cmd) work out of the box.
Generate R2 API Tokens
1. Go to R2 > Manage R2 API Tokens > Create API token.
2. Select permissions: Object Read & Write, or Object Read only.
3. Scope to specific buckets if possible.
4. Save the Access Key ID and Secret Access Key.
AWS CLI Configuration
# Configure a named profile for R2
aws configure --profile r2
# Access Key ID: <your-r2-access-key>
# Secret Access Key: <your-r2-secret-key>
# Region: auto
# Output: json
# Use the R2 endpoint
export R2_ENDPOINT="https://<ACCOUNT_ID>.r2.cloudflarestorage.com"
# List buckets
aws s3 ls --endpoint-url=$R2_ENDPOINT --profile=r2
# Sync a directory
aws s3 sync ./dist s3://app-assets/static/ \
--endpoint-url=$R2_ENDPOINT \
--profile=r2
# Copy a file
aws s3 cp ./backup.tar.gz s3://app-assets/backups/backup-$(date +%Y%m%d).tar.gz \
--endpoint-url=$R2_ENDPOINT \
--profile=r2
# List objects with prefix
aws s3 ls s3://app-assets/images/ \
--endpoint-url=$R2_ENDPOINT \
--profile=r2
# Remove objects by prefix
aws s3 rm s3://app-assets/tmp/ --recursive \
--endpoint-url=$R2_ENDPOINT \
--profile=r2Python boto3 Client
import boto3
s3 = boto3.client(
"s3",
endpoint_url="https://<ACCOUNT_ID>.r2.cloudflarestorage.com",
aws_access_key_id="<R2_ACCESS_KEY>",
aws_secret_access_key="<R2_SECRET_KEY>",
region_name="auto",
)
# Upload file
s3.upload_file("./report.pdf", "app-assets", "reports/report.pdf")
# Generate presigned URL (valid for 1 hour)
url = s3.generate_presigned_url(
"get_object",
Params={"Bucket": "app-assets", "Key": "reports/report.pdf"},
ExpiresIn=3600,
)
print(url)
# List objects
response = s3.list_objects_v2(Bucket="app-assets", Prefix="images/", MaxKeys=100)
for obj in response.get("Contents", []):
print(f"{obj['Key']} - {obj['Size']} bytes")Worker Bindings
Bind R2 buckets to Workers or Pages Functions for server-side access without API tokens.
Wrangler Configuration
# wrangler.toml
name = "asset-worker"
main = "src/index.ts"
compatibility_date = "2024-09-01"
[[r2_buckets]]
binding = "ASSETS"
bucket_name = "app-assets"
[[r2_buckets]]
binding = "UPLOADS"
bucket_name = "user-uploads"Worker with R2 Operations
// src/index.ts
interface Env {
ASSETS: R2Bucket;
UPLOADS: R2Bucket;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// GET — serve file from R2
if (request.method === "GET") {
const key = url.pathname.slice(1); // strip leading /
const object = await env.ASSETS.get(key);
if (!object) {
return new Response("Not Found", { status: 404 });
}
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set("etag", object.httpEtag);
headers.set("cache-control", "public, max-age=86400");
return new Response(object.body, { headers });
}
// Mutations are disabled until application authentication, object-level
// authorization, key normalization, upload-size limits and audit controls exist.
if (request.method === "PUT" || request.method === "DELETE") {
return new Response("Authenticated mutation API not implemented", { status: 403 });
}
return new Response("Method Not Allowed", { status: 405 });
},
};Presigned URL Generation in a Worker
// Generate time-limited signed URLs using Workers
import { AwsClient } from "aws4fetch";
interface Env {
R2_ACCESS_KEY: string;
R2_SECRET_KEY: string;
R2_ACCOUNT_ID: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Fail closed: implement verified caller/object authorization before signing.
return new Response("Authorized signing API not implemented", { status: 403 });
/* Illustrative signing body, disabled until that boundary exists:
const aws = new AwsClient({
accessKeyId: env.R2_ACCESS_KEY,
secretAccessKey: env.R2_SECRET_KEY,
});
const url = new URL(request.url);
const key = url.searchParams.get("key");
if (!key) return new Response("Missing key", { status: 400 });
const r2Url = `https://${env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com/app-assets/${key}`;
const signed = await aws.sign(new Request(r2Url), {
aws: { signQuery: true },
});
return Response.json({ url: signed.url });
*/
},
};Public Bucket Access
Enable public access to serve files directly without a Worker.
1. Go to R2 > bucket > Settings > Public access.
2. Enable and set a custom domain (e.g., assets.example.com).
3. Objects are accessible at https://assets.example.com/<key>.
# Or enable via the r2.dev subdomain (for testing)
# Bucket Settings > R2.dev subdomain > Allow Access
# URL: https://pub-<hash>.r2.dev/<key>Lifecycle Rules
Configure automatic object expiration or transition.
# Set lifecycle rules via the Cloudflare dashboard:
# R2 > bucket > Settings > Object lifecycle rules
# Or via API
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/r2/buckets/app-assets/lifecycle" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"rules": [
{
"id": "expire-tmp-files",
"enabled": true,
"conditions": { "prefix": "tmp/" },
"actions": { "deleteObject": { "daysAfterCreationDate": 7 } }
},
{
"id": "expire-old-logs",
"enabled": true,
"conditions": { "prefix": "logs/" },
"actions": { "deleteObject": { "daysAfterCreationDate": 90 } }
}
]
}'CORS Configuration
# Set CORS policy for browser-based uploads
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/r2/buckets/app-assets/cors" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"corsRules": [
{
"allowedOrigins": ["https://example.com"],
"allowedMethods": ["GET", "PUT", "HEAD"],
"allowedHeaders": ["Content-Type", "Authorization"],
"maxAgeSeconds": 3600
}
]
}'Troubleshooting
| Symptom | Cause | Fix |
|---------|-------|-----|
| NoSuchBucket error via S3 API | Wrong endpoint or bucket name | Verify endpoint is https://<ACCOUNT_ID>.r2.cloudflarestorage.com |
| SignatureDoesNotMatch | Incorrect secr
… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- intl-expansion – Chiến lược mở rộng thị trường quốc tế: chọn thị trường, hình thức thâm nhập, bản địa…
- cloudflare-workers-expert – Chuyên gia về Cloudflare Workers và hệ sinh thái Edge Computing. Bao gồm Wrangler, KV…
- pixel-art – Pixel art với bảng màu theo thế hệ máy (NES, Game Boy, PICO-8).
- pokemon-player – Chơi Pokemon qua trình giả lập không giao diện và đọc RAM.
- polymarket – Truy vấn Polymarket: thị trường, giá, sổ lệnh (orderbook), lịch sử.
- knowledge-ops – Dùng khi Head of Ops, Knowledge Manager hoặc TPM-Internal cần viết, kiểm tra hoặc dọn…
- comment-to-dm-cta – Lập kế hoạch CTA \"Comment KEYWORD\" cho Instagram Reel (từ khóa, lớp phủ, caption, nội…
- competency-matrix – Ma trận năng lực với mức thành thạo kỳ vọng theo chức danh và cấp bậc, kèm phương pháp…