Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Version History

« Previous Version 6 Next »

If desired, create a python virtual environment, and activate it. For example:

Prerequisites: You must have python, pip, and venv available.

python -m venv myproj-venv
source myproj-venv/bin/activate
pip install --upgrade pip

Install the keyring module:

pip install keyring

Here is a very simple example:

  • setsecret.py

    import keyring
    keyring.set_password(service_name="myservice", username="myusername", password="mysecret")
    print(f"Set secret: Done!")
  • getsecret.py

    import keyring
    secret = keyring.get_password(service_name="myservice", username="myusername")
    print(f"Got secret {secret}")

Try running it:

python setsecret.py 
Set secret!

python getsecret.py 
Got secret mysecret

If you are running on a desktop system, such as your mac, windows, or linux gnome laptop, it should work, and it securely stores your secret using your user keyring, which is locked by your login session. But if you are running on a remote system via ssh, or a headless service account, or cron job, you may get this error message. The solution is to install keyrings.alt as describe below:

keyring.errors.NoKeyringError: No recommended backend was available. Install a recommended 3rd party backend package; or, install the keyrings.alt package if you want to use the non-recommended backends. See https://pypi.org/project/keyring for details.

The solution is to install the alternative keyring module. This module stores an encrypted keystore on disk, but it also stores the decryption key right next to it. This is why it’s “non-recommended,” but it’s still a huge improvement over having secrets in your code, or stored plaintext on disk, because it shelters your secret from accidental publishing in git push, and it obsessively sets private filesystem permissions on the keystore, so a breach is only possible if an attacker gains access to the storage, bypassing the filesystem permissions, or if the user account itself is compromised:

pip install keyrings.alt
  • No labels