JordanBelf
JordanBelf

Reputation: 3338

How can I make R read my environmental variables?

I am running R on EC2 spot instances and I need R to terminate the instance and cancel the spot request once the script has run.

For that I have set the "Request ID" into an environmental variable in /.bashrc and my plan was to simply call the following code into R once the script is ready

system("ec2-cancel-spot-instance-requests $SIR")

The issue I am having is that R is not "seeing" the same environmental variables I seen when I type env from outside R thus the command is not working.

I have checked and if I set my environmental variables at /etc/environment R is able to see those variables, but here is the other problem. As those variables are dynamic (the instance ID and the request ID is different each time a spot instance is created), I am running a script to create them in the form of:

export SIR=`cat /etc/ec2_instance_spot_id.txt`

Where that file contains the dynamic ID

So, how can I insert "dynamic" environmental variables into /etc/environment ? Or, how can I make R read the environmental variables at /.bashrc?

Upvotes: 45

Views: 58885

Answers (4)

Paul
Paul

Reputation: 4168

A more complete approach:

Make a file like myenvs/.Renviron with contents:

USERNAME="my_username"
PASSWORD="StrongPassword"

Then, load and use in R like:

readRenviron("myenvs/.Renviron")
username <- Sys.getenv("USERNAME")
password <- Sys.getenv("PASSWORD")

Upvotes: 1

cheevahagadog
cheevahagadog

Reputation: 5138

My approach was this: I had project-level environment variables stored in a .env file. To make it accessible in R, I used

> readRenviron(".env")

Then to access a specific variable

> Sys.getenv("RDS_UID")

And it worked perfectly.

Upvotes: 22

Thorsten
Thorsten

Reputation: 341

Using Sys.getenv() you see all variables listed in the current environment.

However, they are different from those used in your current shell, for example specified in .profile.

To set the variables for R create a .Renviron file in your home directory and write there

MYDIRECTORY="/home/wherever"

After restarting R you will be able to access this variable with

Sys.getenv("MYDIRECTORY")

Upvotes: 18

Dirk is no longer here
Dirk is no longer here

Reputation: 368201

You want Sys.getenv() as in Sys.getenv("PATH"), say.

Or for your example, try

SIR <- Sys.getenv("SIR")   
system(paste("ec2-cancel-spot-instance-requests",  SIR))

As for setting variables at startup, see help(Startup) to learn about ~/.Renvironment etc

Upvotes: 47

Related Questions