[GCP]中国からのアクセスを遮断する
中国からのアクセスが気になったのですべて遮断しておくことにした。
中国とオーストラリアからのアクセスは1G未満でも課金対象らしいしね。
というわけで、PythonでGCPのファイアウォールに設定を追加するプログラムを書きました。といっても公式のサンプルを少し書き換えただけ。
準備としてここのプレインテキストをダウンロードして、プログラムファイルと同じフォルダに入れておく。
コード
""" BEFORE RUNNING: --------------- 1. If not already done, enable the Compute Engine API and check the quota for your project at https://console.developers.google.com/apis/api/compute 2. This sample uses Application Default Credentials for authentication. If not already done, install the gcloud CLI from https://cloud.google.com/sdk and run `gcloud beta auth application-default login`. For more information, see https://developers.google.com/identity/protocols/application-default-credentials 3. Install the Python client library for Google APIs by running `pip install --upgrade google-api-python-client` """ from pprint import pprint from googleapiclient import discovery from oauth2client.client import GoogleCredentials import time, itertools credentials = GoogleCredentials.get_application_default() service = discovery.build('compute', 'v1', credentials=credentials) # Project ID for this request. project = 'Project ID' # TODO: Update placeholder value. with open('cn.txt', 'r', encoding='utf-8') as f: cn_ip = f.read().split('\n')[6:-1] for num, ip in enumerate(itertools.zip_longest(*[iter(cn_ip)]*255)): ip = [i for i in ip if i] firewall_body = { "name": f'block-china-{str(num+1).zfill(2)}', "priority": 10, "sourceRanges": ip, "denied": [ { "IPProtocol": "all" } ] } request = service.firewalls().insert(project=project, body=firewall_body) response = request.execute() # TODO: Change code below to process the `response` dict: pprint(response) time.sleep(1)