AWS Overview and Security
Script is used for setting up and launching a Flask web application on an Amazon EC2 instance running Amazon Linux 2023 AMI
Shebang and execution flags:
#!/bin/bash -ex
This line indicates that the script should be executed using the bash shell. The
-e
flag makes the script exit immediately if any command exits with a non-zero status. The-x
flag makes the script print each command before executing it, which is useful for debugging.Download the Flask application:
wget https://aws-tc-largeobjects.s3-us-west-2.amazonaws.com/DEV-AWS-MO-GCNv2/FlaskApp.zip unzip FlaskApp.zip cd FlaskApp/
These commands download a ZIP file containing the Flask application from a specified URL, unzip the contents, and change the directory to the unzipped FlaskApp folder.
Install necessary software:
yum -y install python3-pip pip install -r requirements.txt yum -y install stress
yum -y install python3-pip
: Installs Python 3 and pip, the Python package installer.pip install -r requirements.txt
: Uses pip to install all the Python packages listed in therequirements.txt
file, which are necessary for the Flask application.yum -y install stress
: Installs thestress
tool, which can be used to test the system by generating load.
Set environment variables:
export PHOTOS_BUCKET=${SUB_PHOTOS_BUCKET} export AWS_DEFAULT_REGION=<INSERT REGION HERE> export DYNAMO_MODE=on
These commands set environment variables needed by the Flask application:
PHOTOS_BUCKET
: Specifies the Amazon S3 bucket where photos are stored.AWS_DEFAULT_REGION
: Specifies the AWS region in which the EC2 instance is running. The placeholder<INSERT REGION HERE>
should be replaced with the actual region.DYNAMO_MODE
: Enables DynamoDB mode.
Run the Flask application:
FLASK_APP=application.py /usr/local/bin/flask run --host=0.0.0.0 --port=80
This command sets the
FLASK_APP
environment variable to the main application file (application.py
) and starts the Flask application, making it accessible on all IP addresses (--host=0.0.0.0
) and on port 80.
To summarize, this script automates the setup of a Flask web application on an EC2 instance, including downloading the application code, installing dependencies, setting environment variables, and running the application.
As of March 15, 2023, the default Amazon Machine Image (AMI) for Amazon EC2 has been updated to the Amazon Linux 2023 AMI.
Amazon Linux 2023 user data script:
code#!/bin/bash -ex
wget https://aws-tc-largeobjects.s3-us-west-2.amazonaws.com/DEV-AWS-MO-GCNv2/FlaskApp.zip
unzip FlaskApp.zip
cd FlaskApp/
yum -y install python3-pip
pip install -r requirements.txt
yum -y install stress
export PHOTOS_BUCKET=${SUB_PHOTOS_BUCKET}
export AWS_DEFAULT_REGION=<INSERT REGION HERE>
export DYNAMO_MODE=on
FLASK_APP=application.py /usr/local/bin/flask run --host=0.0.0.0 --port=80
When using the user data scripts, remember to replace the <INSERT REGION HERE>
with the AWS region you are operating in, and ensure you remove both brackets as well.