Sub topic 2
Giving the Job Credentials Without Leaking Them
Assume you can use a shell, environment variables, exit codes, and basic Git. You also understand how your agent reads prompts and writes results.
Supply Credentials Safely
An unattended job cannot ask for approval, so its credentials must be available before it starts. Use a secret manager, CI secret, or a protected environment file. Do not put secrets in the prompt, command-line arguments, repository files, or logs.
Grant only the access the job needs. A read-only token is safer than a token that can merge code or change production systems.
For a system service, protect the environment file:
sudo install -m 600 /dev/null /etc/nightly-agent.env
sudo sh -c 'printf "%s\n" "AGENT_TOKEN=replace-this-value" > /etc/nightly-agent.env'The service user must be able to read this file, but other users should not. Check your agent’s behavior so it does not print environment variables or include credentials in its output.
Timeouts, Locks, and Exit Status
A wrapper should enforce a time limit, prevent overlap, and preserve failure information. In this example, status 124 means timeout stopped the agent.
#!/usr/bin/env bash
set -Eeuo pipefail
: "${AGENT_TOKEN:?AGENT_TOKEN is not set}"
cd /srv/repos/my-project
log_dir="$HOME/agent-logs"
mkdir -p "$log_dir"
run_id="$(date -u +%Y%m%dT%H%M%SZ)"
log="$log_dir/nightly-$run_id.log"
result="$log_dir/nightly-$run_id.json"
exec > >(tee -a "$log") 2>&1
exec 9>"$HOME/.nightly-agent.lock"
if ! flock -n 9; then
echo "previous run is active; skipping"
exit 0
fi
if timeout 20m /usr/local/bin/my-agent-headless \
--prompt prompts/nightly.md \
--output "$result"; then
status=0
else
status=$?
fi
if [ "$status" -eq 124 ]; then
echo "agent timed out"
fi
if [ "$status" -eq 0 ] &&
! jq -e '.status == "ok" and (.changed_files | type == "array")' \
"$result" >/dev/null; then
echo "invalid agent result"
status=1
fi
echo "exit status: $status"
exit "$status"The lock makes a second run exit safely while the first is active. The timestamped log and result file provide a run record for debugging and auditing. Upload them only to storage with appropriate access controls.
Exercise
Exercise
Why should a scheduled job receive a token through a protected environment or secret manager instead of a command-line argument?
Show answer
Command-line arguments can appear in process listings and scheduler logs, while protected secret storage limits access and reduces accidental disclosure.