I pass access tokens, authentication keys, and other secrets to Python scripts via environment variables rather than encode these values into the scripts themselves. If I was a real boy, I’d use a solution like Hashicorp Vault or other secrets management tool (there’s a bunch of them), but I haven’t yet found the motivation to learn such a tool.
I’m not sure I’d want to build and maintain such a tool if I did find the motivation. I’m sort of lazy sometimes is what I’m saying. So for now, environment variables it is.
PyCharm allows for the passing of environment variables from the IDE to a script, whether that script is running locally or in a remote SSH deployment you’ve configured for your project.
To set the environment variables, select Edit Configurations from the Run menu.
Or in the project bar above the code window, click the dropdown with your script name, and select Edit Configurations.
Either way brings up the following configuration window for the scripts in your project. In the Environment variables: field, click the icon.
That will bring up the following window you can use to configure the environment variables.
Fantastic. But how do we assign the environment variables we’ve configured to a variable in the script itself? We use the os library and call on the environ function, like so.
Let’s say my script called RefreshBlubrryAccessToken.py contains the following.
import os refreshToken = os.environ["BLUBRRY_REFRESH_TOKEN"]
In this example, the variable refreshToken will be set to the value of the BLUBRRY_REFRESH_TOKEN environment variable I set in the User environment variables: configuration window above.
Configured environment variables will be passed both to a locally executed Python interpreter and a remote SSH deployment. When developing a script in PyCharm, this feature is convenient, as PyCharm’s remote deployment feature doesn’t invoke a shell and then run the script. That means a script running via a PyCharm remote SSH deployment isn’t aware of environment variables you might be exporting in ~/.bashrc on your remote host.
Wait. So many flaming hoops. Why even bother with environment variables?
Because you don’t want to hardcode the variable value assignment into the script and then sync the script to a repository you made public. Here, world! Have my secrets! Not good.
By using an environment variable to pass a value into the script, you’ve somewhat obfuscated the secret and avoided the “sync secrets to a public repo” problem. This approach to secrets management isn’t nearly as robust as a true secrets management tool that uses encryption, secret handshakes, and orders signed in triplicate, sent in, sent back, queried, lost, found, subjected to public inquiry, lost again, and finally buried in soft peat for three months and recycled as firelighters.
But for some solutions, using environment variables is good enough.