Environment variables can be used to configure dynamic requirements within an application. And they can be used to store sensitive information like API keys, machine credentials, and encryption secrets.
In development, it's important to protect this sensitive data from being exposed in code repositories or logs. In production, security is even more critical to prevent unauthorized data leakages and breaches.
In this codelab, let's learn how to use environment variables in Python with our Viam projects so our code runs smoothly from development to deployment.
Prerequisites
Sign up for a free Viam account, and then sign in to the Viam app.
What You'll Learn
How to create a Python virtual environment
How to store and reuse values as environment variables in Python
How to move control code to your machine
How to use environment variables during development and in production
VS Code installed, or another similar code editor of your choice.
What You'll Build
An example project, such as a Viam rover, using Python variables to access our machine in Viam.
Borrow a rover online with Try Viam
Borrow a Viam rover: Let's use Try Viam to borrow a rover online at no cost which is already configured with all the components you need. If you want to use your own wheeled robot, see more details in this tutorial.
Once the rover is configured, click Try Viam Now.
Examine the modular resources that make up the machine in the Viam app listed in the left sidebar of the CONFIGURE and CONTROL tabs.
Prepare a project directory
Set up your project directory: From the command line in your terminal window, make a directory for your project, for example, called viam-rover. And navigate into the directory.
Create and activate a virtual environment: In the project directory viam-rover, create and activate a virtual environment called .venv for Python to run in. bash python3 -m venv .venv source .venv/bin/activate Now, .venv prepends the commands in your terminal window to indicate the Python packages being used are from this particular environment. You can exit this environment by running deactivate.
Install the Python SDK
Install the Viam Python SDK and all required general dependencies.
Install the SDK: From the command line in your terminal window (inside the activated .venv Python environment), install the Viam Python SDK:
pip install viam-sdk
Copy the sample code
Refer to Python sample code: In the Viam app, go to the CONNECT tab, and select Python.
Show secrets: The sample code shows you how to authenticate and connect to a machine, as well as some of the methods you can use on your configured components and services. To show your machine's API key and API key ID in the sample code, toggle Include secret on the CONNECT tab's Code sample page.
Hide secrets: Instead of leaving our sensitive credentials hard coded in this code sample, let's set up our API key and API key ID as environment variables. Toggle Include secrets once again, this time to remove the credentials from the code sample.
Create the code file: From the command line in your terminal window, create a new file called rover.py.
touch rover.py
Paste the code sample: Copy and paste the code sample from the Viam app into this new file rover.py.
Run the sample code
Create .env file: From the command line, create a new file called .env to store our environment variables to use in local development.
touch .env
Input environment variables: Add your own environment variables to the .env file, formatted like the following. Make sure to update the values with your own environment variables from the code sample in the Viam app, placed between the double quotes as shown here.
Install python-dotenv package: From the command line, still within our virtual environment .venv, install the python-dotenv package to read key-value pairs from an .env file and can set them as environment variables.
pip install python-dotenv
Load the variables into your environment: At the top of your rover.py file, add the following code to load variables into your environment.
from dotenv import load_dotenv
import os
load_dotenv() # Loads the environment variables from the .env file
ROBOT_API_KEY = os.getenv('ROBOT_API_KEY')
ROBOT_API_KEY_ID = os.getenv('ROBOT_API_KEY_ID')
Use variables in your code: You can now use these variables within your code. On rows 7 and 8 in rover.py, you load values from outside of your code (your environment) into python variables. And then on rows 20 and 21, you use those variables to access your machine.
Run the code: Run the sample code to connect to your machine, and inspect the output.
python rover.py
In the next few sections, learn how to use variables on your machine in production.
Once you have the code working in your local development environment, you may choose to move your control code to your machine, so that it can run in production.
Add the control code to your machine
SSH into your board: From the terminal window, run the following command to SSH (Secure Shell) into your board, where the text in <> should be replaced (including the < and > symbols themselves) with the user and hostname you configured when you set up your machine.
ssh <USERNAME>@<REMOTE-HOSTNAME>.local
Create a project directory: Create a new directory on your machine to hold your project code.
mkdir robot
Create and activate a virtual environment: In the new project directory robot, create and activate a virtual environment called .venv for Python to run in.
python3 -m venv .venv
source .venv/bin/activate
Once again, .venv prepends the commands in your terminal window to indicate the Python packages being used are from this particular environment. You can exit this environment by running deactivate.
Install dependencies: Install the Viam Python SDK (and other dependencies if required) into the folder. bash pip install viam-sdk
Copy file(s) to the machine: From the original computer you were developing on (not the secure shell prompt accessing your machine), copy the rover.py file to your machine.
Add a process: Configure a process by going to the CONFIGURE tab of the Viam app. Click the plus icon (+) next to your machine in the left-hand menu and select Process. Name your process process-rover.
Find executable path: To find out the path of the Python 3 executable that is being used on your machine, you can input which python3 in the command line from within your secure shell. You will need this output for the upcoming steps.
Find file location: To find the complete path of your rover.py file on your machine, navigate into the new robot/ directory, and input pwd in the command line from within your secure shell. You will need this output for the next step.
Configure the process: Fill in the required fields to configure your process and Save in the upper right corner of the screen to save your config. The following example configuration executes the command python3 rover.py in your home/myName/robot/ directory every time your machine boots, and keeps it executing indefinitely.
In our example, we added our code as a process, but you can also add control code to your machine as a module.
Now that you've moved your control code to your machine, let's set up our environment variables to use in production.
Update the configuration JSON
Locate the modular resource: In the Viam app under the CONFIGURE tab, select the modular resource in the side bar to locate the card where we will add environment variables. At the top right of the card, select the curly braces icon to see advanced configuration details.
Add a new JSON property called env and your environment variables, formatted like the following.
Save the changes at the top of the page, and restart the machine in the status dropdown at the top.
But there are other ways to use environment variables:
Add virtual environment: If you're working with modules, you can add a Python virtual environment to a persistent folder location set to the environment variable VIAM_MODULE_DATA, where a module can store data across reboots and versions, after the module is first installed.
Update root profile: If you have administrative (root) privileges, you can add environment variables to your machine's root profile (not the user profile). You'll need to modify the global configuration files that affect all users on the system.
Linux and MacOS users can update a root profile like at /etc/profile, /etc/bash.bashrc, or /etc/zsh/zshrc
Windows users can update System Properties → Environment Variables to set system-wide variables.
Knowing how to manage environment variables allows you to work more efficiently and keep your code DRY (Don't Repeat Yourself) for more maintainable, readable, and error free code. It's also important for security reasons not to leak sensitive data and risk access to secure systems.
What You Learned
How to use environment variables in local development
How to use environment variables on machine in production