r/PythonLearning • • Jun 30 '25

Cannot read env variable in linux

Post image

Running on AWS linux, fedora.

Python version 3.13.5.

Realized that our application was failing as it was not able to fetch the environment variables in Linux.

So I ran a sample python program, and set up a SAMPLENV variable in local environment.

While running the program, it gives me a keyerror, which means it's not able to read the env variable.

(It works on windows, and mac)

0 Upvotes

8 comments sorted by

1

u/[deleted] Jun 30 '25 edited Jun 30 '25

you need to use the getenv() function, if your goal is to print the variable.

EDIT: apparently both work fine. You need to define the variable with export.

You can also try to kill the current Bash instance and open a new one, then:

export SAMPLENV="myValue"

python3 script.py

1

u/amilone-7657 Jun 30 '25

I used it, and it returned None.

1

u/[deleted] Jun 30 '25

i updated my comment, you need to define the var with export

2

u/SirCokaBear Jul 01 '25

in the same terminal type "echo $SAMPLEENV" and if you don't see your variable's value then it's not set.

Given that you're using an AWS instance you should set your env vars in parameter store instead. Your instances IAM role should have the role:

{
  "Effect": "Allow",
  "Action": [
    "ssm:GetParameter",
    "ssm:GetParameters"
  ],
  "Resource": "arn:aws:ssm:YOUR_REGION:YOUR_ACCOUNT_ID:parameter/YOUR_PARAMETER_NAME"
}

and with boto3 I'd recommend making a variable with a settings.py file or something similar like:

import boto3

# Create an SSM client
ssm_client = boto3.client('ssm', region_name='your-region')

# Get the parameter
response = ssm_client.get_parameter(
    Name='/my/app/config',
    WithDecryption=True  # Set True if it is a SecureString
)

# Extract the value
param_value = response['Parameter']['Value']

print(f"Parameter value: {param_value}") # just test printing

and importing within your app importing values like

from settings import param_value

If you are dead set on not using that I guess use .env files and load them in with dotenv or regular yaml based config files but I highly advise against keeping secret values there

3

u/reyarama Jun 30 '25

I find it so strange that people still make reddit posts like this, surely pasting this into chatgpt gives you the answer in 5 seconds

2

u/[deleted] Jun 30 '25

I think a lot of these are actually written by ML engineers trying to train their LLM.

1

u/cancerbero23 Jul 01 '25

How are you running the script? Is the variable defined?