cargo "failed to remove ... Permission denied" (target dir) in CI
cargo tried to remove or overwrite a file in the target directory and the OS denied permission. The directory (often a restored cache or a path mounted from a container run as root) is owned by a user the current step cannot write as.
What this error means
cargo build or cargo clean fails with "error: failed to remove file target/.../X" and "Caused by: Permission denied (os error 13)".
error: failed to remove file `/home/runner/work/app/target/debug/build/app-abc/output`
Caused by:
Permission denied (os error 13)Common causes
Target files owned by root from a container step
An earlier step built inside a container as root and wrote into a mounted target directory; the later non-root step cannot modify those files.
A restored cache with wrong ownership or read-only bits
A cache restored from a different context can land with ownership or permissions the current user cannot write.
How to fix it
Fix ownership of the target directory
Reclaim the target tree for the current user before building.
sudo chown -R "$(id -u):$(id -g)" target
cargo buildUse a clean target dir for the step
Point CARGO_TARGET_DIR at a writable, step-owned path so prior ownership does not leak in.
env:
CARGO_TARGET_DIR: ${{ runner.temp }}/targetHow to prevent it
- Run container build steps as the same UID as later steps, or fix ownership after.
- Scope
CARGO_TARGET_DIRto a writable, per-job path. - Avoid caching a target dir written by root.