Antigravity에서 Google Cloud Developer 플러그인을 사용하여 앱 보호

1. 소개

이 Codelab에서는 Google Cloud에서 gCurrenC 계산기 웹 애플리케이션을 빌드하고 배포한 다음 원치 않는 액세스로부터 보호합니다. Google Antigravity, Google Cloud Developer 플러그인, Developer Knowledge (DK) MCP 서버를 사용하여 애플리케이션에 액세스할 수 있는 사용자를 제어하고 무단 사용으로부터 애플리케이션을 보호하는 보안 아키텍처를 설계하고 구현합니다.

이 실습에서는 Google Antigravity를 DK MCP 서버에 연결하여 Antigravity가 공식 실시간 Google Cloud 문서를 기반으로 작동하도록 합니다. Antigravity는 정적 학습 데이터나 오래된 모델 가중치에 의존하는 대신 현재 아키텍처 패턴, 최신 gcloud CLI 문법, 보안 매개변수를 동적으로 검색하여 할루시네이션을 줄이고 최신 지식을 기반으로 대답을 그라운딩합니다.

빌드할 항목

  • 비공개 컴퓨팅 워크로드: 공개 IP 주소가 없는 커스텀 가상 프라이빗 클라우드 (VPC) 네트워크 내에서 gCurrenC 계산기 웹 앱을 실행하는 Compute Engine 가상 머신 (VM) 2개
  • 보안 인그레스 파이프라인: 전용 프록시 전용 서브넷이 있는 전역 외부 애플리케이션 부하 분산기로, Google 프런트엔드 (GFE)를 통해 인터넷 트래픽을 공개 인터넷에 노출하지 않고 비공개 VM으로 라우팅합니다.
  • 보안 이그레스 파이프라인: 프로젝트 수준의 Cloud Next Generation Firewall (Cloud NGFW) Enterprise 및 Certificate Authority Service (CAS)와 페어링된 Cloud Router 및 Cloud NAT 게이트웨이로, 아웃바운드 HTTPS 환율 API 트래픽에 대해 즉시 TLS 검사 및 침입 방지 서비스 (IPS) 스캔을 수행합니다.

학습할 내용

  • Antigravity CLI를 사용하여 google-cloud-developer 플러그인을 설치하고 Antigravity에서 DK MCP 서버를 구성합니다.
  • IAP (Identity-Aware Proxy) TCP 전달을 사용하여 Compute Engine에서 격리된 비공개 웹 애플리케이션을 배포하고 테스트합니다.
  • Antigravity에서 그라운딩된 멀티턴 프롬프트를 사용하여 프로젝트 수준의 인그레스 및 이그레스 보안 아키텍처를 설계합니다.
  • 전역 외부 애플리케이션 부하 분산, Cloud NAT, CAS, Cloud NGFW Enterprise를 위한 bash 배포 스크립트를 생성, 자체 감사, 실행합니다.

2. 시작하기 전에

기본 요건

이 Codelab을 시작하기 전에 다음 사항을 확인하세요.

  1. Google 계정 및 Chrome 브라우저
  2. 결제가 사용 설정된 새 Google Cloud 프로젝트 이 Codelab 전반에서 API를 사용 설정하고, API 키를 만들고, Google Cloud 리소스를 배포하는 데 사용하므로 프로젝트 ID (PROJECT_ID)를 기록해 둡니다.
  3. API 키, Compute Engine 리소스, VPC 네트워크, CAS 풀, IAP 터널, Cloud NGFW 엔드포인트를 만들 수 있는 Google Cloud 프로젝트의 Identity and Access Management (IAM) 권한
  4. gcloud CLI로 인증하고, 활성 Google Cloud 프로젝트를 설정하고, 필요한 API를 사용 설정합니다.
    1. 터미널 또는 Cloud Shell에서 이미 인증되었는지 확인합니다.
      gcloud auth list
      
      계정을 인증해야 하는 경우 다음 명령어를 실행합니다.
      gcloud auth login
      
    2. gcloud CLI가 프로젝트를 사용하도록 구성되었는지 확인합니다.
      gcloud config list project
      
      프로젝트가 설정되지 않았거나 다른 프로젝트가 활성 상태인 경우 프로젝트 ID를 설정합니다. PROJECT_ID를 Google Cloud 프로젝트 ID로 바꿉니다.
      export PROJECT_ID=PROJECT_ID
      gcloud config set project PROJECT_ID
      
    3. Google Cloud 프로젝트에서 필요한 API를 사용 설정합니다.
      gcloud services enable \
         compute.googleapis.com \
         iap.googleapis.com \
         networksecurity.googleapis.com \
         privateca.googleapis.com \
         developerknowledge.googleapis.com \
         apikeys.googleapis.com
      
  5. Google Antigravity 다운로드 페이지에서 로컬 시스템에 Antigravity 2.0을 설치합니다.

Antigravity CLI를 사용하여 Google Cloud Developer 플러그인 설치

Antigravity CLI를 사용하여 Google Cloud Developer 플러그인을 설치하려면 다음 단계를 따르세요.

  1. 로컬 워크스테이션에 Antigravity CLI를 설치하려면 다음을 수행합니다.
    1. 로컬 터미널을 엽니다.
    2. 설치 프로그램 스크립트를 실행합니다.
      curl -fsSL https://antigravity.google/cli/install.sh | bash
      
    3. 터미널 세션을 닫았다가 다시 열어 시스템 PATH에서 Antigravity CLI 바이너리 agy를 사용할 수 있도록 합니다.
  2. 로컬 터미널에서 다음 명령어를 실행하여 google-cloud-developer 플러그인을 설치합니다.
    agy plugin install https://github.com/google/skills/plugins/cloud/google-cloud-developer
    
    다음과 비슷한 출력이 표시됩니다.
    Cloning plugin from https://github.com/google/skills.git...
      [ok]    google-cloud-developer
              ✔ skills      : 5 processed
              - agents      : skipped (not found)
              - commands    : skipped (not found)
              ✔ mcpServers  : 1 processed
              - hooks       : skipped (not found)
    
    플러그인에 포함된 모든 사용 가능한 기술과 기능에 대해 알아보려면 Google Cloud Developer 플러그인 문서 및 Google Cloud Developer 플러그인 시작하기 Codelab을 참조하세요.

3. Antigravity 및 DK MCP 서버 설정

이 섹션에서는 제한된 Google Cloud API 키를 사용하여 Antigravity에서 DK MCP 서버를 구성합니다.

  1. Antigravity를 열고 /goal를 입력한 후 Enter를 눌러 목표 모드를 활성화한 다음, 다음 프롬프트를 붙여넣어 제한된 API 키를 만들고 DK MCP 서버를 구성합니다. PROJECT_ID를 시작하기 전에 섹션의 Google Cloud 프로젝트 ID로 바꿉니다. 자세한 내용은 google-cloud-developer 플러그인을 참조하세요.
    Set up Antigravity to use the Developer Knowledge MCP server on my local machine. Run the necessary terminal commands to complete the following:
    
    1. Create a restricted API key named 'DKP-MCP-Key' that can only target the Developer Knowledge API. Use the PROJECT_ID to create the API key.
    2. Retrieve the actual key string of the newly created API key.
    3. Create or safely update my ~/.gemini/config/mcp_config.json file (preserve any existing MCP servers) with the correct JSON structure to connect the developer-knowledge server using that API key in the headers.
    You MUST use the following JSON structure for the new server:
    
       "developer-knowledge": {
          "serverUrl": "https://developerknowledge.googleapis.com/mcp",
          "headers": {
          "x-goog-api-key": "<INSERT_RETRIEVED_API_KEY_HERE>"
          }
       }
    
    When you are done, confirm that the setup is complete.
    
  2. DK MCP 서버가 활성 상태인지 확인하려면 Antigravity 채팅 창에 다음 프롬프트를 입력합니다.
    Which MCP servers are available?
    
    Antigravity는 developer-knowledge 및 사용 가능한 도구 (search_documents, answer_query, get_documents)를 나열합니다.Antigravity에서 사용 가능한 MCP 서버 확인

4. 애플리케이션 만들기 및 배포

이 섹션에서는 커스텀 VPC 네트워크 내의 비공개 Compute Engine VM 2개에 gCurrenC 계산기 애플리케이션을 배포합니다.

애플리케이션은 다음을 제공합니다.

  • 포트 8080에서 Python의 기본 제공 http.server 표준 라이브러리를 사용하고 /healthz 상태 점검 엔드포인트를 사용하여 USD, EUR, GBP, JPY, CAD, INR, AUD를 지원하는 실시간 환율 계산기입니다.
  • 실시간 아웃바운드 API 연결 및 암호화된 위협 방지 프로브를 실행하는 보안 확인 콘솔
  • 공개 IP 주소를 노출하지 않고 관리 테스트를 위해 Google의 IAP 범위가 포트 22 및 8080에 도달하도록 허용하는 인그레스 방화벽 규칙

