I am trying to execute a python script on an Amazon Linux 2 instance. In my user-data
section I have a script which copies the python script from an S3 bucket to the instance and executes it like so:
#!/bin/bash
# e - stops the script if there is an error
# x - output every command in /var/log/syslog
set -e -x
# set AWS region
echo "export AWS_DEFAULT_REGION=us-east-1" >> /etc/profile
source /etc/profile
# copy python script from the s3 bucket
aws s3 cp s3://${bucket_name}/ /home/ec2-user --recursive
sudo python3 my_python_script.py
The problem is that the python script doesn't seem to be getting executed at all.
Note: the python script gets copied fine from the bucket
What I am missing here?
UPDATE:
after checking /var/log/cloud-init-output.log
it looks like the problem is in the python script, it cannot find the boto3
module:
+ python3 /home/ec2-user/my_python_script.py
Traceback (most recent call last):
File "/home/ec2-user/my_python_script.py", line 1, in <module>
import boto3
ModuleNotFoundError: No module named 'boto3'
Dec 10 15:52:25 cloud-init[3697]: util.py[WARNING]: Failed running /var/lib/cloud/instance/scripts/part-001 [1]
Dec 10 15:52:25 cloud-init[3697]: cc_scripts_user.py[WARNING]: Failed to run module scripts-user (scripts in /var/lib/cloud/instance/scripts)
Dec 10 15:52:25 cloud-init[3697]: util.py[WARNING]: Running module scripts-user (<module 'cloudinit.config.cc_scripts_user' from '/usr/lib/python2.7/site-packages/cloudinit/config/cc_scripts_user.pyc'>) failed
The problem is that I do have boto3
module installed. I created a custom AMI image that does have all of the modules installed (I used pip3
to install them) before creating the custom AMI image
UPDATE2
I verified that the image does have boto3
package installed in the python3
library:
[ec2-user@ip-ip ~]$ python3
Python 3.7.9 (default, Aug 27 2020, 21:59:41)
[GCC 7.3.1 20180712 (Red Hat 7.3.1-9)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
>>>
UPDATE3
The cause of the problem was that I installed the boto3
package for my user
only (i.e. pip3 install boto3 --user
) and then I created the AMI image. So after adding the bellow line to my user-data
script it worked fine
#!/bin/bash
...
sudo pip3 install boto3
sudo python3 my_python_script.py