Build, deployment, proxy, and language-tool commands can fail under sudo when a variable from the user's shell is removed before the privileged process starts. Preserve only the variable that the root command needs, so sudo still filters unrelated values instead of becoming a full environment pass-through.

The sudoers policy normally keeps env_reset enabled, which creates a small command environment and then adds variables allowed by env_keep or related checks. A scoped Defaults:user entry such as Defaults:deployer env_keep += "BUILD_CACHE" keeps one named variable for one invoking account without changing the environment policy for every sudo user.

Environment variables can change program behavior, load configuration, or expose sensitive values, so do not preserve passwords, tokens, untrusted paths, or variables that affect dynamic linking. Use a separate command-lookup fix for PATH problems, and prefer policy whitelisting over broad sudo -E usage unless the sudoers rule is intentionally allowed to use SETENV.

Steps to preserve environment variables with sudo:

  1. Choose the exact variable and invoking account that need preservation.

    The examples use BUILD_CACHE for the deployer account. Keep the account-specific sudo command rule separate; env_keep preserves environment values but does not grant permission to run a command.

  2. Open a sudoers drop-in for the environment rule with visudo.
    $ sudo visudo -f /etc/sudoers.d/20-build-cache

    Do not edit sudoers policy with a normal text editor. visudo locks the file and checks syntax before saving, which reduces the risk of breaking sudo access.

  3. Add a user-scoped env_keep rule for the selected variable.
    /etc/sudoers.d/20-build-cache
    Defaults:deployer env_keep += "BUILD_CACHE"

    Use Defaults:%build when the same environment variable should be preserved for a sudoers group. Use a plain Defaults line only when every sudo user on the host should receive the same policy.

  4. Validate the sudoers drop-in before relying on it.
    $ sudo visudo -cf /etc/sudoers.d/20-build-cache
    /etc/sudoers.d/20-build-cache: parsed OK
  5. Run a proof command with the preserved variable in the invoking user's environment.
    $ BUILD_CACHE=/srv/build-cache sudo printenv BUILD_CACHE
    /srv/build-cache

    Set the variable before sudo, as shown. Writing sudo BUILD_CACHE=/srv/build-cache ... asks sudoers to accept a command-line environment assignment and can require broader SETENV policy.

  6. Confirm an unlisted variable is still filtered.
    $ UNLISTED_FLAG=not-preserved sudo printenv UNLISTED_FLAG

    No output from printenv means sudo did not pass that variable to the root command.