Last update on .

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 DJANGO_SECRET_KEY variable.

.\\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

  1. Now add that line of code to text file and save with a .ps1 extension. (I use set_env_var.ps1 as my file.) Modify the paths as needed to match your configuration. This command equals one (1) environmental variable.

  2. Add a line for EACH environmental variable that you need to configure and save the file again.

  3. At this point, you should add the set_env_var.ps1 file (or whatever you named yours) to your .gitignore file 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:

  1. From the Start menu, right-click on Power Shell and click Run as administrator.

  2. Type the following command to allow scripts to run.

    Set-ExecutionPolicy RemoteSigned
    
  3. Answer yes when asked if you want to change the execution policy.

  4. Type the following using the path to the .ps1 script file that you just saved. You will see each of the commands run on the screen.

    & "C:\PATH\TO\SCRIPT\set_env_var.ps1"
    
  5. 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 ... button.

    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.

Happy Coding!

Additional Information about Entry

Comments

No comments yet.

Post your comment