Skip to main content

2 posts tagged with "CLI"

View all tags

Aliyun CLI Exit 0 but Failed? jq Default Values Hide Errors

Β· 6 min read

An automation script probed whether a Cloud Assistant command still existed using DescribeCommands with a jq -r '.TotalCount // 0' fallback β€” the API returned an error, the script read TotalCount=0, concluded "command doesn't exist," and dutifully created a duplicate.

Encountered this while running managed hosting for a leading manufacturer's China site β€” Cloud Assistant automation is the dispatch channel for patrols and maintenance on that server.

TL;DR​

Two layers stack into one illusion. Layer one: the aliyun CLI prints API error JSON to stderr with exit code 0, so set -e gets no signal. Layer two: the jq -r '.TotalCount // 0' fallback turns an error response β€” which has no TotalCount field β€” into 0, disguising "query failed" as "query succeeded, zero hits." The house rule: capture with 2>&1, read the raw response first, and never use a jq default as a failure probe. Two more landmines nearby: DescribeCommands takes the singular --CommandId (the array-style --CommandId.1 belongs to InvokeCommand habits and is an error here), and DescribeInvocationResults only accepts a CommandId with object-in-object nesting.

Symptoms: the command exists, the script says it doesn't​

The flow is the classic three-step Cloud Assistant pattern: CreateCommand for a CommandId, InvokeCommand to dispatch, DescribeInvocationResults to read back. Before invoking, the script checks the command object:

# existence probe (buggy)
resp=$(aliyun ecs DescribeCommands --CommandId.1 "c-xxx" 2>&1)
count=$(echo "$resp" | jq -r '.TotalCount // 0')
[ "$count" -eq 0 ] && aliyun ecs CreateCommand ... # judged missing β†’ recreate

In practice this walked into the recreate branch on every run: the command was created in the previous round, yet judged missing in this one. Worse, invoking the freshly recreated CommandId could still hit InvalidCmdId.NotFound β€” the new object isn't ready yet, so both the probe and the recreate were wasted work. Left unfixed, the loop kept burning quota.

Root cause: errors exit 0, and jq washes them into defaults​

Two independent facts compose the trap. On the CLI side, API-level errors are printed to stderr while the process exit code stays 0 β€” exit-code-based defenses like set -e never fire. On the jq side, 2>&1 does carry the error JSON into the pipe, but the object has no TotalCount field, so the // 0 fallback helpfully outputs 0. "API call failed" has been laundered into "call succeeded, zero commands found."

--CommandId.1 is a third, smaller fact: the array-style suffix is the parameter habit of InvokeCommand --InstanceId.1, while DescribeCommands wants the singular --CommandId. The wrong form produces yet another error response, silently swallowed by the same fallback.

Fix: raw response first, jq without fallback probes​

The principle in one line: establish what the response is before asking what a field equals. In code, treat a missing TotalCount as failure instead of as zero:

resp=$(aliyun ecs DescribeCommands --CommandId "c-xxx" 2>&1)  # singular flag, capture stderr

# no TotalCount field = API-level failure: print raw and abort, no defaults
echo "$resp" | jq -e '.TotalCount' >/dev/null 2>&1 \
|| { echo "API call failed: $resp"; exit 1; }

count=$(echo "$resp" | jq -r '.TotalCount')
[ "$count" -eq 0 ] && aliyun ecs CreateCommand ... # only now is "missing" trustworthy

jq -e '.TotalCount' exits non-zero when the field is absent β€” it replaces // 0 by escalating "field not found" into an explicit failure. The raw response $resp prints alongside the error, so a human can tell a parameter mistake from a server-side error at a glance.

One boundary worth adding: a CommandId returned by CreateCommand doesn't guarantee the object is usable β€” invoke may still report InvalidCmdId.NotFound while DescribeCommands already counts TotalCount=1. So after recreating, verify existence before invoking; on NotFound, recreate β€” with the raw-response reading above, never with another fallback.

Reading results: nesting and the two IDs​

The read-back side has its own silent failures. DescribeInvocationResults nests objects inside objects; the correct path is:

