noderman
noderman

Reputation: 1944

Centos: Setting global environment variables at startup

I am sure this question has been asked many times in many different formats, but for the life of me I don't see a clear answer, just bits and pieces and conflicting comments.

I want my AWS CentOS 7 EC2 server to boot up with a certain set of variable=values to be used by my application(s) (specifically, a Node.js app).

How can I craft a file that can be executed automatically at startup (and later, at will during CodeDeploy for example) that will make these variables available to any processes and profiles? What is the full procedure?

MY_ENV=production
MY_OTHER_VAR=something with spaces for example

My app.js:

function(){
   console.log('Hey, this is my variable: ', process.env.MY_ENV);
}

Upvotes: 2

Views: 3500

Answers (2)

Rodrigo Murillo
Rodrigo Murillo

Reputation: 13632

The easiest way is to use user data script.

In your user data you would create entries in /etc/environment file:

cat <<EOF >> /etc/environment
MY_ENV=production
MY_OTHERVAR=x
EOF

This will be insure your variables are available to all processes and user shells after the instance initializes, and will persist between reboots.

See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html

Also see below more information on Heredoc:

How can I write a heredoc to a file in Bash script?

Upvotes: 2

Ashish Pandey
Ashish Pandey

Reputation: 495

Write a startup script to start the server. export all variables in a startup script before starting the server. Maybe something like this: //startup.js

export MY_ENV=prodcution
export MY_OTHERVAR=somevalue
nohup node index.js & > server.log

When you use this script to start the server, these variables will be exported before the startup, and will be available in the process environment.

One more way could be using something like ansible for the deployment. With that, you can use any other file to export variables before running the startup script.

Upvotes: 0

Related Questions