alibabacloud-oss-manage-cron-upload

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OSS Scheduled Local Sync

OSS本地定时同步

Plan and validate scheduled local-folder-to-OSS uploads with an aliyun-CLI-first workflow.
基于aliyun CLI优先的工作流,规划并校验本地文件夹到OSS的定时上传功能。

Scenario Description

场景描述

This skill covers the case where a local folder changes over time and must be uploaded to OSS on a recurring schedule.
Architecture:
Local folder + aliyun CLI (integrated ossutil) + cron/Task Scheduler + OSS Bucket
Capability split:
  • [aliyun CLI]
    installation checks, profile verification, command discovery, OSS-side verification, and integrated
    aliyun ossutil
    upload/list commands.
  • [OS-local]
    cron or Windows Task Scheduler configuration.
  • [Manual/Console]
    RAM policy attachment and optional visual verification in the OSS Console.
本技能适用于本地文件夹内容随时间变化,需要按固定周期上传到OSS的场景。
架构
本地文件夹 + aliyun CLI(集成ossutil) + cron/任务计划程序 + OSS Bucket
能力拆分
  • [aliyun CLI]
    安装检查、配置文件验证、命令发现、OSS侧校验,以及集成的
    aliyun ossutil
    上传/列表命令。
  • [操作系统本地]
    cron或Windows任务计划程序配置。
  • [手动/控制台]
    RAM权限策略挂载,以及可选的OSS控制台可视化验证。

Installation

安装

Pre-check: Aliyun CLI >= 3.3.3 required Run
aliyun version
to verify
>= 3.3.3
. If not installed or version too low, see
references/cli-installation-guide.md
for installation instructions. Then run
aliyun configure set --auto-plugin-install true
. Finally, enable AI safety mode to prevent dangerous operations:
bash
aliyun configure ai-mode enable
Required local tools:
ToolRequiredPurposeVerify
aliyun
CLI
YesCredential gate, command discovery, and integrated
ossutil
upload/list surface
aliyun version
and
aliyun ossutil --help
cron
or
schtasks
YesLocal recurring execution
crontab -l
or
schtasks /Query /TN "OSS Scheduled Sync"
Use
references/cli-installation-guide.md
only for CLI installation and plugin setup. For this skill, use the integrated
aliyun ossutil
command surface — do not require standalone
ossutil
installation or bare
ossutil
commands.
预检查:要求Aliyun CLI版本 >= 3.3.3 运行
aliyun version
确认版本符合
>= 3.3.3
要求。如果未安装或版本过低,参考
references/cli-installation-guide.md
完成安装步骤。 随后运行
aliyun configure set --auto-plugin-install true
。 最后开启AI安全模式以避免危险操作:
bash
aliyun configure ai-mode enable
所需本地工具:
工具是否必须用途验证方式
aliyun
CLI
凭证校验入口、命令发现、集成
ossutil
上传/列表能力入口
aliyun version
aliyun ossutil --help
cron
schtasks
本地周期执行调度
crontab -l
schtasks /Query /TN "OSS Scheduled Sync"
仅在CLI安装和插件配置阶段使用
references/cli-installation-guide.md
。本技能使用集成的
aliyun ossutil
命令集,不要求安装独立版
ossutil
或使用原生
ossutil
命令。

Environment Variables

环境变量

No extra cloud-specific environment variables are required beyond an already configured Alibaba Cloud profile.
Optional local variables used in examples:
VariableRequired/OptionalDescriptionDefault Value
ALIBABA_CLOUD_PROFILE
OptionalSelect a preconfigured Alibaba Cloud CLI profileCLI current profile
ALIYUN_BIN
OptionalAbsolute path to
aliyun
if it is not already in
PATH
aliyun
OSS_SYNC_LOG
OptionalLog file path for scheduled executionOS-specific local path
除了已配置完成的阿里云配置文件外,无需额外的云服务相关环境变量。
示例中使用的可选本地变量:
变量必选/可选描述默认值
ALIBABA_CLOUD_PROFILE
可选选择预先配置的阿里云CLI配置文件CLI当前生效配置
ALIYUN_BIN
可选
aliyun
不在
PATH
中,需指定其绝对路径
aliyun
OSS_SYNC_LOG
可选定时执行的日志文件路径操作系统对应默认本地路径

Parameter Confirmation

参数确认

Parameter Extraction — Extract all user-customizable parameters directly from the user's request. When the user's message already specifies values (such as region, bucket name, paths, schedule, or MaxAge), use those values directly without asking for re-confirmation. Only ask the user for clarification when a required parameter is genuinely missing from their request and cannot be reasonably inferred from context.
Parameter NameRequired/OptionalDescriptionValidation PatternDefault Value
RegionId
RequiredOSS region such as
cn-hangzhou
`^[a-z]{2}-[a-z]+(-[0-9]+)$`
BucketName
RequiredTarget OSS bucket name
^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$
None
TargetOssPrefix
RequiredBucket-relative target OSS prefix such as
backup/photos/
(confirm without a leading
/
)
^[A-Za-z0-9/_.-]*$
(no leading
/
)
None
LocalSourcePath
RequiredLocal folder to uploadAbsolute path, no
~
,
$
, backtick, or
;
None
Schedule
RequiredCron expression or Windows schedule time/frequencyStandard 5-field cron or
schtasks
time
None
MaxAge
Required
aliyun ossutil --max-age
window such as
7d
or
24h
^[0-9]+[dhm]$
None
OperatingSystem
Required
linux
,
macos
, or
windows
`^(linuxmacos
BucketAlreadyExists
RequiredWhether the target bucket already exists`^(yesno)$`
AliyunBinaryPath
OptionalAbsolute path to
aliyun
for scheduler use
Absolute path, no
$
, backtick, or
;
aliyun
LogPath
OptionalLocal log path for the scheduled jobAbsolute path, no
$
, backtick, or
;
OS-specific local path
Input Validation — All parameters must be validated before use. Treat all inputs (including values extracted from user messages) as untrusted. Before substituting any parameter into a shell command:
  1. Validate the value against the Validation Pattern column above. Reject values that do not match.
  2. BucketName
    must contain only lowercase letters, digits, and hyphens (
    [a-z0-9-]
    ), be 3–63 characters, and must not start or end with a hyphen.
  3. RegionId
    must match the Alibaba Cloud region format (e.g.,
    cn-hangzhou
    ,
    us-west-1
    ,
    ap-southeast-5
    ).
  4. MaxAge
    must be a positive integer followed by
    d
    (days),
    h
    (hours), or
    m
    (minutes).
  5. LocalSourcePath
    ,
    AliyunBinaryPath
    , and
    LogPath
    must be absolute paths and must not contain shell metacharacters (
    $
    ,
    `
    ,
    $(
    ,
    ;
    ,
    |
    ,
    &
    ,
    >
    ,
    <
    ,
    \n
    ).
  6. TargetOssPrefix
    must contain only alphanumeric characters,
    /
    ,
    _
    ,
    .
    , and
    -
    , and must not start with
    /
    .
  7. If any parameter fails validation, stop and report the error to the user. Do not attempt to sanitize or escape invalid values — reject them outright.
参数提取:直接从用户请求中提取所有可自定义参数。 当用户消息中已明确指定参数值(如地域、存储桶名称、路径、调度周期、MaxAge等),直接使用该值无需二次确认。 仅当必填参数确实未在用户请求中提供,且无法从上下文合理推断时,才需要询问用户确认。
参数名称必选/可选描述校验规则默认值
RegionId
必填OSS地域,例如
cn-hangzhou
`^[a-z]{2}-[a-z]+(-[0-9]+)$`
BucketName
必填目标OSS存储桶名称
^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$
TargetOssPrefix
必填存储桶内的目标OSS前缀,例如
backup/photos/
(确认无开头的
/
^[A-Za-z0-9/_.-]*$
(无开头的
/
LocalSourcePath
必填待上传的本地文件夹绝对路径,不能包含
~
$
、反引号或
;
Schedule
必填Cron表达式或Windows任务调度时间/频率标准5段cron表达式或
schtasks
支持的时间格式
MaxAge
必填
aliyun ossutil --max-age
时间窗口,例如
7d
24h
^[0-9]+[dhm]$
OperatingSystem
必填
linux
macos
windows
`^(linuxmacos
BucketAlreadyExists
必填目标存储桶是否已存在`^(yesno)$`
AliyunBinaryPath
可选调度器使用的
aliyun
绝对路径
绝对路径,不能包含
$
、反引号或
;
aliyun
LogPath
可选定时任务的本地日志路径绝对路径,不能包含
$
、反引号或
;
操作系统对应默认本地路径
输入校验:所有参数使用前必须完成校验 所有输入(包括从用户消息中提取的值)都视为不可信。在将任何参数代入shell命令前:
  1. 对照上方校验规则列验证参数值,不符合的直接拒绝。
  2. BucketName
    只能包含小写字母、数字和连字符(
    [a-z0-9-]
    ),长度3-63位,且不能以连字符开头或结尾。
  3. RegionId
    必须符合阿里云地域格式(例如
    cn-hangzhou
    us-west-1
    ap-southeast-5
    )。
  4. MaxAge
    必须是正整数后跟
    d
    (天)、
    h
    (小时)或
    m
    (分钟)。
  5. LocalSourcePath
    AliyunBinaryPath
    LogPath
    必须是绝对路径,且不能包含shell元字符(
    $
    `
    $(
    ;
    |
    &
    >
    <
    \n
    )。
  6. TargetOssPrefix
    只能包含字母、数字、
    /
    _
    .
    -
    ,且不能以
    /
    开头。
  7. 若任何参数校验失败,停止流程并向用户上报错误,不要尝试清理或转义无效值,直接拒绝即可。

Authentication

鉴权

Pre-check: Alibaba Cloud Credentials Required
Security Rules:
  • NEVER read, echo, or print AK/SK values (e.g.,
    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    is FORBIDDEN)
  • NEVER read or
    cat
    credential files such as
    ~/.aliyun/config.json
    ,
    ~/.ossutil/config
    , or any file that may contain secrets
  • NEVER ask the user to input AK/SK directly in the conversation or command line
  • NEVER use
    aliyun configure set
    with literal credential values
  • ONLY use
    aliyun configure list
    to check credential status
bash
aliyun configure list
Check the output for a valid profile (AK, STS, or OAuth identity).
If no valid profile exists, STOP here.
  1. Obtain credentials from Alibaba Cloud Console
  2. Configure credentials outside of this session (via
    aliyun configure
    in terminal or environment variables in shell profile)
  3. Return and re-run after
    aliyun configure list
    shows a valid profile
Reuse the active CLI profile for all
aliyun ossutil
commands. Do not print or hardcode secrets. Do not replace this gate with
ossutil config
or any other secret-entry flow.
预检查:需要阿里云凭证
安全规则:
  • 绝对禁止读取、回显或打印AK/SK值(例如禁止执行
    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
  • 绝对禁止读取或
    cat
    凭证文件,例如
    ~/.aliyun/config.json
    ~/.ossutil/config
    或任何可能包含密钥的文件
  • 绝对禁止要求用户在对话或命令行中直接输入AK/SK
  • 绝对禁止使用明文凭证值执行
    aliyun configure set
    命令
  • 仅允许使用
    aliyun configure list
    检查凭证状态
bash
aliyun configure list
检查输出中是否存在有效配置(AK、STS或OAuth身份)。
如果不存在有效配置,直接停止流程
  1. 阿里云控制台获取凭证
  2. 在当前会话外配置凭证(通过终端执行
    aliyun configure
    或在shell配置文件中设置环境变量)
  3. aliyun configure list
    显示有效配置后,再返回重新执行流程
所有
aliyun ossutil
命令复用当前生效的CLI配置,不要打印或硬编码密钥,不要用
ossutil config
或其他密钥输入流程替换本校验入口。

RAM Policy

RAM权限策略

The default workflow needs least-privilege access for bucket discovery, bucket metadata verification, and object upload under the confirmed prefix.
ScopeRequired Actions
Account-level verification
oss:ListBuckets
Target bucket verification
oss:GetBucketInfo
Incremental upload to target prefix
oss:PutObject
,
oss:GetObject
,
oss:ListObjects
Optional test cleanup
oss:DeleteObject
Use
references/ram-policies.md
for the policy JSON and the prefix-scoped resource examples.
Do not redefine the default minimum set around
oss:AbortMultipartUpload
. In this skill, the default least-privilege path stays anchored on bucket discovery, bucket metadata verification, and prefix-scoped upload/list/read actions. Multipart-cleanup permissions are follow-up work only when the user explicitly asks for them.
默认工作流需要最小权限,用于存储桶发现、存储桶元数据校验、以及指定前缀下的对象上传。
作用范围所需操作权限
账号级校验
oss:ListBuckets
目标存储桶校验
oss:GetBucketInfo
目标前缀下的增量上传
oss:PutObject
oss:GetObject
oss:ListObjects
可选测试清理
oss:DeleteObject
参考
references/ram-policies.md
获取策略JSON和前缀级资源示例。
不要重新定义基于
oss:AbortMultipartUpload
的默认最小权限集。本技能的默认最小权限路径始终围绕存储桶发现、存储桶元数据校验、前缀级上传/列表/读取操作。仅当用户明确要求时,才额外提供分片清理权限。

Core Workflow

核心工作流

Execute, don't just document. Run each step's commands directly in the environment. Do not only write solution documents or scripts — actually execute
aliyun version
,
aliyun configure list
,
aliyun ossutil cp
, etc. against the live environment.
Extract
RegionId
,
BucketName
,
TargetOssPrefix
,
LocalSourcePath
,
Schedule
,
MaxAge
,
OperatingSystem
, and
BucketAlreadyExists
from the user's request. Only ask the user if a required parameter is genuinely missing.
执行而不仅仅是文档记录:直接在环境中运行每个步骤的命令。不要仅编写解决方案文档或脚本,要真实在运行环境中执行
aliyun version
aliyun configure list
aliyun ossutil cp
等命令。
从用户请求中提取
RegionId
BucketName
TargetOssPrefix
LocalSourcePath
Schedule
MaxAge
OperatingSystem
BucketAlreadyExists
。仅当必填参数确实缺失时才询问用户。

Step 1: Verify CLI and credentials
[aliyun CLI]

步骤1:校验CLI和凭证
[aliyun CLI]

bash
aliyun version
aliyun configure list
aliyun configure ai-mode enable
Verify that:
  • aliyun
    version is
    >= 3.3.3
  • at least one valid profile is present
  • AI safety mode is enabled (dangerous operations will be blocked)
If the version is too low or
aliyun
is missing, see
references/cli-installation-guide.md
. Do not work around a missing CLI by switching to standalone
ossutil
or
aliyun oss sync
.
bash
aliyun version
aliyun configure list
aliyun configure ai-mode enable
校验以下条件:
  • aliyun
    版本为
    >= 3.3.3
  • 至少存在一个有效配置
  • AI安全模式已开启(危险操作会被拦截)
如果版本过低或缺少
aliyun
,参考
references/cli-installation-guide.md
。不要切换到独立版
ossutil
aliyun oss sync
来绕过CLI缺失问题。

Step 2: Verify or create the bucket prerequisite
[aliyun CLI]

步骤2:校验或创建存储桶前置条件
[aliyun CLI]

Always start by checking the candidate bucket inventory:
bash
aliyun ossutil api list-buckets --output-format json \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
If
BucketAlreadyExists=yes
, verify the selected bucket explicitly:
bash
aliyun ossutil stat "oss://${BucketName}" --region "${RegionId}" --output-format json \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
Cross-region note: When the active CLI profile's region (shown by
aliyun configure list
) differs from the target bucket's
RegionId
, you must add
--region "${RegionId}"
to
stat
,
ls
, and
cp
commands. Using
--endpoint
alone is insufficient because the request signing region must also match. The
--region
flag overrides both the endpoint and the signing region in a single step.
What to confirm:
  • the bucket name is present in the account inventory
  • the bucket region matches
    RegionId
  • the bucket is reachable with the active profile
  • if multiple existing buckets can satisfy the same backup target, you can remind the user that a bucket with versioning enabled is preferable for backup safety, but this is only a recommendation and does not block using the confirmed existing bucket
If
BucketAlreadyExists=no
, use the check-then-act idempotent pattern:
  1. First run
    list-buckets
    (above) to confirm the bucket truly does not exist in the account — if it already exists, skip creation and go directly to
    stat
    verification.
  2. Only if the bucket is confirmed absent, create it by following the existing creation flow of this skill.
  3. After creation, immediately re-run
    stat
    to verify:
bash
aliyun ossutil stat "oss://${BucketName}" --region "${RegionId}" --output-format json \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
Optional recommendation for recurring backup scenarios:
  • if multiple candidate buckets exist and one already has versioning enabled, mention that it is preferable for backup rollback safety
  • if the confirmed existing bucket does not have versioning enabled, it can still be used for this workflow; enabling versioning is only an optional hardening suggestion, not a prerequisite
Keep
aliyun ossutil
as the canonical surface for upload and verification commands such as
cp
,
ls
, and
stat
. For bucket creation, follow the existing creation flow already documented by this skill instead of inventing a new command family here. Do not fabricate success, extra deployment files, or fake local artifacts just to cover a missing prerequisite.
始终先检查候选存储桶清单:
bash
aliyun ossutil api list-buckets --output-format json \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
如果
BucketAlreadyExists=yes
,显式校验选中的存储桶:
bash
aliyun ossutil stat "oss://${BucketName}" --region "${RegionId}" --output-format json \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
跨地域注意事项:当当前CLI配置的地域(通过
aliyun configure list
查看)与目标存储桶的
RegionId
不同时,必须
stat
ls
cp
命令中添加
--region "${RegionId}"
。仅使用
--endpoint
不足够,因为请求签名的地域也需要匹配。
--region
参数可以一步同时覆盖端点和签名地域配置。
需要确认的内容:
  • 存储桶名称存在于账号清单中
  • 存储桶地域与
    RegionId
    匹配
  • 当前配置可以正常访问该存储桶
  • 如果有多个现有存储桶都可以满足相同备份目标,可以提醒用户优先选择开启了版本控制的存储桶以提升备份安全性,但这只是建议,不会阻塞使用用户确认的现有存储桶
如果
BucketAlreadyExists=no
,使用先检查后操作的幂等模式:
  1. 首先执行上述
    list-buckets
    命令确认存储桶确实不存在于账号中——如果已存在,跳过创建步骤直接进入
    stat
    校验。
  2. 仅当确认存储桶不存在时,按照本技能现有创建流程创建存储桶。
  3. 创建完成后,立即重新执行
    stat
    命令校验:
bash
aliyun ossutil stat "oss://${BucketName}" --region "${RegionId}" --output-format json \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
定期备份场景的可选建议:
  • 如果有多个候选存储桶,且其中一个已开启版本控制,说明其更适合备份回滚安全需求
  • 如果确认的现有存储桶未开启版本控制,仍然可以用于本工作流;开启版本控制只是可选的加固建议,不是前置条件
上传和校验命令(如
cp
ls
stat
)始终使用
aliyun ossutil
作为标准入口。存储桶创建按照本技能已记录的现有流程执行,不要自定义新的命令集。不要为了覆盖缺失的前置条件而伪造成功结果、额外部署文件或虚假本地产物。

Step 3: Run the canonical incremental upload test
[aliyun CLI / integrated ossutil]

步骤3:执行标准增量上传测试
[aliyun CLI / 集成ossutil]

Use the official data-plane command family for the actual scheduled upload job through
aliyun ossutil
:
bash
aliyun ossutil cp "${LocalSourcePath}" "oss://${BucketName}/${TargetOssPrefix}" \
  -r -u \
  --max-age "${MaxAge}" \
  --region "${RegionId}" \
  --read-timeout 300 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
Key rules for this command:
  • -u
    is mandatory: uploads only when the target object is missing or the source file is newer than the existing OSS object
  • -r -u --max-age
    must stay together as the canonical flag set
  • --region "${RegionId}"
    ensures both endpoint and signing region are correct
  • --read-timeout 300 --connect-timeout 30
    prevents the command from hanging indefinitely; adjust
    --read-timeout
    upward for very large files if needed
  • Add
    -f
    only for unattended runs (cron, Task Scheduler, CI)
  • Use absolute paths for
    LocalSourcePath
    (never
    ~
    )
  • Normalize
    TargetOssPrefix
    without a leading
    /
  • Do not substitute with bare
    ossutil
    ,
    aliyun oss sync
    , or
    Cache-Control
    metadata rewrites
If
TargetOssPrefix
is empty, use
oss://${BucketName}/
(with trailing slash). Otherwise use
oss://${BucketName}/${TargetOssPrefix}
after prefix normalization.
If
LocalSourcePath
does not exist
in the current environment (e.g., container or CI runner), create it under the current working directory with a small test file, then run the upload command against it and verify with
aliyun ossutil ls
. This proves the upload path works end-to-end. Do not skip the upload test just because the directory is absent — create it and validate connectivity, permissions, and command correctness:
bash
mkdir -p "${LocalSourcePath}" && echo "test" > "${LocalSourcePath}/test.txt"
aliyun ossutil cp "${LocalSourcePath}" "oss://${BucketName}/${TargetOssPrefix}" \
  -r -u --max-age "${MaxAge}" --region "${RegionId}" \
  --read-timeout 300 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil ls "oss://${BucketName}/${TargetOssPrefix}" --region "${RegionId}" \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
通过
aliyun ossutil
使用官方数据面命令集执行实际定时上传任务:
bash
aliyun ossutil cp "${LocalSourcePath}" "oss://${BucketName}/${TargetOssPrefix}" \
  -r -u \
  --max-age "${MaxAge}" \
  --region "${RegionId}" \
  --read-timeout 300 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
本命令的核心规则:
  • -u
    为必填参数:仅当目标对象不存在,或源文件比现有OSS对象更新时才上传
  • -r -u --max-age
    必须作为标准参数组共同使用
  • --region "${RegionId}"
    确保端点和签名地域都正确
  • --read-timeout 300 --connect-timeout 30
    避免命令无限期挂起;如果需要上传超大文件,可以适当调大
    --read-timeout
  • 仅在非交互运行场景(cron、任务计划程序、CI)中添加
    -f
    参数
  • LocalSourcePath
    使用绝对路径(禁止使用
    ~
  • 标准化
    TargetOssPrefix
    ,移除开头的
    /
  • 不要替换为原生
    ossutil
    aliyun oss sync
    Cache-Control
    元数据重写逻辑
如果
TargetOssPrefix
为空,使用
oss://${BucketName}/
(带尾部斜杠)。否则在标准化前缀后使用
oss://${BucketName}/${TargetOssPrefix}
如果当前环境(如容器或CI运行器)中不存在
LocalSourcePath
,在当前工作目录下创建该路径并添加一个小测试文件,然后执行上传命令,再用
aliyun ossutil ls
校验。这可以证明上传路径端到端可用。不要因为目录不存在就跳过上传测试——创建目录并验证连通性、权限和命令正确性:
bash
mkdir -p "${LocalSourcePath}" && echo "test" > "${LocalSourcePath}/test.txt"
aliyun ossutil cp "${LocalSourcePath}" "oss://${BucketName}/${TargetOssPrefix}" \
  -r -u --max-age "${MaxAge}" --region "${RegionId}" \
  --read-timeout 300 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil ls "oss://${BucketName}/${TargetOssPrefix}" --region "${RegionId}" \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills

Step 4: Wrap the upload in a local script
[aliyun CLI + OS-local]

步骤4:将上传逻辑封装为本地脚本
[aliyun CLI + 操作系统本地]

Minimal script template:
bash
#!/usr/bin/env bash
set -euo pipefail

ALIYUN_BIN="${ALIYUN_BIN:-aliyun}"
LOCAL_SOURCE_PATH="${LocalSourcePath}"   # MUST be an absolute path, never use ~
BUCKET_NAME="${BucketName}"
TARGET_OSS_PREFIX="${TargetOssPrefix#/}"
MAX_AGE="${MaxAge}"
REGION_ID="${RegionId}"
LOG_FILE="${OSS_SYNC_LOG:-$HOME/oss-sync.log}"
READ_TIMEOUT="${READ_TIMEOUT:-600}"
CONNECT_TIMEOUT="${CONNECT_TIMEOUT:-30}"
最小化脚本模板:
bash
#!/usr/bin/env bash
set -euo pipefail

ALIYUN_BIN="${ALIYUN_BIN:-aliyun}"
LOCAL_SOURCE_PATH="${LocalSourcePath}"   # 必须为绝对路径,禁止使用~ 
BUCKET_NAME="${BucketName}"
TARGET_OSS_PREFIX="${TargetOssPrefix#/}"
MAX_AGE="${MaxAge}"
REGION_ID="${RegionId}"
LOG_FILE="${OSS_SYNC_LOG:-$HOME/oss-sync.log}"
READ_TIMEOUT="${READ_TIMEOUT:-600}"
CONNECT_TIMEOUT="${CONNECT_TIMEOUT:-30}"

--- Input validation ---

--- 输入校验 ---

[[ "${BUCKET_NAME}" =~ ^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$ ]] || { echo "ERROR: Invalid BucketName: ${BUCKET_NAME}" >&2; exit 1; } [[ "${REGION_ID}" =~ ^[a-z]{2}-[a-z]+(|-[0-9]+)$ ]] || { echo "ERROR: Invalid RegionId: ${REGION_ID}" >&2; exit 1; } [[ "${MAX_AGE}" =~ ^[0-9]+[dhm]$ ]] || { echo "ERROR: Invalid MaxAge: ${MAX_AGE}" >&2; exit 1; } [[ "${TARGET_OSS_PREFIX}" =~ ^[A-Za-z0-9/_.-]$ ]] || { echo "ERROR: Invalid TargetOssPrefix: ${TARGET_OSS_PREFIX}" >&2; exit 1; } [[ "${LOCAL_SOURCE_PATH}" == / ]] || { echo "ERROR: LocalSourcePath must be absolute: ${LOCAL_SOURCE_PATH}" >&2; exit 1; }
TARGET_URI="oss://${BUCKET_NAME}/"
if [ -n "${TARGET_OSS_PREFIX}" ]; then TARGET_URI="oss://${BUCKET_NAME}/${TARGET_OSS_PREFIX}" fi
"${ALIYUN_BIN}" ossutil cp "${LOCAL_SOURCE_PATH}" "${TARGET_URI}"
-r -u -f
--max-age "${MAX_AGE}"
--region "${REGION_ID}"
--read-timeout "${READ_TIMEOUT}" --connect-timeout "${CONNECT_TIMEOUT}"
--user-agent AlibabaCloud-Agent-Skills >> "${LOG_FILE}" 2>&1

> **Note**: The `-f` flag is included in the script template because the script is intended for unattended cron/Task Scheduler execution where interactive prompts must not block the job. The `--region` flag is preferred over `--endpoint` because it sets both the endpoint and signing region correctly, which is required when the CLI profile's default region differs from the target bucket's region.
[[ "${BUCKET_NAME}" =~ ^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$ ]] || { echo "ERROR: 无效的BucketName: ${BUCKET_NAME}" >&2; exit 1; } [[ "${REGION_ID}" =~ ^[a-z]{2}-[a-z]+(|-[0-9]+)$ ]] || { echo "ERROR: 无效的RegionId: ${REGION_ID}" >&2; exit 1; } [[ "${MAX_AGE}" =~ ^[0-9]+[dhm]$ ]] || { echo "ERROR: 无效的MaxAge: ${MAX_AGE}" >&2; exit 1; } [[ "${TARGET_OSS_PREFIX}" =~ ^[A-Za-z0-9/_.-]$ ]] || { echo "ERROR: 无效的TargetOssPrefix: ${TARGET_OSS_PREFIX}" >&2; exit 1; } [[ "${LOCAL_SOURCE_PATH}" == / ]] || { echo "ERROR: LocalSourcePath必须为绝对路径: ${LOCAL_SOURCE_PATH}" >&2; exit 1; }
TARGET_URI="oss://${BUCKET_NAME}/"
if [ -n "${TARGET_OSS_PREFIX}" ]; then TARGET_URI="oss://${BUCKET_NAME}/${TARGET_OSS_PREFIX}" fi
"${ALIYUN_BIN}" ossutil cp "${LOCAL_SOURCE_PATH}" "${TARGET_URI}"
-r -u -f
--max-age "${MAX_AGE}"
--region "${REGION_ID}"
--read-timeout "${READ_TIMEOUT}" --connect-timeout "${CONNECT_TIMEOUT}"
--user-agent AlibabaCloud-Agent-Skills >> "${LOG_FILE}" 2>&1

> **注意**:脚本模板中包含`-f`参数,因为脚本是为非交互的cron/任务计划程序执行设计的,需要避免交互提示阻塞任务。优先使用`--region`参数而非`--endpoint`,因为它可以同时正确设置端点和签名地域,当CLI配置的默认地域与目标存储桶地域不同时这是必需的。

Step 5: Configure the scheduler
[OS-local]

步骤5:配置调度器
[操作系统本地]

Linux/macOS cron:
For the default Linux/macOS path in this skill, keep
cron
/
crontab
as the documented scheduler surface. Do not silently swap the answer to
launchd
unless the user explicitly asks for a launchd-specific variant.
If
crontab
is not found
: In container or minimal environments,
crontab
may not be pre-installed. Install the
cronie
package first:
  • CentOS/Alibaba Cloud Linux/RHEL:
    yum install -y cronie
  • Debian/Ubuntu:
    apt-get install -y cron
If
systemctl start crond
fails (e.g., no systemd in containers), you can still add cron entries via
crontab
— the cron daemon is not strictly required for entry registration, only for actual execution. In such cases, document the cron entry for the user to deploy on their production host, and do not let the missing daemon block the rest of the workflow.
bash
crontab -e
Example entry (use
echo ... | crontab -
for non-interactive installation):
cron
0 3 * * * /usr/local/bin/oss-sync-upload.sh >> /var/log/oss-sync-cron.log 2>&1
Windows Task Scheduler via local CLI:
bat
schtasks /Create /SC DAILY /ST 03:00 /TN "OSS Scheduled Sync" /TR "C:\tools\oss-sync-upload.bat"
Label this step clearly as OS-local. It is not an Alibaba Cloud API action. Keep the scheduler output minimal and directly actionable; do not explode this step into extra README files, XML exports, PowerShell wrappers, demo payloads, or other auxiliary artifacts unless the user explicitly asks for them.
Linux/macOS cron
本技能默认Linux/macOS路径下,使用
cron
/
crontab
作为标准调度器入口。除非用户明确要求
launchd
专属版本,否则不要静默替换为
launchd
方案。
如果找不到
crontab
:在容器或精简环境中,可能未预装
crontab
。先安装
cronie
包:
  • CentOS/阿里云Linux/RHEL:
    yum install -y cronie
  • Debian/Ubuntu:
    apt-get install -y cron
如果
systemctl start crond
执行失败(例如容器中没有systemd),仍然可以通过
crontab
添加cron条目——cron守护进程仅对实际执行是必需的,不影响条目注册。这种情况下,为用户记录cron条目供其在生产主机上部署即可,不要因为缺少守护进程阻塞后续工作流。
bash
crontab -e
示例条目(非交互安装可使用
echo ... | crontab -
):
cron
0 3 * * * /usr/local/bin/oss-sync-upload.sh >> /var/log/oss-sync-cron.log 2>&1
Windows任务计划程序 本地CLI配置:
bat
schtasks /Create /SC DAILY /ST 03:00 /TN "OSS Scheduled Sync" /TR "C:\tools\oss-sync-upload.bat"
明确标注本步骤属于操作系统本地操作,不是阿里云API操作。保持调度器输出简洁、可直接执行;除非用户明确要求,否则不要扩展出额外README文件、XML导出、PowerShell封装、演示负载或其他辅助产物。

Step 6: Verify the upload target
[aliyun CLI / integrated ossutil]

步骤6:校验上传目标
[aliyun CLI / 集成ossutil]

Always run this verification after any upload (including test uploads from Step 3):
bash
aliyun ossutil ls "oss://${BucketName}/${TargetOssPrefix}" --region "${RegionId}" \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
Confirm that the expected objects appear under the target prefix. Do not skip this step — it proves end-to-end connectivity and permissions.
If the user wants a manual visual check, label it clearly as
[Manual/Console]
and confirm the target prefix in the OSS Console.
每次上传后(包括步骤3的测试上传)都必须执行本校验:
bash
aliyun ossutil ls "oss://${BucketName}/${TargetOssPrefix}" --region "${RegionId}" \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
确认目标前缀下存在预期的对象。不要跳过本步骤——它可以证明端到端连通性和权限正常。
如果用户需要手动可视化检查,明确标注为
[手动/控制台]
操作,指引用户在OSS控制台中确认目标前缀。

Step 7: State the capability boundary clearly

步骤7:明确说明能力边界

Always state these limitations when relevant:
  • The actual incremental sync step runs through
    aliyun ossutil
    .
    This skill stays on the
    aliyun
    CLI surface and does not require a separate standalone
    ossutil
    installation.
  • Scheduler setup is OS-local. Cron and Task Scheduler are configured on the host OS, not through Alibaba Cloud APIs.
  • RAM policy attachment is typically manual or follows the user's existing IAM workflow.
  • Bucket creation should happen before scheduled upload when the target bucket is missing. Follow the existing creation flow of this skill for that prerequisite.
  • If multiple equivalent existing buckets are available, it is fine to remind the user that a versioning-enabled bucket is preferable for backup safety. If no versioned bucket is available, continue with the confirmed existing bucket instead of blocking the workflow.
  • Optional OSS Console checks are manual.
  • Do not simulate success. When a prerequisite is missing, say so plainly instead of creating fake local test data, pretend execution logs, or extra packaging artifacts.
相关场景下必须明确说明以下限制:
  • 实际增量同步步骤通过
    aliyun ossutil
    执行
    。本技能始终基于
    aliyun
    CLI入口,无需单独安装独立版
    ossutil
  • 调度器配置属于操作系统本地操作。Cron和任务计划程序在主机操作系统上配置,不通过阿里云API操作。
  • RAM权限策略挂载通常为手动操作,或遵循用户现有IAM工作流
  • 目标存储桶缺失时,需要在定时上传配置前先创建存储桶。该前置条件按照本技能现有创建流程执行。
  • 如果有多个等效的现有存储桶可用,可以提醒用户优先选择开启版本控制的存储桶以提升备份安全性。如果没有版本控制存储桶,继续使用用户确认的现有存储桶即可,不要阻塞工作流。
  • 可选OSS控制台检查为手动操作
  • 不要模拟成功结果。当前置条件缺失时,明确说明情况,不要创建虚假本地测试数据、伪造执行日志或额外打包产物。

Success Verification Method

成功验证方法

Use
references/verification-method.md
as the authoritative checklist.
Minimum pass conditions:
  1. aliyun configure list
    shows a valid profile.
  2. aliyun ossutil cp --help
    succeeds.
  3. the canonical
    aliyun ossutil cp ... -r -u --max-age ... --region ...
    command completes without permission or endpoint errors.
  4. aliyun ossutil ls ... --region ...
    shows the expected uploaded objects under the confirmed prefix.
  5. the upload command keeps
    -u
    , meaning it uploads only when the target object is missing or the local source file is newer than the existing OSS object.
  6. the local scheduler entry is visible through
    crontab -l
    or Task Scheduler history/query, or is documented for the user when crontab is not available in the current environment.
参考
references/verification-method.md
作为权威检查清单。
最低通过条件:
  1. aliyun configure list
    显示有效配置。
  2. aliyun ossutil cp --help
    执行成功。
  3. 标准命令
    aliyun ossutil cp ... -r -u --max-age ... --region ...
    执行完成,无权限或端点错误。
  4. aliyun ossutil ls ... --region ...
    显示确认的前缀下存在预期上传对象。
  5. 上传命令保留
    -u
    参数,即仅当目标对象缺失或本地源文件比现有OSS对象更新时才上传。
  6. 本地调度条目可通过
    crontab -l
    或任务计划程序历史/查询可见,或当当前环境不可用crontab时已为用户记录该条目。

Cleanup

清理

Cleanup is optional because this skill is intended for recurring sync, but test artifacts and scheduler entries can be removed safely.
Linux/macOS cron
[OS-local]
:
  • remove the cron line with
    crontab -e
  • delete the local script and log file only if the user explicitly wants rollback
Windows Task Scheduler
[OS-local]
:
bat
schtasks /Delete /TN "OSS Scheduled Sync" /F
Optional OSS test cleanup
[aliyun CLI / integrated ossutil]
:
bash
aliyun ossutil rm "oss://${BucketName}/${TargetOssPrefix}test-object.txt" --region "${RegionId}" \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
Do not delete the bucket or production objects unless the user explicitly asks for that cleanup scope.
Disable AI safety mode
[aliyun CLI]
:
After all tasks are completed, disable AI safety mode to restore normal CLI behavior:
bash
aliyun configure ai-mode disable
清理为可选操作,因为本技能是为定期同步设计的,但测试产物和调度条目可以安全移除。
Linux/macOS cron
[操作系统本地]
  • 执行
    crontab -e
    删除对应cron行
  • 仅当用户明确要求回滚时,才删除本地脚本和日志文件
Windows任务计划程序
[操作系统本地]
bat
schtasks /Delete /TN "OSS Scheduled Sync" /F
可选OSS测试清理
[aliyun CLI / 集成ossutil]
bash
aliyun ossutil rm "oss://${BucketName}/${TargetOssPrefix}test-object.txt" --region "${RegionId}" \
  --read-timeout 60 --connect-timeout 30 \
  --user-agent AlibabaCloud-Agent-Skills
除非用户明确要求对应清理范围,否则不要删除存储桶或生产对象。
关闭AI安全模式
[aliyun CLI]
所有任务完成后,关闭AI安全模式恢复CLI正常行为:
bash
aliyun configure ai-mode disable

API and Command Tables

API与命令表

See
references/related-apis.md
for the command inventory, OSS capability notes, and validation notes. That file is reference metadata only.
参考
references/related-apis.md
获取命令清单、OSS能力说明和校验说明。该文件仅为参考元数据。

Best Practices

最佳实践

  1. Keep
    aliyun
    for pre-checks, command discovery, bucket verification, and integrated
    aliyun ossutil cp
    for the actual scheduled upload.
  2. Use
    --region "${RegionId}"
    on all
    aliyun ossutil
    commands (
    stat
    ,
    cp
    ,
    ls
    ,
    rm
    ) to ensure both endpoint and signing region are correct. This is especially important when the CLI profile's default region differs from the target bucket's region. Do not rely on
    --endpoint
    alone, as it does not override the signing region and will fail with "Invalid signing region in Authorization header" errors when using STS tokens across regions.
  3. Keep scheduler steps labeled as OS-local so the user understands they are outside Alibaba Cloud APIs.
  4. Use the narrowest RAM policy possible: bucket inventory at account scope, bucket info on the target bucket, and object upload only on the confirmed prefix.
  5. Run
    aliyun version
    and
    aliyun configure list
    on the target machine before live execution.
  6. Never print AK/SK values, never hardcode them in scripts, never read credential files like
    ~/.aliyun/config.json
    , and never replace the credential gate with inline secret handling.
  7. If the bucket does not exist, create it first before configuring scheduled upload. If multiple existing buckets can satisfy the same backup target, you may remind the user that a versioning-enabled bucket is preferable for backup safety, but if no such bucket exists, continue with the confirmed existing bucket.
  8. Always use absolute paths for
    LocalSourcePath
    in commands and scripts. Do not use
    ~
    (tilde) because it may not expand inside quoted strings, causing "not a directory" errors.
  9. In generated scripts intended for cron or Task Scheduler, include the
    -f
    flag to prevent interactive confirmation prompts from blocking unattended execution.
  1. 预检查、命令发现、存储桶校验使用
    aliyun
    ,实际定时上传使用集成的
    aliyun ossutil cp
  2. 所有
    aliyun ossutil
    命令(
    stat
    cp
    ls
    rm
    )都添加
    --region "${RegionId}"
    参数,确保端点和签名地域都正确。当CLI配置的默认地域与目标存储桶地域不同时这一点尤为重要。不要仅依赖
    --endpoint
    ,因为它不会覆盖签名地域,跨地域使用STS令牌时会出现“Authorization头中签名地域无效”错误。
  3. 明确标注调度器步骤为操作系统本地操作,让用户理解这些操作不属于阿里云API范畴。
  4. 使用最小范围的RAM权限策略:账号级别的存储桶清单权限、目标存储桶的信息读取权限、仅确认前缀下的对象上传权限。
  5. 生产执行前,在目标机器上运行
    aliyun version
    aliyun configure list
    校验。
  6. 永远不要打印AK/SK值,不要在脚本中硬编码,不要读取
    ~/.aliyun/config.json
    等凭证文件,不要用内联密钥处理替换凭证校验入口。
  7. 如果存储桶不存在,先创建存储桶再配置定时上传。如果有多个现有存储桶都可以满足相同备份目标,可以提醒用户优先选择开启版本控制的存储桶以提升备份安全性,但如果没有这类存储桶,继续使用用户确认的现有存储桶即可。
  8. 命令和脚本中
    LocalSourcePath
    始终使用绝对路径,不要使用
    ~
    (波浪号),因为它在引号字符串中可能不会展开,导致“不是目录”错误。
  9. 生成用于cron或任务计划程序的脚本时,包含
    -f
    参数以避免交互确认提示阻塞非交互执行。

Reference Links

参考链接

ReferenceDescription
references/cli-installation-guide.md
Required CLI installation guide copied from the creator skill asset
references/verification-method.md
Pre-check, upload, scheduler, and manual verification checklist
references/related-apis.md
aliyun
and integrated
ossutil
command inventory with OSS API mapping
references/ram-policies.md
Least-privilege RAM policy guidance for verification and upload
references/acceptance-criteria.md
Correct and incorrect command patterns for this scenario
参考文件描述
references/cli-installation-guide.md
从创建者技能资产中拷贝的必备CLI安装指南
references/verification-method.md
预检查、上传、调度器和手动校验清单
references/related-apis.md
aliyun
和集成
ossutil
命令清单及OSS API映射关系
references/ram-policies.md
用于校验和上传的最小权限RAM策略指引
references/acceptance-criteria.md
本场景的正确和错误命令模式