jq -r '.Invocation.InvocationResults.InvocationResult[0].Output' \
<<< "$resp" | base64 -d

Writing it with array intuition as .InvocationResults[0] throws Cannot index object with number β€” the failure is in the accessor, and the data is already in the response. The other confusion source is the ID system: InvokeCommand returns an InvokeId (t- prefix), while DescribeInvocationResults only accepts a CommandId (c- prefix); if only the InvokeId is at hand, exchange it via DescribeInvocations --InvokeId first. When polling, terminal states are exactly Success and Failed, and results deserve a ~10-second wait after dispatch.

Cloud Assistant pitfalls travel in sets: dispatched content can get corrupted (heredoc assembly) and background jobs get killed (nohup) β€” see Aliyun RunCommand Corrupts Files? Ship base64, Not heredoc and Aliyun Assistant Kills nohup Jobs? Escape with setsid.

Notes

  • Always capture aliyun CLI calls with 2>&1 and judge the response text; the exit code is untrustworthy (errors also exit 0).
  • Never use jq // default as a failure probe β€” a missing field should fail loudly, not default to zero.
  • DescribeCommands takes singular --CommandId; the array-style .1 suffix belongs to InvokeCommand.
  • DescribeInvocationResults only accepts a CommandId; the path is .Invocation.InvocationResults.InvocationResult[0].

FAQ​

What should I watch out for when parsing aliyun CLI output with jq?​

The biggest trap is fallback defaults: jq -r '.TotalCount // 0' prints 0 on an error response instead of failing β€” error JSON goes to stderr with exit code 0, and when TotalCount is missing, the default washes the failure into a legitimate-looking empty result. Capture the raw response with 2>&1 and read it before applying jq, and never use a // default as a failure probe.

Why does the aliyun CLI return success even when the API call failed?​

The CLI prints API-level error JSON to stderr while the process exit code stays 0 β€” set -e and || exit never see it. Failure detection must be based on response content (error code / message fields), never on the exit code.

Why can't DescribeInvocationResults read my results?​

Two common causes. Wrong nesting: the result is an object inside an object, and the correct path is .Invocation.InvocationResults.InvocationResult[0] β€” the array-style .InvocationResults[0] throws Cannot index object with number even though the data is right there. Mixed IDs: DescribeInvocationResults only accepts a CommandId (c- prefix); if all you have is an InvokeId (t- prefix), exchange it first via DescribeInvocations --InvokeId.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

coscli has no upload? v1 uses cp, sync, rm; LHCOS quirks

Β· 6 min read

While wiring up off-site uploads for a PostgreSQL backup, the first line of the script was the intuitive coscli upload backup.sql.gz cos://… β€” which failed immediately: no such subcommand.

Ran into this in a PostgreSQL off-site backup pipeline (shell scripts + Tencent Cloud coscli, v1.0.9).

TL;DR​

v1 has no upload/delete verbs: use cp for uploads/downloads, sync for folder sync, rm for deletes, always adding -r for recursion; pass the region via -e if you skip the config file. LHCOS buckets (the object storage bundled with Lighthouse instances) add a quirk: they never appear in the account's global COS bucket list β€” GET Service returns 0 buckets, and a HEAD against the exact bucket name is the existence test. Bucket creation and deletion are console-only; file APIs work normally.

Symptoms: no such command, wrong arg count, empty bucket list​

Three symptoms that look unrelated β€” a missing command (if you searched "coscli command not found" or "COS CLI upload fails"), -r reporting accepts 2 args, and GET Service returning an empty list β€” are two rule sets stacked: v1's verb table, and LHCOS bucket visibility.

First trap: the intuitive verb doesn't exist. upload and delete both fail as unknown subcommands β€” they simply aren't in v1's help.

Second trap: the recursion flag treated as a command. With -r misplaced or arguments missing, the tool reports accepts 2 args β€” -r is not a standalone command, just cp/sync's recursion flag, and the positional arguments follow cp's signature.

Third trap, the most misleading: running the list-buckets call (GET Service) to confirm the bucket exists returns 0 buckets. Meanwhile the backup job has been writing and reading that bucket all along β€” the bucket is fine, just absent from that list.

Root cause: coscli v1's verb table, plus LHCOS staying out of the global list​

v1's semantics are object operations, not resource management. The v1 verb set is three words: cp (upload/download), sync (folder sync), rm (delete). The upload/delete verbs in many tutorials belong to other tools or newer CLI versions; recursion is the -r flag rather than a command, so "command + -r + source + target" with one positional argument missing reports accepts 2 args. Tencent also ships an older Python tool, coscmd, with yet another verb table β€” check which tool a tutorial is about before copying.

LHCOS buckets are a separate namespace, not merged into the account's COS list. GET Service only returns buckets from the COS product line; LHCOS buckets never appear in it, so an empty list does not mean the bucket is missing. The existence test is a HEAD against the exact bucket name. File-level APIs (upload/download/delete) address the bucket directly and work normally; only bucket creation and deletion are console-only operations.

Fix: a fixed invocation shape for scripts, HEAD for existence​

  1. The non-interactive shape. --init-skip=true skips the first-run setup wizard, -i/-k pass the keys, -e names the region endpoint β€” together they make the command usable from cron and scripts:
# upload a single file; add -r for directories
coscli --init-skip=true cp backup.sql.gz cos://examplebucket-1250000000/backup/ \
-e cos.ap-guangzhou.myqcloud.com -i "$SECRET_ID" -k "$SECRET_KEY"

# folder sync
coscli --init-skip=true sync ./dump/ cos://examplebucket-1250000000/backup/ \
-e cos.ap-guangzhou.myqcloud.com -i "$SECRET_ID" -k "$SECRET_KEY"

# delete (add -r for recursion)
coscli --init-skip=true rm -r cos://examplebucket-1250000000/backup/old/ \
-e cos.ap-guangzhou.myqcloud.com -i "$SECRET_ID" -k "$SECRET_KEY"

Bucket names carry the APPID suffix (1250000000 in the example); the Guangzhou region endpoint looks like cos.ap-guangzhou.myqcloud.com.

  1. Existence checks bypass the bucket list. When debugging "does this bucket exist", HEAD the exact bucket name or check the console β€” an empty GET Service result proves nothing.

  2. One-off operations go to the console. Bucket creation, deletion, and permission changes are console actions; scripts don't touch them.

Intentv1 invocation
Upload one filecp <local> cos://bucket/path/
Upload a directorycp -r <dir> cos://bucket/path/
Sync a foldersync <dir> cos://bucket/path/
Deleterm [-r] cos://bucket/path/

Watch out

  • Inline -i/-k values linger in shell history and process lists. For cron jobs, source credentials from a 0600-permission file instead; scope the sub-account to read-write on the target bucket only.
  • LHCOS and COS are separate product lines with separate billing and capacity β€” don't audit LHCOS through the COS bucket list.
  • Check the verb table first on errors: coscli v1, v2, and coscmd share no verb table β€” run --version to see which one you installed before matching tutorials.

FAQ​

coscmd supports upload β€” why doesn't coscli?​

They are two different tools: coscmd is the older Python CLI, while coscli v1 (e.g. 1.0.9) uses object verbs β€” cp for uploads (add -r for directories), sync for folder sync, rm for deletes. Same transfer, different verb table; check which CLI a tutorial targets before copying its commands.

How do I check whether an LHCOS bucket exists?​

Don't trust the bucket list: GET Service returns 0 buckets for the LHCOS namespace. Send a HEAD request for the exact bucket name (or check the console) β€” that's the existence test. File APIs work normally; only bucket creation and deletion are console-only.

How do I run coscli non-interactively in scripts?​

Combine --init-skip=true (skips the setup wizard), -i/-k for the keys, and -e cos.<region>.myqcloud.com for the endpoint. In cron jobs, source credentials from a 0600-permission file instead of inline values, and scope the sub-account to read-write on the target bucket only.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me