애플리케이션 배포

  1. Antigravity 채팅 창에 /goal를 입력한 후 다음 프롬프트를 실행합니다.
    You are a Cloud developer. Deploy the "gCurrenC calculator" app onto two (2) Compute Engine VMs with no external IP addresses (`--no-address`) inside a dedicated custom VPC network and private subnet.
    
    CRITICAL INSTRUCTIONS ON OUTPUT:
    - The VMs are strictly private with no external IP addresses and the local IAP tunnel has NOT been started yet. Any web URL is completely unreachable and will fail with a connection error.
    - In your final response, simply confirm that the private VMs and Managed Instance Group are deployed, and state that the user should establish the IAP tunnel. Do not output, format, or suggest any web preview link or URL (such as http://localhost:8080 or internal IP addresses) in your final response.
    
    Run this script in the terminal:
    
    ```bash
    #!/usr/bin/env bash
    set -euxo pipefail
    
    # Disable any interactive confirmation prompts so execution never hangs
    export CLOUDSDK_CORE_DISABLE_PROMPTS=1
    
    # --- User Configuration ---
    PROJECT_ID="[PROJECT_ID]"
    REGION="us-central1"
    ZONE="us-central1-a"
    NETWORK="gcurrenc-vpc"
    SUBNET="gcurrenc-app-subnet"
    SUBNET_RANGE="10.10.1.0/24"
    # --------------------------
    
    echo "==> [1/5] Configuring project, default region/zone, and enabling APIs..."
    gcloud config set project "${PROJECT_ID}"
    gcloud config set compute/region "${REGION}"
    gcloud config set compute/zone "${ZONE}"
    gcloud services enable compute.googleapis.com
    
    echo "==> [2/5] Creating custom VPC network and private workload subnet..."
    gcloud compute networks create "${NETWORK}" \
       --subnet-mode=custom \
       --description="Dedicated VPC for currency exchange app demo" 2>/dev/null || true
    
    gcloud compute networks subnets create "${SUBNET}" \
       --network="${NETWORK}" \
       --region="${REGION}" \
       --range="${SUBNET_RANGE}" \
       --enable-private-ip-google-access \
       --description="Private subnet hosting backend compute instances" 2>/dev/null || true
    
    echo "==> [3/5] Generating standalone Python standard-library startup script..."
    cat << 'STARTUP_EOF' > /tmp/private_app_startup.sh
    #!/bin/bash
    set -euxo pipefail
    
    mkdir -p /opt/gcurrenc-app
    
    # Pure Python standard-library application (zero pip/apt dependencies needed at boot)
    cat << 'APPEOF' > /opt/gcurrenc-app/app.py
    import os
    import sys
    import json
    import socket
    import urllib.request
    import urllib.parse
    import ssl
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
    
    SUPPORTED_CURRENCIES = ["USD", "EUR", "GBP", "JPY", "CAD", "INR", "AUD"]
    
    class CurrencyAppHandler(BaseHTTPRequestHandler):
       def address_string(self):
          return str(self.client_address[0])
    
       def do_GET(self):
          parsed = urllib.parse.urlparse(self.path)
          path = parsed.path
          params = urllib.parse.parse_qs(parsed.query)
    
          if path == "/favicon.ico":
                self.send_response(204)
                self.end_headers()
                return
    
          if path == "/healthz":
                self.send_response(200)
                self.send_header("Content-Type", "text/plain")
                self.end_headers()
                self.wfile.write(b"OK")
                return
    
          if path == "/api/security-test":
                mode = params.get("mode", ["safe"])[0]
                target = "https://secure.eicar.org/eicar.com.txt" if mode == "threat" else "https://api.frankfurter.dev/v1/latest?from=USD&to=EUR"
                try:
                   req = urllib.request.Request(target, headers={"User-Agent": "SecureCurrencyApp/1.0"})
                   ctx = ssl.create_default_context()
                   with urllib.request.urlopen(req, timeout=5, context=ctx) as resp:
                      data = {"verdict": "PERMITTED", "target": target, "http_status": resp.status}
                      code = 200
                except Exception as e:
                   data = {"verdict": "BLOCKED_OR_FAILED", "target": target, "error": str(e)}
                   code = 502
    
                self.send_response(code)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps(data, indent=2).encode("utf-8"))
                return
    
          self.render_page()
    
       def do_POST(self):
          parsed = urllib.parse.urlparse(self.path)
          if parsed.path == "/generate":
                content_length = int(self.headers.get("Content-Length", 0))
                post_body = self.rfile.read(content_length).decode("utf-8")
                form = urllib.parse.parse_qs(post_body)
    
                base_curr = form.get("base_curr", ["USD"])[0]
                target_curr = form.get("target_curr", ["EUR"])[0]
                try:
                   amount = float(form.get("amount", ["2500.00"])[0])
                except ValueError:
                   amount = 2500.00
    
                rate_str = "Unavailable"
                total_str = "Rate lookup pending outbound internet activation"
                try:
                   if base_curr == target_curr:
                      rate = 1.0
                   else:
                      url = f"https://api.frankfurter.dev/v1/latest?from={base_curr}&to={target_curr}"
                      req = urllib.request.Request(url, headers={"User-Agent": "SecureCurrencyApp/1.0"})
                      with urllib.request.urlopen(req, timeout=4) as resp:
                            res_json = json.loads(resp.read().decode("utf-8"))
                            rate = res_json["rates"][target_curr]
                   rate_str = str(rate)
                   total_str = f"{round(amount * rate, 2):,.2f} {target_curr}"
                except Exception as e:
                   total_str = f"Outbound connection unavailable {str(e)}"
    
                self.render_page(base_curr, target_curr, amount, rate_str, total_str)
                return
    
          self.send_response(404)
          self.end_headers()
    
       def render_page(self, base_curr="USD", target_curr="EUR", amount=2500.00, fx_rate="1.00", total_str=""):
          hostname = socket.gethostname()
          curr_options_base = "".join([f'<option value="{c}" {"selected" if c == base_curr else ""}>{c}</option>' for c in SUPPORTED_CURRENCIES])
          curr_options_target = "".join([f'<option value="{c}" {"selected" if c == target_curr else ""}>{c}</option>' for c in SUPPORTED_CURRENCIES])
    
          result_block = ""
          if total_str:
                if fx_rate == "Unavailable":
                   rate_line = "<p style='margin: 6px 0;'>Exchange Rate: <span style='color: #d93025; font-weight: bold;'>⚠️ Offline-Outbound internet blocked</span></p>"
                else:
                   rate_line = f"<p style='margin: 6px 0; font-size: 14px; color: #137333;'>🟢 Exchange Rate: <strong>1 {base_curr} = {fx_rate} {target_curr}</strong> (Secured via Cloud NAT & Cloud NGFW)</p>"
    
                result_block = f"""
                <div style="margin-top: 22px; background: #e6f4ea; border: 1px solid #c6e1c6; border-left: 5px solid #34a853; padding: 18px 20px; border-radius: 8px;">
                   <h4 style="margin: 0 0 6px 0; text-transform: uppercase; font-size: 12px; color: #137333; letter-spacing: 0.5px;">Conversion Result</h4>
                   <div style="font-size: 24px; font-weight: 700; color: #202124; margin-bottom: 6px;">
                      {amount:,.2f} {base_curr} = <span style="color: #1a73e8;">{total_str}</span>
                   </div>
                   {rate_line}
                </div>
                """
    
          html = ("""<!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>gCurrenC calculator</title>
       <style>
          body {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
                background: #f8f9fa;
                margin: 30px 15px;
                color: #202124;
                display: flex;
                justify-content: center;
          }
          .container {
                width: 100%;
                max-width: 860px;
          }
          .card {
                background: white;
                padding: 24px 28px;
                border-radius: 12px;
                box-shadow: 0 1px 3px rgba(60,64,67,0.12), 0 4px 8px rgba(60,64,67,0.06);
                border: 1px solid #dadce0;
                margin-bottom: 20px;
          }
          .header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-bottom: 1px solid #e8eaed;
                padding-bottom: 14px;
                margin-bottom: 20px;
          }
          .header h2 {
                margin: 0 0 4px 0;
                font-size: 20px;
                font-weight: 600;
          }
          .header p {
                margin: 0;
                font-size: 13px;
                color: #5f6368;
          }
          .badge {
                background: #e8f0fe;
                color: #1a73e8;
                padding: 6px 12px;
                border-radius: 16px;
                font-weight: 600;
                font-size: 12px;
                border: 1px solid #d2e3fc;
                display: flex;
                align-items: center;
                gap: 6px;
          }
          .badge::before {
                content: "";
                width: 8px;
                height: 8px;
                border-radius: 50%;
                background-color: #34a853;
          }
          .form-row {
                display: flex;
                gap: 14px;
                align-items: flex-end;
                flex-wrap: wrap;
          }
          .form-group {
                display: flex;
                flex-direction: column;
                gap: 6px;
          }
          .form-group label {
                font-size: 12px;
                font-weight: 600;
                color: #5f6368;
                text-transform: uppercase;
                letter-spacing: 0.5px;
          }
          input, select {
                padding: 10px 14px;
                border: 1px solid #dadce0;
                border-radius: 6px;
                font-size: 14px;
                color: #202124;
                background-color: #fff;
                box-sizing: border-box;
                transition: border-color 0.15s, box-shadow 0.15s;
          }
          input:focus, select:focus {
                outline: none;
                border-color: #1a73e8;
                box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.15);
          }
          button {
                padding: 11px 20px;
                background: #1a73e8;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                transition: background 0.15s, box-shadow 0.15s;
          }
          button:hover {
                background: #1557b0;
                box-shadow: 0 1px 2px rgba(60,64,67,0.3);
          }
          .danger-btn {
                background: #d93025;
          }
          .danger-btn:hover {
                background: #b31412;
          }
          pre {
                background: #202124;
                color: #8ab4f8;
                padding: 14px;
                border-radius: 6px;
                overflow-x: auto;
                font-family: "SF Mono", "Fira Code", Consolas, monospace;
                font-size: 13px;
                line-height: 1.5;
                margin: 0;
          }
          /* Collapsible Security Console */
          details.security-drawer {
                background: white;
                border-radius: 12px;
                box-shadow: 0 1px 3px rgba(60,64,67,0.12);
                border: 1px solid #dadce0;
                overflow: hidden;
                margin-bottom: 24px;
          }
          details.security-drawer summary {
                padding: 16px 20px;
                font-size: 14px;
                font-weight: 600;
                cursor: pointer;
                list-style: none;
                display: flex;
                justify-content: space-between;
                align-items: center;
                user-select: none;
                background: #fafafa;
                transition: background 0.15s;
          }
          details.security-drawer summary::-webkit-details-marker {
                display: none;
          }
          details.security-drawer summary:hover {
                background: #f1f3f4;
          }
          details.security-drawer[open] summary {
                border-bottom: 1px solid #dadce0;
                background: #ffffff;
          }
          .expand-toggle {
                font-size: 13px;
                font-weight: 500;
          }
          details.security-drawer summary .expand-toggle::before {
                content: "▶ Click to Expand";
                color: #1a73e8;
          }
          details.security-drawer[open] summary .expand-toggle::before {
                content: "▼ Click to Collapse";
                color: #5f6368;
          }
          .drawer-body {
                padding: 20px;
                background: #ffffff;
          }
          .drawer-body p {
                margin-top: 0;
                font-size: 13px;
                color: #5f6368;
          }
          .probe-buttons {
                display: flex;
                gap: 10px;
                margin-bottom: 14px;
          }
       </style>
    </head>
    <body>
    <div class="container">
       <div class="card">
          <div class="header">
                <div>
                   <h2>💱 gCurrenC calculator</h2>
    
                </div>
                <div class="badge">Serving host: {hostname}</div>
          </div>
          <form method="POST" action="/generate">
                <div class="form-row">
                   <div class="form-group" style="flex: 1.5; min-width: 140px;">
                      <label>Amount</label>
                      <input type="number" step="0.01" name="amount" value="{amount}" required>
                   </div>
                   <div class="form-group" style="flex: 1; min-width: 100px;">
                      <label>From</label>
                      <select name="base_curr">{curr_options_base}</select>
                   </div>
                   <div class="form-group" style="flex: 1; min-width: 100px;">
                      <label>To (Target)</label>
                      <select name="target_curr">{curr_options_target}</select>
                   </div>
                   <div class="form-group">
                      <button type="submit">Convert currency ➔</button>
                   </div>
                </div>
          </form>
          {result_block}
       </div>
    
       <!-- Collapsible Security Verification Console -->
       <details class="security-drawer">
          <summary>
                <span>🛡️ Security verification console</span>
                <span class="expand-toggle"></span>
          </summary>
          <div class="drawer-body">
                <p>Test outbound HTTPS traffic and threat prevention capabilities in real time:</p>
                <div class="probe-buttons">
                   <button type="button" onclick="runProbe('safe')">Test Outbound API Connection</button>
                   <button type="button" class="danger-btn" onclick="runProbe('threat')">Simulate Encrypted Threat (EICAR)</button>
                </div>
                <pre id="output">Waiting for command...</pre>
          </div>
       </details>
    </div>
    <script>
    function runProbe(mode) {
       const el = document.getElementById('output');
       el.innerText = 'Executing outbound request...';
       fetch('/api/security-test?mode=' + mode)
          .then(res => res.json())
          .then(data => el.innerText = JSON.stringify(data, null, 2))
          .catch(err => el.innerText = 'Connection dropped / reset by Firewall: ' + err);
    }
    </script>
    </body>
    </html>"""
             .replace("{hostname}", str(hostname))
             .replace("{amount}", str(amount))
             .replace("{curr_options_base}", curr_options_base)
             .replace("{curr_options_target}", curr_options_target)
             .replace("{result_block}", result_block)
          )
          self.send_response(200)
          self.send_header("Content-Type", "text/html; charset=utf-8")
          self.end_headers()
          self.wfile.write(html.encode("utf-8"))
    
    def run():
       server_address = ('0.0.0.0', 8080)
       httpd = ThreadingHTTPServer(server_address, CurrencyAppHandler)
       httpd.serve_forever()
    
    if __name__ == '__main__':
       run()
    APPEOF
    
    # Register and start systemd unit
    cat << 'SERVICEEOF' > /etc/systemd/system/gcurrenc-app.service
    [Unit]
    Description=Currency exchange calculator web application
    After=network.target
    
    [Service]
    Type=simple
    User=root
    WorkingDirectory=/opt/gcurrenc-app
    ExecStart=/usr/bin/python3 /opt/gcurrenc-app/app.py
    Restart=always
    
    [Install]
    WantedBy=multi-user.target
    SERVICEEOF
    
    systemctl daemon-reload
    systemctl enable gcurrenc-app
    systemctl start gcurrenc-app
    STARTUP_EOF
    
    echo "==> [4/5] Creating Firewall, Regional Instance Template, and 2-VM MIG..."
    gcloud compute firewall-rules create allow-iap-admin \
       --network="${NETWORK}" \
       --allow=tcp:22,tcp:8080 \
       --source-ranges=35.235.240.0/20 \
       --target-tags=gcurrenc-app-vm \
       --description="Allow IAP SSH and port 8080 access to private VMs" \
       --quiet 2>/dev/null || true
    
    # Explicitly pass both --region and --instance-template-region to avoid prompt
    gcloud compute instance-templates create gcurrenc-app-template \
       --instance-template-region="${REGION}" \
       --region="${REGION}" \
       --network="${NETWORK}" \
       --subnet="${SUBNET}" \
       --machine-type=e2-medium \
       --no-address \
       --tags=gcurrenc-app-vm \
       --metadata-from-file=startup-script=/tmp/private_app_startup.sh \
       --quiet
    
    gcloud compute instance-groups managed create gcurrenc-app-mig \
       --base-instance-name=gcurrenc-vm \
       --template="projects/${PROJECT_ID}/regions/${REGION}/instanceTemplates/gcurrenc-app-template" \
       --size=2 \
       --zone="${ZONE}" \
       --quiet
    
    gcloud compute instance-groups managed set-named-ports gcurrenc-app-mig \
       --named-ports=http-port:8080 \
       --zone="${ZONE}" \
       --quiet
    
    echo "==> [5/5] Verifying private VM deployment and internal status..."
    sleep 30
    
    gcloud compute instances list \
       --filter="name ~ '^gcurrenc-vm-'" \
       --zones="${ZONE}" \
       --format="table(name,zone.basename():label=ZONE,networkInterfaces[0].networkIP:label=INTERNAL_IP,status)"
    
    FIRST_VM=$(gcloud compute instances list \
       --filter="name ~ '^gcurrenc-vm-'" \
       --zones="${ZONE}" \
       --format="value(name)" \
       --limit=1)
    
    echo "Testing healthz on ${FIRST_VM} via IAP tunnel..."
    gcloud compute ssh "${FIRST_VM}" \
       --zone="${ZONE}" \
       --tunnel-through-iap \
       --quiet \
       --command="curl -fsS http://localhost:8080/healthz"
    
    echo ""
    echo "=========================================================================="
    echo "PREREQUISITE COMPLETE: 2 private VMs deployed with no external IPs."
    echo "VPC: ${NETWORK} | Subnet: ${SUBNET} (${SUBNET_RANGE})"
    echo "Instance Group: gcurrenc-app-mig (Zone: ${ZONE}, Port: 8080)"
    echo ""
    echo "The VMs are private and the IAP tunnel is not active. Set up the background IAP tunnel first to access the deployed app."
    echo ""
    echo "=========================================================================="
    ```
    

VM 인스턴스 생성 확인

Antigravity가 두 개의 비공개 Compute Engine VM에 애플리케이션 배포를 완료하면 Google Cloud 콘솔에서 인스턴스를 확인합니다.

  1. Google Cloud 콘솔에서 VM 인스턴스로 이동합니다.
  2. 두 VM 인스턴스가 내부 IP 주소로 실행 중이고 외부 IP 주소가 없는지 확인합니다.외부 IP 주소가 없는 비공개 Compute Engine VM 인스턴스 2개 확인

5. 애플리케이션 테스트

비공개 VM에는 외부 IP 주소 (--no-address)와 Cloud NAT 게이트웨이가 없으므로 인터넷에 연결할 수 없고 외부 환율 API에 연결할 수 없습니다. 보안 아웃바운드 액세스를 구성하기 전에 로컬 IAP 터널을 통해 애플리케이션을 테스트하여 인터넷 액세스가 없는지 확인합니다.

  1. /goal 모드에서 Antigravity 채팅 창에 다음 프롬프트를 실행합니다.
    Automate the IAP tunnel configuration and health verification for the web app, then output the live test URL.
    
    Run a terminal script that performs the following steps non-interactively:
    
    1. Firewall Check:
       - Identify the active network ('gcurrenc-vpc' if it exists, otherwise 'default').
       - Idempotently ensure an ingress firewall rule exists permitting 'tcp:22,tcp:8080' from the Google IAP range '35.235.240.0/20' targeting 'gcurrenc-app-vm'.
    
    2. VM Health Verification:
       - Find the first running instance matching '^gcurrenc-vm-' in zone 'us-central1-a'.
       - Via 'gcloud compute ssh --tunnel-through-iap', verify that the 'gcurrenc-app' systemd service is active. If not active, restart it.
    
    3. Background IAP Tunnel:
       - Free up local port 8080 if an old tunnel or process is lingering (e.g., using 'lsof -ti:8080 | xargs kill -9' or 'fuser -k 8080/tcp').
       - Launch 'gcloud compute start-iap-tunnel <VM_NAME> 8080 --local-host-port=localhost:8080 --zone=us-central1-a' in the background using nohup, redirecting output to '/tmp/iap_tunnel.log'.
       - Wait up to 10 seconds for the tunnel to establish, checking with 'curl -fsS http://localhost:8080/healthz'.
    
    4. Output Web Preview URL:
       - Detect whether the environment is Google Cloud Shell (check if $CLOUD_SHELL is true) or a local workstation.
       - If Cloud Shell, print instructions and the direct web preview link.
       - If local machine, provide the clickable 'http://localhost:8080' URL.
    
  2. 터널이 시작되면 웹브라우저에서 http://localhost:8080/을 엽니다.아웃바운드 인터넷 액세스 권한이 없는 비공개 VM에서 실행되는 gCurrenC 계산기
  3. 애플리케이션을 테스트합니다.
    1. 통화 환산을 클릭합니다. 변환 결과에 Offline - Outbound internet blocked 및 Outbound connection unavailable가 표시됩니다. 비공개 VM은 인터넷에 연결하여 최신 환율을 가져올 수 없으므로 이 결과는 예상된 것입니다.
    2. 보안 확인 콘솔을 펼치고 아웃바운드 API 연결 테스트를 클릭합니다. 출력에 https://api.frankfurter.dev/v1/latest의 verdict: BLOCKED_OR_FAILED ()가 표시됩니다. 비공개 VM은 인터넷에 연결하여 https://api.frankfurter.dev/v1/latest에서 환율을 가져올 수 없으므로 이 결과는 예상된 것입니다.
    3. 암호화된 위협 시뮬레이션 (EICAR)을 클릭합니다. 출력에는 https://secure.eicar.org/eicar.com.txt의 verdict: BLOCKED_OR_FAILED도 표시됩니다. 비공개 VM에 인터넷 연결이 없으므로 이 결과도 예상된 것입니다.

로컬 IAP 터널 중지

보안 아키텍처를 설계하고 배포하기 전에 로컬 IAP 터널을 종료하여 포트 8080을 확보합니다.

  1. /goalThinking mode…
    Free up local port 8080 and terminate any running Google Cloud IAP tunnels (e.g., kill processes matching 'start-iap-tunnel' or listening on port 8080).
    
    Antigravity가 IAP 터널이 종료되고 로컬 포트 8080이 사용 가능한 상태임을 확인합니다.

6. 애플리케이션 보호

이전 섹션에서는 공개 IP 주소가 없는 비공개 Compute Engine VM을 만들고 두 가지 핵심 네트워킹 및 보안 문제를 확인했습니다.

  • 인바운드 액세스 (인그레스): 인터넷 사용자는 비공개 VM 인스턴스에 직접 도달할 수 없으며, 웹 애플리케이션을 노출하려면 VM을 공개 인터넷에 노출하지 않고 전역 외부 애플리케이션 부하 분산기와 전용 프록시 전용 서브넷을 통해 트래픽을 프록시해야 합니다.
  • 아웃바운드 액세스 (이그레스): 비공개 VM에는 실시간 HTTPS 환율 API를 쿼리하기 위해 인터넷에 연결할 수 있는 경로가 없으며, 아웃바운드 액세스를 사용 설정하려면 SSL/TLS 신뢰를 깨지 않고 멀웨어 및 데이터 무단 반출을 위해 암호화된 트래픽을 검사해야 합니다.

이 섹션에서는 공식 Google Cloud 문서 (@retrieving-developer-knowledge)를 기반으로 간소화된 워크플로를 통해 Antigravity를 안내하여 애플리케이션의 프로젝트 수준 인그레스 및 이그레스 보안 아키텍처를 설계, 자체 감사, 배포합니다.

통합 보안 아키텍처 설계

  1. /goal 모드에서 다음 프롬프트를 실행하여 인바운드 및 아웃바운드 트래픽 흐름을 모두 포괄하는 엔드 투 엔드 아키텍처 다이어그램과 설명을 생성합니다.
    You are a Google Cloud Network and Security Architect. We need to design an end-to-end security architecture for our "gCurrenC calculator" app running on private Compute Engine VMs with no external IP addresses inside 'gcurrenc-vpc'.
    
    We are operating in a standalone Google Cloud project without an Organization resource, so all security resources must be scoped at the project level.
    
    Use the @retrieving-developer-knowledge skill to consult official Google Cloud documentation and suggest an architecture diagram and explanation covering both flows:
    
    1. Ingress Flow:
       - How internet users securely reach the private VMs via a global external Application Load Balancer.
       - Why Envoy-based external Application Load Balancers require a dedicated proxy-only subnet, and how Google Front Ends (GFEs) proxy traffic to private backends without exposing VMs to the public internet.
    
    2. Egress Flow:
       - How private VMs reach the internet via Cloud NAT to query live currency exchange APIs, such as frankfurter.dev.
       - How Cloud NGFW Enterprise provides Layer 7 deep packet inspection and intrusion prevention (IPS) for outbound encrypted HTTPS traffic.
       - How TLS inspection backed by Certificate Authority Service (CAS) decrypts outbound HTTPS sessions on the fly, and what Root CA trust configuration the private VMs require.
    
    Provide a clear diagram and explain how these components connect together.
    
    Antigravity는 DK MCP 서버를 쿼리하고 전역 외부 애플리케이션 부하 분산, 프록시 전용 서브넷, Cloud NAT, CAS, 프로젝트 수준 Cloud NGFW Enterprise가 어떻게 연결되는지 보여주는 아키텍처 다이어그램과 설명을 반환합니다.

아키텍처 리소스 개요 생성

  1. 배포 스크립트를 생성하기 전에 다음 프롬프트를 입력하여 설계를 분류된 프로젝트 수준 리소스 개요로 구성합니다.
    Act as a Lead Network Security Architect. Using the @retrieving-developer-knowledge skill, provide an architectural outline of all the Google Cloud resources required to secure the "gCurrenC calculator" app.
    
    Our starting state:
    - The custom VPC ('gcurrenc-vpc'), workload subnet ('gcurrenc-app-subnet'), and 2-instance MIG ('gcurrenc-app-mig', port 8080) are already deployed.
    - All newly added security components must be project-level resources (no organization resources).
    
    Structure your resource outline into three distinct categories, indicating which resources are new additions:
    1. Core VPC Infrastructure: proxy-only subnet ('gcurrenc-proxy-subnet', 10.10.2.0/24), Cloud Router, and Cloud NAT gateway.
    2. Inbound security (ingress): global external ALB components (forwarding rule on port 443, target HTTPS proxy, SSL certificate, URL map, backend service attached to 'gcurrenc-app-mig' on port 8080, and HTTP health check on '/healthz') and ingress firewall rules.
    3. Outbound security (egress): CAS DevOps CA pool and root CA, project-level Cloud NGFW Enterprise components (Threat Prevention profile, Security Profile Group, Firewall Endpoint in zone us-central1-a, and Endpoint Association attaching the TLS policy), and global network firewall policy egress rules.
    
    For each resource, briefly state its role in the security boundary and how it connects to adjacent components.
    
    Antigravity는 핵심 VPC 인프라, 인바운드 부하 분산, 프로젝트 수준 아웃바운드 위협 방지에 매핑된 구조화된 리소스 개요를 생성합니다.

배포 스크립트 생성 및 자체 감사

  1. /goal 모드에서 다음 프롬프트를 실행하여 완전한 비대화형 bash 배포 스크립트를 생성하고 동일한 차례에 규정 준수 요구사항에 따라 자동으로 자체 감사합니다.
    Act as a Principal Infrastructure Engineer. Using the @retrieving-developer-knowledge skill, generate a complete, non-interactive Bash script to deploy this entire security architecture for our "gCurrenC calculator" app, and self-audit the script before outputting it.
    
    Requirements:
    - Discover the project ID, region, and zone dynamically from the existing 'gcurrenc-app-subnet' and 'gcurrenc-app-mig'.
    - Keep all resources scoped strictly to the project level (no Organization resource).
    - Deploy the proxy-only subnet, global external Application Load Balancer, Cloud Router, and Cloud NAT. Don't use Cloud Armor.
    - Deploy project-level Cloud NGFW Enterprise with CAS TLS inspection ('--tls-inspect' on the firewall policy egress rule and 'gcloud beta' for the project-level firewall endpoint association) and an explicit DENY override for malware and antivirus threats.
    - Distribute the root CA to the private VMs over IAP SSH with connection timeouts so the guest OS trust store is updated.
    - Print the final Load Balancer URL ('https://${LB_IP}') at the end.
    
    Wrap the script in 'set -euxo pipefail' and output only the single executable bash script block.
    
    Antigravity는 전체 bash 스크립트를 생성하고, 규정 준수 제약 조건에 따라 모든 명령어를 자체 감사하며, set -euxo pipefail로 래핑된 단일 실행 파일 스크립트 블록을 출력합니다.

보안 배포 스크립트 실행

  1. /goal 모드에서 이전 프롬프트에서 생성된 bash 스크립트를 다음 형식으로 Antigravity 채팅 창에 붙여넣어 배포를 실행하고 라이브 애플리케이션 URL (https://<LB_IP>)을 출력합니다.
    Run this script.
    <PASTED-SCRIPT>
    

7. 보안 애플리케이션 확인

배포 스크립트가 완료되면 Antigravity는 전역 외부 애플리케이션 부하 분산기 (https://<LB_IP>)의 외부 HTTPS URL을 출력합니다.

  1. 웹브라우저에서 https://<LB_IP>을 열고 브라우저의 자체 서명 인증서 경고를 우회하여 gCurrenC 계산기 인터페이스를 로드합니다.전역 외부 애플리케이션 부하 분산기, Cloud NAT, Cloud NGFW Enterprise로 보호되는 gCurrenC 계산기
  2. 애플리케이션을 테스트하여 아웃바운드 연결과 위협 방지를 모두 확인합니다.
    1. 통화 환산을 클릭합니다. 애플리케이션은 실시간으로 변환된 환율을 즉시 표시합니다. 이를 통해 인그레스 부하 분산이 Google 프런트엔드 (GFE)와 프록시 전용 서브넷을 통해 원활하게 라우팅되고 Cloud NAT가 api.frankfurter.dev에서 실시간 환율을 가져오는 것을 확인할 수 있습니다.
    2. 보안 확인 콘솔을 펼치고 아웃바운드 API 연결 테스트를 클릭합니다. 애플리케이션에 verdict: PERMITTED (HTTP 200)가 표시됩니다. 이는 Cloud NAT 라우팅이 작동하고 VM 운영체제가 복호화된 HTTPS 세션에 대해 비공개 CAS 루트 CA를 신뢰함을 확인합니다.
    3. 암호화된 위협 시뮬레이션 (EICAR)을 클릭합니다. 애플리케이션에 verdict: PERMITTED이 표시됩니다. 이를 통해 Cloud NGFW Enterprise가 CAS에서 지원하는 TLS 검사를 사용하여 아웃바운드 HTTPS 요청을 복호화하고 침입 방지 서비스 (IPS)를 사용하여 EICAR 테스트 서명을 검사하는 것을 확인할 수 있습니다.

8. 삭제

이 Codelab에서 만든 리소스의 비용이 Google Cloud 계정에 청구되지 않도록 하려면 Codelab 리소스만 삭제하거나 Google Cloud 프로젝트를 삭제하면 됩니다.

  1. Google Cloud 프로젝트를 유지하고 이 Codelab에서 만든 리소스만 삭제하려면 Antigravity 채팅 창에서 /goal 모드로 다음 프롬프트를 실행합니다.
    Remove all resources created in this session, including the gcurrenc app and its resources. Don't delete the project.
    
  2. 이 Codelab을 위해 전용 Google Cloud 프로젝트를 만들었고 전체 프로젝트를 삭제하려면 Antigravity 채팅 창에서 /goal 모드로 다음 프롬프트를 실행합니다.
    Clean up the demo environment by deleting the Google Cloud project. Run the following command in the terminal:
    gcloud projects delete "$(gcloud config get-value project 2>/dev/null)" --quiet
    

9. 축하합니다

수고하셨습니다 Google Antigravity에서 Google Cloud 개발자 플러그인 (DK MCP 서버)을 사용하여 Google Cloud에 gCurrenC 계산기 웹 애플리케이션을 배포하고 보호했습니다.

다음 단계

공식 Google Cloud 문서를 살펴보고 이 Codelab에서 사용되는 서비스에 대해 자세히 알아보세요.