Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access environment variable in Rust

The piece of code is as follows:

// Log in to Discord using a bot token from the environment                  
let discord = Discord::from_bot_token(                                       
    &env::var("DISCORD_TOKEN").unwrap()                                      
).expect("login failed");

I get an error saying it is unable to find the environment variable DISCORD_TOKEN.

My environment does show the variable:

myawesomename$env | grep DISCORD
DISCORD_TOKEN=you'llneverknow

If I print all the keys and values that Rust knows:

for (key, value) in env::vars() {                                            
    println!("{}: {}", key, value);                                      
}

It doesn't show the environment variable.

On a similar note, when I do env | grep CARGO, none of the CARGO variables exist, but they are printed in the Rust code.

There is something I fundamentally doesn't understand about the profile/system env variables Rust is looking at (which, I assumed, are the variables in the environment in which the process is launched).

UPDATE: I don't know what I change, but it works now. I apologize for intruding on everyone's time. Thank you for helping me look into this though.

like image 272
chr0nikler Avatar asked Nov 08 '22 06:11

chr0nikler


1 Answers

Undeleted this question because I got the answer. But it's because I didn't examine all the factors before asking the question.

It worked when I ran cargo run, but didn't work when I ran sudo cargo run. I was running it in sudo because I was trying to read memory of another process. The sudo profile has it's own set of env vars, and it resets the environment before going sudo.

To fix this, I ran sudo visudo and inserted this line

Defaults env_keep += "DISCORD_TOKEN'

From there, it worked.

This link got me the answer.

like image 199
chr0nikler Avatar answered Jan 04 '23 01:01

chr0nikler