LoginSignup
4
6

More than 3 years have passed since last update.

Serverless VPC AccessでGAE(Standard)からCloud Memorystore使ってみた

Last updated at Posted at 2019-11-25

いまきたさんぎょう

GAE(Standard)で
Cloud Memorystoreに
アクセス出来るよ

注意

Serverless VPC Accessはbetaです。
いつの間にか変わっていても私のせいじゃないです。

Serverless VPC Accessとは

GAE(かCloud Functions)から、VPC内のリソースに、プライベートIPアドレスでアクセス出来るようになります
詳しくは公式ドキュメントを読んでください。

で、具体的に何できんの?

  • CloudSQL
  • Cloud Memorystore
  • GCEサーバー

などのVPC中にあるリソースを、外部に公開することなく、GAE(やCloud Functions)からアクセスすることが出来るようになります。

また、GAEの2nd Generation(Python3.7)では、1st Generation(Python2.7)で使えたMemcacheが使えなくなっていますが、その代替としても
言及されています

Cloud Memorystoreで使ってみる

GAE(Python3.7+Standard)から、Serverless VPC AccessでCloud Memorystoreを使ってみました。

VPCの準備

gcloudなりConsoleなりでVPCを作ってください。
後述の理由で、Serverless VPC Access試すだけならSubnetは作らない方が楽です。

Serverless VPC Accessの準備

Serverless VPC Accessで「IP 範囲は、VPC ネットワーク内の既存の IP アドレス予約と重複してはいけません」らしいので、IPアドレスの範囲はいい感じに設定してください。

ちなみに、IPアドレスの範囲が被っていると、GCE Subnetに下のようなエラーが出ます。

"Invalid value for field 'resource.ipCidrRange': '10.147.0.0/28'. Extended subnetworks in auto subnet mode networks cannot overlap with 10.128.0.0/9."

Cloud Memorystoreの準備

作ったVPC内にCloud Memorystoreを作ります

Connection propertiesに
* IPアドレス
* ポート
が表示されるので、メモっておきます。

GAEの準備

GAE Standardでも、GAE Flexibleからのアクセスと同様に、利用出来ます。

# -*- coding: utf-8 -*-

from flask import Flask, request
import os
import redis

app = Flask(__name__)


redis_host = os.environ.get('REDISHOST', 'localhost')
redis_port = int(os.environ.get('REDISPORT', 6379))
redis_client = redis.StrictRedis(host=redis_host, port=redis_port)

@app.route('/hoge', methods=['GET'])
def hoge_request():
    value = redis_client.incr('counter', 1)
    return str(value), 200

app.yaml

runtime: python37
service: default
entrypoint: gunicorn handlers:app --workers=1

env_variables:
  REDISHOST: CloudMemorystoreのIPアドレス
  REDISPORT: CloudMemorystoreのポート

vpc_access_connector:
  name: "projects/projectのID/locations/asia-northeast1/connectors/コネクタの名前"

handlers:
- url: /hoge
  script: auto

requirements.txt

flask
gunicorn
redis

デプロイ
公式ドキュメントにもあるようにbetaを付ける必要があります(※)。

gcloud beta app deploy app.yaml

※betaつけないと、デプロイには成功しますが、デプロイ後のMemorystoreへのアクセス時に失敗します

結果

Redisにカウントが保存され、アクセスするたびにインクリメントされます。

> curl "https://エンドポイント.appspot.com/hoge"
8
> curl "https://エンドポイント.appspot.com/hoge"                                                                                                                                        
9

その他

  • GAEとServerless VPC Accessは同じリージョンである必要があります
    • リリースノートには無いですが、いつの間にかasia-northeast1で使えるようになっています
4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6