1

My django project fetches credentials from environment variables, now I want to automate this process and store the credentials in the vault(hashivcorp). I have a python and shell script which fetches data from an API and exports it as environment variables, when I run it using os.system command it runs the shell script but as it runs it in a subprocess, I can't access the variables in the main(parent) process/shell. Only way of doing it by inserting the shell script in the settings.py file. Is there any way I can do it so that I get those in the main process? P.s: I did try sourcing, os.system didn't recognise it as a command.

Here's the code I'm running:

import os

os.environ['ENV'] = 'Demo'
os.system('python3 /home/rishabh/export.py')

print(os.environ.get('RDS_DB_NAME'))

output:

None

the python file, shell script works just fine.

3
  • Why do you want to run export.py as a child process, and not inside your main process? But if you really want to do it, you could (inside export.py) create a text file which contains the environment variables you are interested in, together with their values, and then process this file in the main script. Commented May 20, 2020 at 12:07
  • I also suggest that you remove the shell tag from your question, because there is nothing shell specific in it. Commented May 20, 2020 at 12:09
  • I was looking for a way to run it that way only. Commented May 26, 2020 at 12:05

1 Answer 1

1

One way to do it is to run export.py in the same process, as user1934428 suggested:

import os
import sys

os.environ['ENV'] = 'Demo'

sys.path.append('/home/rishabh/')
import export   # runs export.py in the same process

print(os.environ.get('RDS_DB_NAME'))

This assumes there are no __name__ == '__main__' checks inside export.py.

You only need the sys.path line if export.py is in a different directory than your current script.

Sign up to request clarification or add additional context in comments.

1 Comment

It didn't cross my mind that I can even do it this way. Thanks a lot for the help! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.