0

I am running this code while launching ec2 instance, python is installed, but the folder is not created.

#!/bin/bash

sudo yum update -y

sudo yum install python36 -y

mkdir venv

cd venv

virtualenv -p /usr/bin/pyton3.6 python36

echo "source /home/ec2-user/venv/python36/bin/activate" > /home/ec2-user/.bashrc

pip install boto3
1
  • 1
    Scripts in user data are run as root. So you might be looking in the wrong place for the venv directory. Can you add the full path with mkdir e.g. mkdir /home/ec2-user/venv ? Commented Nov 25, 2017 at 9:26

2 Answers 2

3

A couple of things could go wrong with that script. I suggest a more robust way to write it:

#!/bin/bash

cd "$(dirname "$0")"

sudo yum update -y
sudo yum install python36 -y

if [ ! -d venv ]; then
    mkdir venv
    virtualenv -p /usr/bin/pyton3.6 venv/python36

    echo "source venv/python36/bin/activate" >> ~/.bashrc

    source venv/python36/bin/activate
    pip install boto3
fi

Improved points:

  • Make sure we are in the right directory, by doing a cd into the directory of the script
  • Do not hardcode the user home directory location, use ~
  • Do not truncate ~/.bashrc if already exists
  • Before installing boto3, it's important to activate the virtual env, otherwise pip will not install it inside the virtual env (it will try to install system-wide)
Sign up to request clarification or add additional context in comments.

1 Comment

Because this is an EC2 launch script, it's in 'userdata', and that means that the script is actually being run as root, not as the ec2-user who is ultimately the user that will be using the virtualenv.
0

Thank you for inputs. This worked. Mainly:

  • clear paths
  • activate virtual environment for boto3 install

'#!/bin/bash

sudo yum update -y

sudo yum install python36 -y

mkdir /home/ec2-user/venv

cd /home/ec2-user/venv

virtualenv -p /usr/bin/python3.6 python36

echo "source /home/ec2-user/venv/python36/bin/activate" >> /home/ec2-user/.bashrc

source /home/ec2-user/venv/python36/bin/activate

pip install boto3

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.