Elastic BeanstalkのFlaskチュートリアル

Elastic Beanstalkの理解のためにFlaskでのチュートリアルをやってみたメモ。

仮想環境の設定

ローカルのPythonのバージョンを確認する。

$ python --version
Python 2.7.16
$ python3 --version
Python 3.8.5

プロジェクトディレクトリを作成する。

mkdir eb-flask
cd eb-flask

仮想環境を作成する。

python3 -m venv venv
source venv/bin/activate

Flaskをインストールする。

pip install flask==1.0.2

インストールされているライブラリを表示する。

$ pip freeze
click==7.1.2
Flask==1.0.2
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
Werkzeug==1.0.1

この出力をrequirements.txtに保存する。

pip freeze > requirements.txt

アプリケーションの作成

application.pyファイルを作成する。

from flask import Flask

# print a nice greeting.
def say_hello(username = "World"):
    return '<p>Hello %s!</p>\n' % username

# some bits of text for the page.
header_text = '''
    <html>\n<head> <title>EB Flask Test</title> </head>\n<body>'''
instructions = '''
    <p><em>Hint</em>: This is a RESTful web service! Append a username
    to the URL (for example: <code>/Thelonious</code>) to say hello to
    someone specific.</p>\n'''
home_link = '<p><a href="/">Back</a></p>\n'
footer_text = '</body>\n</html>'

# EB looks for an 'application' callable by default.
application = Flask(__name__)

# add a rule for the index page.
application.add_url_rule('/', 'index', (lambda: header_text +
    say_hello() + instructions + footer_text))

# add a rule when the page is accessed with a name appended to the site
# URL.
application.add_url_rule('/<username>', 'hello', (lambda username:
    header_text + say_hello(username) + home_link + footer_text))

# run the app.
if __name__ == "__main__":
    # Setting debug to True enables debug output. This line should be
    # removed before deploying a production app.
    application.debug = True
    application.run()

ローカルで実行して動作を確認する。

$ python3 application.py
 * Serving Flask app "application" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 152-118-818

ブラウザでアクセスしてみる。

f:id:sotoiwa:20200913040125p:plain

Ctrl+Cで停止する。

EB CLIによるデプロイ

EB CLIをインストールする。

brew update
brew install awsebcli

venvフォルダを無視するように.ebignoreファイルを作成する。

echo venv > .ebignore

eb initリポジトリを初期化する。

EB CLIAWS_PROFILEAWS_DEFAULT_PROFILEは見ないようなので注意。--profileAWS_EB_PROFILE環境変数で指定する。

export AWS_EB_PROFILE=hogehoge
eb init -p python-3.6 flask-tutorial --region ap-northeast-1

このコマンドはリモートにアプリケーションを作成し、.elasticbeanstalk/config.ymlファイルと.gitignoreファイルを作っている。

もう一度eb initを設定して鍵ペアを設定する。

$ eb init
Cannot setup CodeCommit because there is no Source Control setup, continuing with initialization
Do you want to set up SSH for your instances?
(Y/n): Y

Select a keypair.
1) default
2) [ Create new KeyPair ]
(default is 1): 1

config.yamlを確認する。

branch-defaults:
  default:
    environment: null
global:
  application_name: flask-tutorial
  branch: null
  default_ec2_keyname: default
  default_platform: Python 3.6
  default_region: ap-northeast-1
  include_git_submodules: true
  instance_profile: null
  platform_name: null
  platform_version: null
  profile: null
  repository: null
  sc: null
  workspace_type: Application

環境を作成する。

$ eb create flask-env
Creating application version archive "app-200913_034415".
Uploading flask-tutorial/app-200913_034415.zip to S3. This may take a while.
Upload Complete.
Environment details for: flask-env
  Application name: flask-tutorial
  Region: ap-northeast-1
  Deployed Version: app-200913_034415
  Environment ID: e-b7yamqbzyz
  Platform: arn:aws:elasticbeanstalk:ap-northeast-1::platform/Python 3.6 running on 64bit Amazon Linux/2.9.14
  Tier: WebServer-Standard-1.0
  CNAME: UNKNOWN
  Updated: 2020-09-12 18:44:19.683000+00:00
