0

I am launching an EC2 instance and when the instance is launched for the first time, I am trying to run a few commands and set a few environment variables using UserData. The commands that I have added to the UserData:

#!/bin/bash
 
sudo apt-get -y update
sudo apt-get install gcc g++ build-essential
sudo apt install -y zip awscli python3-pip python3.7 python3.7-dev
python3.7 -m pip install --upgrade pip
pip3 install virtualenv
mkdir anomaly-detection

export DB_ADAPTER=postgresql+psycopg2
export DB_USER=dummy_user
export DB_PASSWORD=dummy_pwd
export DB_HOST=ec2-xx-xxx-xxx-xxx.eu-central-1.compute.amazonaws.com
export DB_NAME=dummy_db

After the instance is launched, I launch the instance and when I check for the environment variables, they aren't set, also the mkdir command wasn't run. (So I am assuming that all the commands haven't been executed).

What is the mistake I am doing?

6
  • It actually launches as a sub shell, so these env vars aren't accessible. I think you could try running the script with . ./script/location/script.sh. Notice the leading dot. Commented Aug 11, 2020 at 13:48
  • Hey @MarkoE, what would the location of the script be which has been written using userdata? Also, should I add the . ./script/location/script.sh command in the userdata? Commented Aug 11, 2020 at 13:50
  • If you're using Terraform, you can choose where to copy it. If you're doing it from the AWS console - don't. :) Commented Aug 11, 2020 at 13:52
  • Sorry, but I am unable to understand how can it be done. I am new to shell scripting, so it is confusing me. Once I enter the userdata, shouldn't the commands be automatically run when the instance is launched? Also, I am not using Terraform Commented Aug 11, 2020 at 14:01
  • Is your instance up & running? If so, you could go through the log file /var/log/cloud-init-output.log and see which errors are there, if any. Which Linux distribution are you using? Commented Aug 11, 2020 at 14:30

1 Answer 1

1

The User Data script is run as the root user.

If you wish to define environment variables for users that will exist when the login, you should define them in each user's .profile file. If you always login as ec2-user, then adding it to /home/ec2-user/.profile would be sufficient.

See: How to permanently set environmental variables - Unix & Linux Stack Exchange

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.