Search code examples
pythonenvironment-variablespm2

Environment variable not visible in Python application started from pm2


I'm using a server for the first time. It has Ubuntu 18.04.
I've never worked with that OS, but after some guides I managed to get my code working, except for the environment variable.
In ~/.bashrc at the end of file I added export KEY="123asd".
Then I reloaded the terminal.
I checked if my environment variable is loaded via printenv KEY and it shows the correct value.
In my main.py there's:

import os
import telebot

API_KEY = os.getenv("KEY")
bot = telebot.TeleBot(API_KEY)

When I run it with pm2 start main.py --interpreter=python3 there's an error in logs:

raise Exception('Bot token is not defined')
Exception: Bot token is not defined

If I understand correctly it means that API_KEY is None so there's a problem with the environment variable.
I tried giving API_KEY an actual value, not an environment variable, and it worked fine.
So what else do I need to do to use an environment variable properly?


Solution

  • I was looking in the wrong place.
    If I want to use pm2 then I need to create a ecosystem.config.js file and give it my variable. Like this:

    module.exports = {
      apps : [{
              name: "main.py",
        env: {
            KEY: "123asd"
        }
      }]
    }
    

    It works, only I'm not sure if it's correct since there are more than 1 processes of my main.py (1 online, others are erorred)