CloudFrontの理解を深める
IT分野に関わる教育を受けておらず、ド素人から、独学で学習を始めて8か月が経ちました。
最近やっと、自分で試したいことを、調べながら、検証していけるようになり、AWSの面白さ、利便性を感じております。
自分が2度手間にならないように、誰かの役に立つように、記録を残しておきます。
今回、使ってみて、理解できた点が、下記の項目
●CloudFrontで楽々Routingが設定できる。
(リージョンに関わらず、APIの統合が行える)
●API Gatewayと組み合わせることでHTTPSを利用できるようになる。
●BehaviorsのForwarded Query StringsをYesにしないとオリジンへのquerystringが消えてしまう。
●querystringの値の種類に応じてのキャッシュ動作の制御はできない。
●オリジンからの4XX,5xxステータスコードをデフォルトで5分間キャッシュする。
●また、API Gatewayが30秒でタイムアウト
構成図
originAPI
from __future__ import print_function
from flask import Flask, Response, request
import json
import requests
import urllib
from datetime import date
from datetime import datetime
from datetime import timedelta
application = Flask(__name__)
@application.route('/', methods=['POST', 'GET'])
def index():
return 'OK', 200
@application.route('/cache/healthcheck', methods=['GET'])
def healthcheck():
print('url')
print(request.url)
response = {'Message':'','Status':[]}
qs = urllib.parse.urlparse(request.url).query
qs_d = urllib.parse.parse_qs(qs)
if str(qs_d['location']) == "['UTC']":
response['Message'] = datetime.now().strftime('%X')
elif str(qs_d['location']) == "['JPN']":
response['Message'] = (datetime.now()+ timedelta(hours=9)).strftime('%X')
else :
response['Message'] = "other"
print('other')
return json.dumps(response)
if __name__ == "__main__":
application.run(host="0.0.0.0", port=80)
完成度は低いかもしれませんが、同じクエリパラーメータで更新の確認ができるように作成しました。
使い方
$ curl http://localhost:/
{"Status": "OK"}
$ curl http://localhost:80/cache/healthcheck?location=JPN
{"Message": "19:51:37", "Status": "OK"}
$ curl http://localhost:80/cache/healthcheck?location=UTC
{"Message": "10:51:42", "Status": "OK"}
API Gatewayの設定
/
ANY endpoint:http://ec2-54-87-176-237.compute-1.amazonaws.com/
OPTINS
/{proxy+}
ANY endpoint:http://ec2-54-87-176-237.compute-1.amazonaws.com/{proxy}
OPTION
●HTTPプロキシ統合を使用する
●CORS有効化にする
この二点でAPI Gatewayによる不具合はなくなると思います。
CloudFrontの設定
Origins and Origin Groups
Origin Domain Name and Path | Origin ID | Origin Protocol Policy |
---|---|---|
<API Gateway 1 Invoke URL> | Custom+<API Gateway 1 Invoke URL> | Matcch Viewer |
<API Gateway 2 Invoke URL> | Custom+<API Gateway 2 Invoke URL> | Matcch Viewer |
Behaviors
Procedence | Path Patter | Origin or Origin Group | Forwarded Query Strings |
---|---|---|---|
0 | /cache/* | Custom+<API Gateway 1 Invoke URL> | Yes |
1 | Default(*) | Custom+<API Gateway 2 Invoke URL> | Yes |
Forwarded Query StringsをNoにしているとquerystringがオリジンへ届かないので要注意
cacheしたくないときはBehabior>Maximum TTL:0,Default TTL:0に設定する
エラーページをキャッシュしたくない
本来はオリジンの保護の目的でCloudFrontがキャッシュしてくれるが、テスト中は不要なので無効化しておく
Error Pages
HTTP Error Code | ErrorCaching Minimum TTL |
---|---|
404 | 0 |
500 | 0 |
502 | 0 |
これでCloudFrontでエラーページをキャッシュことがなくなります。
だれかの役に立てることを願っています。