Printing Status:
2020-09-12 18:44:17    INFO    createEnvironment is starting.
2020-09-12 18:44:20    INFO    Using elasticbeanstalk-ap-northeast-1-XXXXXXXXXXXX as Amazon S3 storage bucket for environment data.
2020-09-12 18:44:43    INFO    Created target group named: arn:aws:elasticloadbalancing:ap-northeast-1:XXXXXXXXXXXX:targetgroup/awseb-AWSEB-DLYISY30D943/fa15ef921c4fe09e
2020-09-12 18:44:43    INFO    Created security group named: sg-0b3074f38558b6421
2020-09-12 18:44:59    INFO    Created security group named: awseb-e-b7yamqbzyz-stack-AWSEBSecurityGroup-19PX2C25JMPKO
2020-09-12 18:44:59    INFO    Created Auto Scaling launch configuration named: awseb-e-b7yamqbzyz-stack-AWSEBAutoScalingLaunchConfiguration-OSJXRF7P0DQJ
2020-09-12 18:46:01    INFO    Created Auto Scaling group named: awseb-e-b7yamqbzyz-stack-AWSEBAutoScalingGroup-T5SX9XD2N2VC
2020-09-12 18:46:01    INFO    Waiting for EC2 instances to launch. This may take a few minutes.
2020-09-12 18:46:17    INFO    Created Auto Scaling group policy named: arn:aws:autoscaling:ap-northeast-1:XXXXXXXXXXXX:scalingPolicy:7d1c4f9c-b997-4c17-ba4d-ff5a7dfa159a:autoScalingGroupName/awseb-e-b7yamqbzyz-stack-AWSEBAutoScalingGroup-T5SX9XD2N2VC:policyName/awseb-e-b7yamqbzyz-stack-AWSEBAutoScalingScaleDownPolicy-PSY20TDVRWHT
2020-09-12 18:46:17    INFO    Created Auto Scaling group policy named: arn:aws:autoscaling:ap-northeast-1:XXXXXXXXXXXX:scalingPolicy:ba04196c-4b35-4523-aa32-baab91307553:autoScalingGroupName/awseb-e-b7yamqbzyz-stack-AWSEBAutoScalingGroup-T5SX9XD2N2VC:policyName/awseb-e-b7yamqbzyz-stack-AWSEBAutoScalingScaleUpPolicy-1J31UZFQGTUMR
2020-09-12 18:46:17    INFO    Created CloudWatch alarm named: awseb-e-b7yamqbzyz-stack-AWSEBCloudwatchAlarmLow-1U8DQE7SNCNQ7
2020-09-12 18:46:17    INFO    Created CloudWatch alarm named: awseb-e-b7yamqbzyz-stack-AWSEBCloudwatchAlarmHigh-5DZOHOVPHBP9
2020-09-12 18:46:52    INFO    Created load balancer named: arn:aws:elasticloadbalancing:ap-northeast-1:XXXXXXXXXXXX:loadbalancer/app/awseb-AWSEB-VKC2T6OMQOUJ/c093e23bcd628f56
2020-09-12 18:46:52    INFO    Created Load Balancer listener named: arn:aws:elasticloadbalancing:ap-northeast-1:XXXXXXXXXXXX:listener/app/awseb-AWSEB-VKC2T6OMQOUJ/c093e23bcd628f56/d6adb15d9b920ccb
2020-09-12 18:47:39    INFO    Application available at flask-env.eba-mmea7p4k.ap-northeast-1.elasticbeanstalk.com.
2020-09-12 18:47:40    INFO    Successfully launched environment: flask-env

Alert: An update to the EB CLI is available. Run "pip install --upgrade awsebcli" to get the latest version.

eb openコマンドでサイトを開いて確認する。

eb open

f:id:sotoiwa:20200913040141p:plain

eb terminateコマンドで環境を終了する。

eb terminate flask-env

環境は「終了済み」となる。アプリケーションは消えない。