A while back, I wrote about setting up a Django website on an Windows web server via IIS (see this article). One of the most laborious steps in this process is to set up your environmental variables for the site in IIS.
There is a way to automate these steps using the Windows Power Shell. You can configure an environmental variable for a website with a single command from the Power Shell command line. Add several of these commands to a
.ps1 script file and you can get your settings in place by simply running the script.
Here is the basic command to set up one environmental variable. This example is setting up the
.\\inetsrv\appcmd set config -section:system.webServer/fastCgi /+"[fullPath='C:\path\to\venv\Scripts\python.exe',arguments='C:\path\to\<project>\wfastcgi.py'].environmentVariables.[name='DJANGO_SECRET_KEY',value='secret-key-here']" /commit:apphost
Setting up the Script
Now add that line of code to text file and save with a
.ps1extension. (I use
set_env_var.ps1as my file.) Modify the paths as needed to match your configuration. This command equals one (1) environmental variable.
Add a line for EACH environmental variable that you need to configure and save the file again.
At this point, you should add the
set_env_var.ps1file (or whatever you named yours) to your
.gitignorefile so that it does not push to your repository and expose your settings. (Number 1 rule of Git is do not expose your keys and other security settings in your repo.)
Running the Script
Once you have all of your environmental variables in the script file, do the following to execute it:
From the Start menu, right-click on Power Shell and click
Run as administrator.
Type the following command to allow scripts to run.
yeswhen asked if you want to change the execution policy.
Type the following using the path to the
.ps1script file that you just saved. You will see each of the commands run on the screen.
To review what was set up, open IIS and do the following:
a. Select the root server and open the FastCGI Settings.
b. Double-click the python path for the website.
c. Open the Environment Variables collection property box by clicking the
d. Review the list. If you received any error messages when the script was run, you may have to enter them manually as described in the previously mentioned article.
Hopefully, this will save you some time and effort. And, while creating the actual script file does take some time, it is still much faster than the click, click, click required when setting them up manually.