I am trying to set environment variables with EC2s user data, but nothing i do seems to work
here are the User data scripts i tried
#!/b
This maynot be the exact answer to the OP's question but similar. I've thought of sharing this as I've wasted enough time searching for the answer and finally figured it out.
Example assuming - AWS EC2 running ubuntu
.
If there is a scenario where you need to define the environment variables as well use it in the same bash session (same user-data process), then either you can add the variables to /etc/profile
, /etc/environment
or /home/ubuntu/.zshrc
file. I have not tried /home/ubuntu/.profile
file BTW.
Assuming adding to .zshrc
file,
sudo su ubuntu -c "$(cat << EOF
echo 'export PATH="/tmp:\$PATH"' >> /home/ubuntu/.zshrc
echo 'export ABC="XYZ"' >> /home/ubuntu/.zshrc
echo 'export PY_VERSION=3.8.1' >> /home/ubuntu/.zshrc
source /home/ubuntu/.zshrc
echo printenv > /tmp/envvars # To test
EOF
)"
Once the user data is finished running, you can see the environment variables which you have added in the script are echoed to the envvars
file. Reloading the bash with source /home/ubuntu/.zshrc
made the newly added variables available in the bash session.
(additional info) How to install zsh
and oh-my-zsh
?
sudo apt-get install -y zsh
sudo su ubuntu -c "$(cat << EOF
ssh-keyscan -H github.com >> /home/ubuntu/.ssh/known_hosts
git clone https://github.com/robbyrussell/oh-my-zsh.git /home/ubuntu/.oh-my-zsh
cp /home/ubuntu/.oh-my-zsh/templates/zshrc.zsh-template /home/ubuntu/.zshrc
echo DISABLE_AUTO_UPDATE="true" >> /home/ubuntu/.zshrc
cp /home/ubuntu/.oh-my-zsh/themes/robbyrussell.zsh-theme /home/ubuntu/.oh-my-zsh/custom
EOF
)"
sudo chsh -s /bin/zsh ubuntu
Wondering why I didn't added the environment variable in .bashrc
? The scenario which I mentioned above (using the environment variables in the same user-data session) adding to .bashrc
won't work. .bashrc
is only sourced for interactive Bash shells so there should be no need for .bashrc to check if it is running in an interactive shell. So just like above,
source /home/ubuntu/.bashrc
won't reload the bash. You can check this out written right in the beginning of the .bashrc
file,
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac