使用 CLI 連接 cloudflare R2
安裝 AWS CLI(Linux)
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
設定 AWS CLI 設定檔
取得 token
登入 Cloudflare Dashboard → 選擇使用 R2 的帳號 → 左側選單「R2」→ 點選「API」→管理權杖裡面, 新增新的 Token 得到 Access Key ID 和 Secret Access Key,只會顯示一次,要留好。之前有生成過符合需求 policy 的 token也可以用以前的。
打指令
在終端機輸入:
aws configure --profile [porfile]
為了示範方便,porfile 我設定 cloudflare-r2。
終端機會提示輸入 Access Key ID 和 Secret Access Key,大概像這樣
AWS Access Key ID: <你的 Access Key>
AWS Secret Access Key: <你的 Secret Key>
Default region name: auto
Default output format: json
option
到 ~/.aws 編輯設定檔,剛剛打錯的東西都可以到這裡來修正、優化。這邊有兩個檔案,
confin 和 credentials ,我會在 credentials 多加一個 endpoint_url ,免得每次連線指令都在重複打。
[cloudflare-r2]
aws_access_key_id = <your-access-key>
aws_secret_access_key = <your-sercet-key>
endpoint_url = https://account-id.r2.cloudflarestorage.com
endpoint_url 是認人的,不看儲存體,在 左側選單「R2」→ 點選「API」→搭配使用 R2 與 API 可以直接複製他的值
指令範例
credentials 要跟我一樣有寫 endpoint_url 才能這麼乾淨,否則都要加上 ```--endpoint_url = https://account-id.r2.cloudflarestorage.com``
- 列出 r2 某個 bucket 該層的檔案
aws s3 ls s3://<bucket-name> --profile cloudflare-r2
- 上傳本地檔案
aws s3 cp path/to/file.txt s3://<bucket-name> --profile cloudflare-r2 - 刪除檔案 aws s3 rm s3://bucket-name/fonts/old.txt --profile cloudflare-r2
- 遞迴刪除檔案
aws s3 rm s3://<bucket-name>/<folder>/ --recursive --profile cloudflare-r2
為什麼指令這樣寫?
接著來看點我正在寫得指令,這是列出我某個儲存的資料夾內容的指令。
aws s3 ls s3://emfont/fonts/ --profile cloudflare-r2
🔍 第一個 s3(在 aws s3 ls)
這是 AWS CLI 的命令群組,代表你要操作的是 S3 類的指令。
整個 AWS CLI 的語法是這樣的:
aws <服務> <動作> <參數>
所以:
aws s3 ls ...
意思是:「我要用 aws CLI 執行 s3 服務的 ls 動作」。
🔍 第二個 s3://emfont/fonts/
這是 S3 URI(統一資源識別碼) 的格式,代表你要操作的對象位置。
它的格式是這樣:
s3://<bucket-name>/<object-path>
所以:
s3://emfont/fonts/
意思是:「我在 S3 裡的 emfont 這個 bucket 裡的 fonts/ 資料夾下」。
這其實跟網址 https://example.com/dir/file.txt 很像,但是給 CLI 用的路徑。
aws s3 ls s3://emfont/fonts/ --profile cloudflare-r2
意思就是:
「用 AWS CLI 的
s3模組來執行ls(列出內容)指令,針對emfontbucket 裡的fonts/資料夾,使用我指定的 Cloudflare R2 認證」。
同場加映 S3 URI、HTTP URL 和 Cloudflare R2 的幾種常見用法
| 你要做什麼 | 建議使用格式 | 備註 |
|---|---|---|
| 用 CLI 上傳/刪除物件 | s3://bucket/key + --endpoint-url | 或設定在 ~/.aws/config 裡 |
| 用程式上傳檔案(Python boto3) | S3 URI + 指定 endpoint | endpoint 一定要設 |
| 給瀏覽器存取檔案 | https://*.r2.dev/... | 公開存取用 |
| 看 R2 管理介面 | Cloudflare 儀表板 | 可產生 Access Key、設定 Bucket 權限 |