I have experimented with many approaches to setting permanent environment variables EC2 instances running Amazon Linux 2, but none of the approaches are persistent across users and across login sessions.

What specific syntax and process will successfully set environment variables so that the values of the variables will be available to all users and during every session?

So far, methods that I have tried include setting values separately in each of the following three files during the USERDATA's launch script for the instance:


I tried each file one at a time and not all three at the same time.

I also tried using Python's os.environ but that did not work either.

User Suggesions

Per @NasirRiley's suggestion, it now works when I create a setVars.sh file and place it in /etc/profile.d during the instance's USERDATA startup sequence:

export SOME_VAR_NAME=some-var-value  
  • Have you tried putting them in a shell file in /etc/profile.d. Jun 14, 2019 at 23:12
  • @NasirRiley Not yet. I can try that right now. I was hoping for some guidance instead of trying an uneducated shotgun approach.
    – CodeMed
    Jun 14, 2019 at 23:14
  • It is important to make sure that you start a new shell session after creating the scripts in /etc/profile.d. Jun 14, 2019 at 23:18
  • @NasirRiley That did not work. Please see the results I posted at the end of the OP. What else can I try?
    – CodeMed
    Jun 14, 2019 at 23:53
  • That's because the line to set the variable is written wrongly. It should be export SOME_VAR_NAME=some-var-value. What you have there is just going to print "export SOME_VAR_NAME=some-var-value" in the terminal when the user opens it. Replace the echo line with export SOME_VAR_NAME=some-var-value. Jun 14, 2019 at 23:58

2 Answers 2


It's better to set universal variables by creating scripts in /etc/profile.d.

You want to create it with an extension of your shell name. For example, if it's bash, it will be called script.sh for example.


The syntax inside will be:

export SOME_VAR_NAME=some-var-value

You will need to start a new shell session to add the variable to your environment which you can do by logging out and back in. It will added for the other users' environments when they do the same or the next time they log in if they aren't currently logged in.

Just a note: you don't actually need the shebang line as it's sourced in according to your shell. I put it in myself sometimes as it's just a force of habit but it doesn't hurt or affect anything. You can leave it out if you'd like.


just append it to the ~/.bash_profile file
and then activate (run) your changes:

echo "export YOUR_ENV_VAR_NAME=your_env_var_value" >> ~/.bash_profile && \
source ~/.bash_profile

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .