Skip to content
Latchkey

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)".

cargo
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.

Terminal
sudo chown -R "$(id -u):$(id -g)" target
cargo build

Use a clean target dir for the step

Point CARGO_TARGET_DIR at a writable, step-owned path so prior ownership does not leak in.

.github/workflows/ci.yml
env:
  CARGO_TARGET_DIR: ${{ runner.temp }}/target

How to prevent it

  • Run container build steps as the same UID as later steps, or fix ownership after.
  • Scope CARGO_TARGET_DIR to a writable, per-job path.
  • Avoid caching a target dir written by root.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →