2

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);
}
noderman
  • 1,934
  • 1
  • 20
  • 36

2 Answers2

2

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?

Rodrigo Murillo
  • 13,080
  • 2
  • 29
  • 50
  • Tested and worked with modifications; accepting your answer but editing to fix the syntax and correct the newlines according to heredoc. Thanks a lot for the tip on EC2 userdata; this will also help me. – noderman Feb 02 '18 at 03:14
  • Thanks for the edit. To prevent overwriting of existing settings, the heredoc should append to the file using >> append operator. I have made that edit. – Rodrigo Murillo Feb 02 '18 at 04:21
0

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.

Ashish Pandey
  • 483
  • 5
  • 18
  • 1
    Sorry but this seems to be an incomplete answer and has a problem similar to my reasoning for posting the question. "Write a startup script" - how, where to put it, how to make it executable, will it work for all profiles (like a `PATH` variable in Windows, for example). Remember we are talking about setting up the Linux environment before any of my actual app files are run, so they can freely use the variables. I will consider an answer that is more than bits and pieces and that can actually be used as a guide. Thanks! – noderman Feb 01 '18 at 04:15