Wei Guang's Blog

Setting Environment Variables on Amazon Linux

Maintaining the security of your sensitive data, like the AWS S3 secret key and secret ID, is a critical part of good practice. Rather than including these details in your code and pushing them to git, it's a safer choice to set these variables on your server and then retrieve them from the system environment.

Now, let's see how to set these environment variables on the server. We'll use Amazon Linux as an example. First, you need to edit the ~/.bash_profile file:

$ sudo vim ~/.bash_profile

Upon opening the file, you'll see content similar to the following:

# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
	. ~/.bashrc
fi

# User specific environment and startup programs

You should add your variables at the end of this file, as shown below:

# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
	. ~/.bashrc
fi

export AWS_ACCESS_KEY_ID="Your AWS ACCESS KEY ID"
export AWS_SECRET_ACCESS_KEY="Your AWS SECRET ACCESS KEY"

After saving the changes, execute the updated .bash_profile by running the following command:

$ source ~/.bash_profile

Now, you can access the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from your environment variables. Here's an example of how you would do it in Node.JS:

const ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID
const SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY