When GPG (GNU Privacy Guard) runs for the first time under a user account, it automatically creates a ~/.gnupg
directory with default configuration files. While this is convenient for most users, it becomes problematic in:
- Automated scripts running in clean environments
- Containerized applications
- CI/CD pipelines
- Multi-user systems where home directory pollution should be avoided
The most straightforward method is to specify an alternative home directory using the --homedir
flag:
gpg --homedir /tmp/gpg-temp --list-keys
For complete isolation, combine multiple approaches:
# Create temporary GNUPGHOME
export GNUPGHOME=$(mktemp -d)
trap 'rm -rf "$GNUPGHOME"' EXIT
# Alternative: Use a fake home directory
FAKE_HOME=$(mktemp -d)
env HOME="$FAKE_HOME" gpg --list-keys
For system administrators who want to enforce this behavior:
- Edit
/etc/environment
:GNUPGHOME=/var/lib/gnupg
- Or create
/etc/profile.d/gnupg.sh
:export GNUPGHOME=/var/lib/gnupg
Building on the mentioned Ruby gem, here's how to implement temporary GPG homes:
require 'tempfile'
def with_temp_gpg
Dir.mktmpdir do |dir|
ENV['GNUPGHOME'] = dir
yield
ensure
ENV.delete('GNUPGHOME')
end
end
with_temp_gpg do
system('gpg --import key.asc')
# Perform GPG operations
end
If you encounter permission problems with custom homedirs:
- Ensure directory permissions are 700
- Set correct ownership for the running user
- When using systemd services, add
ReadWritePaths=/your/custom/path
When working with GPG in automated environments or restricted systems, the automatic creation of ~/.gnupg
can be problematic. This behavior persists even when you're using temporary keyrings or isolated operations. Here's how to gain full control over GPG's directory behavior.
The most elegant solution is using environment variables to redirect GPG's home directory:
export GNUPGHOME=/path/to/temporary/directory
gpg --list-keys
For one-off operations where you don't want to modify environment variables:
gpg --homedir /tmp/gpg_temp --list-keys
For servers or build environments, you might want to set this permanently in /etc/environment
:
GNUPGHOME=/var/lib/gpg
Here's how to create a completely isolated GPG environment in Ruby (similar to your rgpg approach):
require 'tempfile'
require 'fileutils'
def with_isolated_gpg
Dir.mktmpdir do |dir|
ENV['GNUPGHOME'] = dir
yield
ensure
ENV.delete('GNUPGHOME')
end
end
For cases where you absolutely don't want any directory created, combine with --no-options
:
gpg --no-options --no-auto-check-trustdb --homedir /nonexistent
The gpgconf
utility provides additional control:
gpgconf --kill all
gpgconf --launch all --homedir /custom/path