Created
September 16, 2018 09:11
-
-
Save mjdietzx/728de117f511a32b756d894088d02b1b to your computer and use it in GitHub Desktop.
spin up an ec2 instance and tear it down upon completion from AWS lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ec2_client = boto3.client('ec2') | |
user_data = """#!/bin/bash | |
sudo apt-get update | |
curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py" | |
sudo python3 get-pip.py | |
sudo pip3 install boto3 | |
sudo apt-get install -y libgtk2.0-dev | |
sudo pip3 install opencv-python | |
echo "{}" >> {} | |
python3 {} {} | |
sudo shutdown -H now""" | |
# | |
# launch ec2 instance | |
# | |
script = 'ec2_freeze_frames.py' | |
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), script), 'r') as f: | |
s = f.read() | |
u_d = user_data.format(s, script, script, params...) | |
instance = ec2_client.run_instances( | |
ImageId='ami-66506c1c', | |
InstanceType='t2.large', | |
MinCount=1, # required by boto, even though it's kinda obvious. | |
MaxCount=1, | |
InstanceInitiatedShutdownBehavior='terminate', # make shutdown in script terminate ec2 | |
IamInstanceProfile={'Name': os.environ['EC2_WORKER']}, | |
UserData=u_d # file to run on instance init. | |
) | |
print(instance) | |
assert instance['ResponseMetadata']['HTTPStatusCode'] == 200, instance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment