빠른 연결로 Cloud Run 서비스 간 인증 간소화

1. 개요

Cloud Run에서 마이크로서비스 또는 멀티 에이전트 애플리케이션을 빌드할 때는 내부 백엔드 서비스가 공개 인터넷에 노출되지 않아야 합니다. 대신 각 백엔드 서비스가 인증(--no-allow-unauthenticated)을 요구하도록 구성하고 승인된 호출자에게만 Cloud Run 호출자(roles/run.invoker) IAM 역할을 부여합니다.

기존에는 인증된 Cloud Run 서비스를 호출하려면 호출 애플리케이션이 코드에서 수동 토큰 삽입을 수행해야 했습니다. HTTP 요청을 전송하기 전에 코드가 Compute 메타데이터 서버에 Google 서명 OpenID Connect(OIDC) ID 토큰을 쿼리합니다. 이 토큰은 대상 서비스의 대상 URL로 범위가 지정되며 코드는 이를 Authorization: Bearer 헤더에 연결합니다. 애플리케이션 코드 내에서 인증 배관을 작성하고 유지보수하면 불필요한 마찰이 발생합니다.

  • 비즈니스 로직을 Google Cloud 인증 라이브러리에 결합하여 환경 전반의 가독성과 이식성을 저하시킵니다.
  • 토큰 획득 로직은 대상 유형과 보안 모드에 따라 다릅니다. 예를 들어 Cloud Run에는 OIDC ID 토큰이 필요하고, Google API에는 OAuth 2.0 액세스 토큰이 필요하며, mTLS에는 바인딩된 토큰이 필요합니다.

Cloud Run 빠른 연결(프리뷰)은 애플리케이션 코드에서 수동 토큰 삽입을 삭제합니다. 호출(소스) Cloud Run 서비스에서 앰비언트 네트워킹을 사용 설정하고 소스 서비스를 대상 서비스에 바인딩하는 선언적 ExpressLink 리소스를 만듭니다. Google 관리형 사이드카 프록시는 대상으로 향하는 아웃바운드 일반 텍스트 HTTP 요청을 가로채고 호출자 서비스의 ID 토큰을 자동으로 삽입하며 대상으로의 연결을 암호화합니다.

이 Codelab에서는 동일한 비공개 백엔드 서비스에 대해 두 가지 접근 방식을 비교합니다.

  1. Python으로 Compute 메타데이터 서버에서 OIDC ID 토큰을 가져오는 비공개 대상 서비스와 호출자 서비스(caller-oidc)를 배포합니다. 이 단계에서는 백엔드에 대한 엔드 투 엔드 연결을 확인하고 빠른 연결 없이 필요한 인증 코드를 보여줍니다.
  2. 메타데이터 토큰 가져오기 코드가 삭제된 두 번째 호출자 서비스(caller-express-link)를 배포하고 앰비언트 네트워킹과 빠른 연결을 사용하여 대상 서비스에 연결합니다.
PART 1: WITHOUT EXPRESS LINK (caller-oidc)
+----------------------------------------------+          +-----------------+
| Caller Service (caller-oidc)                 |  HTTPS   | Destination     |
|                                              | + token  | (destination)   |
|  App Container                               | -------> |                 |
|   1. Parse audience URL with urllib.parse    |          | Verifies caller |
|   2. Fetch OIDC ID token via google-auth     |          | has IAM role    |
|   3. Set Authorization: Bearer header        |          | run.invoker     |
+----------------------------------------------+          +-----------------+

PART 2: WITH EXPRESS LINK (caller-express-link)
+----------------------------------------------+          +-----------------+
| Caller Service (caller-express-link)         |  HTTPS   | Destination     |
|  +----------------+      +----------------+  | + token  | (destination)   |
|  | App Container  | HTTP | Ambient        |  | -------> |                 |
|  | requests.get() | ---> | Sidecar Proxy  |  |          | Same service    |
|  | (no auth code) |      | (Express Link) |  |          | as Part 1       |
|  +----------------+      +----------------+  |          | (unchanged)     |
+----------------------------------------------+          +-----------------+

기본 요건

  • Python 및 HTTP 웹 서비스에 대한 기본 지식
  • Google Cloud IAM 서비스 계정 및 Cloud Run 배포에 대한 기본 지식

학습할 내용

  • IAM 인증을 시행하는 비공개 Cloud Run 대상 서비스를 배포하는 방법
  • 메타데이터 서버의 google-auth OIDC ID 토큰을 사용하여 Python에서 서비스 간 요청을 수동으로 인증하여 기본 연결을 확인하는 방법
  • 수동 토큰 가져오기 코드를 삭제하고 앰비언트 네트워킹이 사용 설정된 Cloud Run 호출자 서비스를 배포하는 방법
  • 호출자 서비스가 인증 코드를 사용하지 않고 인증된 대상 서비스를 호출할 수 있도록 Cloud Run 빠른 연결을 만드는 방법

빌드할 항목

  • destination: /ping 엔드포인트를 노출하는 Cloud Run의 비공개 Python Flask 서비스
  • caller-oidc: 애플리케이션 코드에서 OIDC ID 토큰을 수동으로 가져오고 삽입하여 destination을 호출하는 Python Flask 서비스
  • caller-express-link: 빠른 연결을 통해 동일한 destination 서비스를 호출하는 토큰 삽입 코드가 없는 Python Flask 서비스

필요한 항목

  • 웹브라우저(예: Chrome)
  • 결제가 사용 설정되어 있고 IAM 서비스 계정, Cloud Run 서비스, 네트워크 서비스 리소스를 만들 수 있는 권한이 있는 Google Cloud 프로젝트

2. 환경 설정

Google Cloud 프로젝트 설정

  1. 아직 Google 계정이 없다면 Google 계정을 만들어야 합니다.
    • 직장 또는 학교 계정 대신 개인 계정을 사용합니다. 직장 및 학교 계정에는 이 실습에 필요한 API를 사용 설정하지 못하도록 하는 제한사항이 있을 수 있습니다.
  2. Google Cloud 콘솔에 로그인합니다.
  3. Cloud 콘솔에서 결제를 사용 설정합니다.
    • 이 실습을 완료하는 데 드는 클라우드 리소스 비용은 $1(USD) 미만입니다.
    • 이 실습이 끝날 때 안내되는 단계에 따라 리소스를 삭제하면 추가 요금이 청구되지 않습니다.
    • 신규 사용자는 미화 $300 상당의 무료 체험판을 사용할 수 있습니다.
  4. 새 프로젝트를 만들거나 기존 프로젝트를 재사용합니다.
    • 프로젝트 할당량에 관한 오류가 표시되면 기존 프로젝트를 재사용하거나 기존 프로젝트를 삭제하여 새 프로젝트를 만듭니다.

Cloud Shell 시작

이 Codelab에서는 Google Cloud CLI(gcloud), Python, curl가 사전 설치된 브라우저 기반 명령줄 환경인 Cloud Shell을 사용합니다.

  1. Google Cloud 콘솔의 상단 탐색 메뉴에서 Cloud Shell 활성화를 클릭합니다. 메시지가 표시되면 승인을 클릭합니다.
  2. 프로젝트 ID와 배포 리전을 내보내고 $PROJECT_ID를 사용하도록 gcloud를 구성합니다. YOUR_PROJECT_ID를 프로젝트 ID로 바꾸고 원하는 경우 us-west1를 다른 Cloud Run 리전으로 바꿉니다.
export PROJECT_ID="YOUR_PROJECT_ID"
export REGION="us-west1"
gcloud config set project "$PROJECT_ID"
  1. 프로젝트 번호와 활성 Google Cloud 계정을 내보내고 네 가지 변수가 모두 채워졌는지 확인합니다.
export PROJECT_NUMBER=$(gcloud projects describe "$PROJECT_ID" --format="value(projectNumber)")
export ACTIVE_ACCOUNT=$(gcloud config get-value account 2>/dev/null)
echo "PROJECT_ID: $PROJECT_ID | PROJECT_NUMBER: $PROJECT_NUMBER | ACCOUNT: $ACTIVE_ACCOUNT | REGION: $REGION"

gcloud 업데이트 및 API 사용 설정

  1. 앰비언트 네트워킹 및 빠른 연결을 위한 최신 beta 명령어를 사용할 수 있도록 gcloud 구성요소를 업데이트합니다.
gcloud components update --quiet
  1. Cloud Run 소스 배포, IAM 서비스 계정, 앰비언트 네트워킹, Network Services 빠른 연결에 필요한 Google Cloud API를 사용 설정합니다.
gcloud services enable \
    iam.googleapis.com \
    run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com \
    networkservices.googleapis.com \
    networksecurity.googleapis.com \
    trafficdirector.googleapis.com \
    cloudtrace.googleapis.com

작업공간 디렉터리 만들기

이 Codelab에서 빌드할 세 개의 서비스 폴더를 보관할 작업 디렉터리를 만듭니다.

mkdir -p ~/express-link-codelab
cd ~/express-link-codelab

3. 비공개 대상 서비스 배포

먼저 destination이라는 비공개 Cloud Run 서비스를 배포합니다. 이 단일 대상 서비스를 Codelab의 두 부분에 모두 재사용합니다.

  • 대상 서비스는 아웃바운드 토큰 삽입을 수행하지 않습니다.
  • 대상 서비스는 빠른 연결을 통해 트래픽을 수신하기 위해 앰비언트 네트워킹을 사용 설정할 필요가 없습니다.
  1. 대상 서비스의 전용 IAM 서비스 계정을 만듭니다.
gcloud iam service-accounts create destination-identity \
    --display-name="Cloud Run destination service account"
  1. destination 폴더를 만들고 해당 폴더로 이동합니다.
mkdir -p ~/express-link-codelab/destination
cd ~/express-link-codelab/destination
  1. 다음 명령어를 실행하여 Flask 및 Gunicorn으로 requirements.txt 파일을 만듭니다.
cat << 'EOF' > requirements.txt
Flask==3.0.0
gunicorn==21.2.0
EOF
  1. 다음 명령어를 실행하여 K_SERVICE 환경 변수에서 Cloud Run 서비스 이름을 반환하는 /ping 엔드포인트를 노출하는 main.py 파일을 만듭니다.
cat << 'EOF' > main.py
import os
from flask import Flask

app = Flask(__name__)

@app.route("/ping")
def ping():
    service_name = os.environ.get("K_SERVICE", "unknown")
    return f"Hello from {service_name}"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
EOF
  1. Cloud Run이 인증되지 않은 요청을 거부하도록 --no-allow-unauthenticated를 사용하여 소스에서 destination를 배포합니다.
gcloud run deploy destination \
    --source . \
    --region="$REGION" \
    --service-account="destination-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --no-allow-unauthenticated
  1. 대상 서비스의 결정론적 URL과 전체 리소스 URI를 환경 변수에 저장합니다.
export DESTINATION_URL="https://destination-${PROJECT_NUMBER}.${REGION}.run.app"
export DESTINATION_URI="//run.googleapis.com/projects/${PROJECT_NUMBER}/locations/${REGION}/services/destination"
echo "DESTINATION_URL: $DESTINATION_URL"
echo "DESTINATION_URI: $DESTINATION_URI"
  1. Cloud Shell에서 직접 테스트할 수 있도록 사용자 계정에 destination에 대한 Cloud Run 호출자(roles/run.invoker) 역할을 부여합니다.
gcloud run services add-iam-policy-binding destination \
    --member="user:$ACTIVE_ACCOUNT" \
    --role="roles/run.invoker" \
    --region="$REGION"
  1. 자체 ID 토큰을 사용하여 인증된 요청을 /ping에 전송하여 destination가 실행 중인지 확인합니다.
TOKEN=$(gcloud auth print-identity-token)
curl -H "Authorization: Bearer $TOKEN" "$DESTINATION_URL/ping"

다음과 같은 응답이 표시됩니다.

Hello from destination

4. 빠른 연결 없이 대상 호출

빠른 연결을 도입하기 전에 caller-oidc를 빌드하여 현재 서비스 간 인증에 필요한 사항을 확인하고 호출 서비스가 destination에 도달할 수 있는지 확인합니다. 빠른 연결 없이 destination를 안전하게 호출하려면 다음 두 레이어를 구성해야 합니다.

  • IAM 승인: caller-oidc 서비스 계정에 destination에 대한 roles/run.invoker 역할을 부여합니다.
  • 애플리케이션 수준 토큰 삽입: google-auth 라이브러리를 caller-oidc에 추가하고 대상 URL을 파싱하여 루트 OIDC 잠재고객을 추출합니다. 그런 다음 메타데이터 서버에서 서명된 ID 토큰을 가져와 Authorization: Bearer ID_TOKEN를 아웃바운드 HTTPS 요청에 연결합니다.

caller-oidc를 구성하고 배포하려면 다음 단계를 따르세요.

  1. caller-oidc의 전용 서비스 계정을 만듭니다.
gcloud iam service-accounts create caller-oidc-identity \
    --display-name="Cloud Run OIDC caller service account"
  1. caller-oidc-identity가 destination를 호출하도록 승인합니다.
gcloud run services add-iam-policy-binding destination \
    --member="serviceAccount:caller-oidc-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role="roles/run.invoker" \
    --region="$REGION"
  1. destination과 함께 caller-oidc 디렉터리를 만듭니다.
mkdir -p ~/express-link-codelab/caller-oidc
cd ~/express-link-codelab/caller-oidc
  1. 다음 명령어를 실행하여 requirements.txt 파일을 만듭니다. 애플리케이션 컨테이너에서 토큰 검색을 처리하려면 google-auth를 구체적으로 추가해야 합니다.
cat << 'EOF' > requirements.txt
Flask==3.0.0
google-auth==2.23.0
requests==2.31.0
gunicorn==21.2.0
EOF
  1. 다음 명령어를 실행하여 수동 OIDC 토큰 삽입으로 main.py 파일을 만듭니다.
cat << 'EOF' > main.py
import os
from urllib.parse import urlparse
from flask import Flask, request
from google.auth.transport.requests import Request as GoogleAuthRequest
from google.oauth2 import id_token
import requests

app = Flask(__name__)

@app.route("/ping")
def ping():
    service_name = os.environ.get("K_SERVICE", "unknown")
    return f"Hello from {service_name}"

@app.route("/")
def call_destination():
    target_url = request.args.get("target_url")
    if not target_url:
        return "Error: target_url query parameter not set.", 400

    try:
        # 1. Extract the root service URL (scheme + host) for the OIDC audience claim
        parsed_url = urlparse(target_url)
        target_audience = f"{parsed_url.scheme}://{parsed_url.netloc}"

        # 2. Fetch a Google-signed OIDC ID token from the metadata server
        auth_req = GoogleAuthRequest()
        token = id_token.fetch_id_token(auth_req, target_audience)

        # 3. Inject the token as an HTTP Bearer header
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(target_url, headers=headers, timeout=10)
        return f"I called the destination and it replied: '{response.text}'"
    except Exception as e:
        return f"Error calling destination: {str(e)}", 500

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
EOF
  1. Cloud Run에 caller-oidc를 배포합니다.
gcloud run deploy caller-oidc \
    --source . \
    --region="$REGION" \
    --service-account="caller-oidc-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --no-allow-unauthenticated
  1. 사용자 계정에 caller-oidc 호출 권한을 부여합니다.
gcloud run services add-iam-policy-binding caller-oidc \
    --member="user:$ACTIVE_ACCOUNT" \
    --role="roles/run.invoker" \
    --region="$REGION"
  1. caller-oidc의 결정론적 URL을 저장하고 호출하여 HTTPS URL $DESTINATION_URL/ping을 target_url로 전달합니다.
export CALLER_OIDC_URL="https://caller-oidc-${PROJECT_NUMBER}.${REGION}.run.app"
TOKEN=$(gcloud auth print-identity-token)
curl -H "Authorization: Bearer $TOKEN" "$CALLER_OIDC_URL/?target_url=$DESTINATION_URL/ping"

destination에서 성공적인 응답이 표시됩니다.

I called the destination and it replied: 'Hello from destination'

5. 빠른 연결을 위한 호출자 서비스 배포

이제 동위 디렉터리에 caller-express-link라는 두 번째 호출자 서비스를 빌드합니다. 빠른 연결을 사용하면 caller-express-link에 토큰 삽입 코드가 필요하지 않으며 requests.get(target_url, timeout=10)를 직접 호출합니다.

  1. caller-express-link의 전용 서비스 계정을 만듭니다.
gcloud iam service-accounts create caller-express-link-identity \
    --display-name="Cloud Run Express Link caller service account"
  1. 관리형 앰비언트 네트워킹 사이드카가 빠른 연결 라우팅 및 보안 구성을 다운로드할 수 있도록 caller-express-link-identity에 roles/trafficdirector.client 역할을 부여합니다. 사이드카가 trace 스팬을 내보낼 수 있도록 roles/cloudtrace.agent도 부여합니다.
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role="roles/trafficdirector.client"

gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role="roles/cloudtrace.agent"
  1. caller-oidc과 함께 caller-express-link 디렉터리를 만듭니다.
mkdir -p ~/express-link-codelab/caller-express-link
cd ~/express-link-codelab/caller-express-link
  1. 다음 명령어를 실행하여 google-auth 없이 requirements.txt 파일을 만듭니다.
cat << 'EOF' > requirements.txt
Flask==3.0.0
requests==2.31.0
gunicorn==21.2.0
EOF
  1. 다음 명령어를 실행하여 일반 requests.get(target_url, timeout=10) 호출이 있고 토큰 삽입 로직이 없는 main.py 파일을 만듭니다.
cat << 'EOF' > main.py
import os
from flask import Flask, request
import requests

app = Flask(__name__)

@app.route("/ping")
def ping():
    service_name = os.environ.get("K_SERVICE", "unknown")
    return f"Hello from {service_name}"

@app.route("/")
def call_destination():
    target_url = request.args.get("target_url")
    if not target_url:
        return "Error: target_url query parameter not set.", 400

    try:
        response = requests.get(target_url, timeout=10)
        return f"I called the destination and it replied: '{response.text}'"
    except Exception as e:
        return f"Error calling destination: {str(e)}", 500

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
EOF
  1. ../caller-oidc/main.py에 대해 diff를 실행하여 삭제한 인증 상용구를 확인합니다.
diff -u ../caller-oidc/main.py main.py || true
  1. --ambient-networking 및 --ambient-scope=global를 사용 설정한 상태에서 gcloud beta run deploy를 사용하여 caller-express-link를 배포합니다.
gcloud beta run deploy caller-express-link \
    --source . \
    --region="$REGION" \
    --service-account="caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --no-allow-unauthenticated \
    --ambient-networking \
    --ambient-scope=global
  1. caller-express-link에서 앰비언트 네트워킹이 활성 상태인지 확인합니다.
gcloud run services describe caller-express-link --region="$REGION"

버전 요약 끝에서 Ambient Networking 및 Ambient Scope가 표시되는지 확인합니다.

  Ambient Networking: Enabled
  Ambient Scope:     global
  1. 사용자 계정에 caller-express-link 호출 권한을 부여하고 caller-express-link-identity에 destination 호출 권한을 부여합니다.
gcloud run services add-iam-policy-binding caller-express-link \
    --member="user:$ACTIVE_ACCOUNT" \
    --role="roles/run.invoker" \
    --region="$REGION"

gcloud run services add-iam-policy-binding destination \
    --member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role="roles/run.invoker" \
    --region="$REGION"
  1. caller-express-link의 URL 및 리소스 URI를 destination의 HTTP(http://) 결정론적 URL과 함께 저장합니다.
export CALLER_EL_URL="https://caller-express-link-${PROJECT_NUMBER}.${REGION}.run.app"
export CALLER_EL_URI="//run.googleapis.com/projects/${PROJECT_NUMBER}/locations/${REGION}/services/caller-express-link"
export DESTINATION_HTTP_URL="http://destination-${PROJECT_NUMBER}.${REGION}.run.app"
echo "CALLER_EL_URL: $CALLER_EL_URL"
echo "CALLER_EL_URI: $CALLER_EL_URI"
echo "DESTINATION_HTTP_URL: $DESTINATION_HTTP_URL"
  1. 빠른 연결을 만들기 전에 caller-express-link를 통해 destination를 호출하는 테스트를 수행합니다.
TOKEN=$(gcloud auth print-identity-token)
curl -H "Authorization: Bearer $TOKEN" "$CALLER_EL_URL/?target_url=$DESTINATION_HTTP_URL/ping"

예상대로 요청을 가로채고 사용자 인증 정보를 삽입할 빠른 연결이 아직 없으므로 호출이 403 Forbidden로 실패합니다.

I called the destination and it replied: '
<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>403 Forbidden</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Forbidden</h1>
<h2>Your client does not have permission to get URL <code>/ping</code> from this server.</h2>
<h2></h2>
</body></html>
'

6. 빠른 연결로 서비스 연결

이제 코드 한 줄도 변경하지 않고 Cloud Run 서비스를 재배포하지도 않은 채 caller-express-link(소스 서비스)를 destination에 연결하는 ExpressLink 리소스를 선언합니다.

  1. global 위치에 빠른 연결 리소스를 만듭니다.
gcloud beta network-services express-links create caller-to-destination \
    --location=global \
    --description="Express Link from caller-express-link to destination" \
    --source-services="$CALLER_EL_URI" \
    --destination-services="$DESTINATION_URI"
  1. 빠른 연결을 나열하여 리소스가 있는지 확인합니다.
gcloud beta network-services express-links list --location=global

명령어 출력:

NAME
caller-to-destination
  1. 빠른 연결 구성 세부정보를 검사합니다.
gcloud beta network-services express-links describe caller-to-destination --location=global

명령어 출력:

createTime: '2026-10-27T19:30:04.492105068Z'
description: Express Link from caller-express-link to destination
destination:
  services:
  - //run.googleapis.com/projects/PROJECT_NUMBER/locations/us-west1/services/destination
etag: ...
name: projects/PROJECT_ID/locations/global/expressLinks/caller-to-destination
source:
  services:
  - //run.googleapis.com/projects/PROJECT_NUMBER/locations/us-west1/services/caller-express-link
updateTime: '2026-10-27T19:30:11.309054865Z'
  1. caller-express-link에 대해 정확히 동일한 curl 요청을 다시 실행합니다.
TOKEN=$(gcloud auth print-identity-token)
curl -H "Authorization: Bearer $TOKEN" "$CALLER_EL_URL/?target_url=$DESTINATION_HTTP_URL/ping"

이번에는 Ambient 사이드카가 destination에 대한 HTTP 요청을 가로채고, caller-express-link-identity의 ID 토큰을 삽입하고, 연결을 TLS로 업그레이드하고, 대상의 응답을 반환합니다.

I called the destination and it replied: 'Hello from destination'

다음 표에는 caller-oidc와 caller-express-link 간의 변경사항이 요약되어 있습니다.

측정기준

빠른 연결(caller-oidc) 없음

빠른 연결(caller-express-link) 사용

requirements.txt의 인증 라이브러리

google-auth 필요

없음(Flask, requests, gunicorn만 해당)

main.py에 아웃바운드 전화

잠재고객 URL 파싱, id_token.fetch_id_token() 호출, Authorization: Bearer 헤더 연결

일반 requests.get(target_url, timeout=10)

앱의 타겟 URL 스키마

https://destination-PROJECT_NUMBER.REGION.run.app

http://destination-PROJECT_NUMBER.REGION.run.app(Ambient 사이드카에 의해 TLS로 업그레이드됨)

호출자 Cloud Run 구성

표준 배포

호출자 서비스 계정에 대한 --ambient-networking --ambient-scope=global + roles/trafficdirector.client

대상 Cloud Run 구성

--no-allow-unauthenticated + roles/run.invoker

변경되지 않음(--no-allow-unauthenticated + roles/run.invoker)

7. 삭제

Google Cloud 계정에 요금이 계속 청구되지 않도록 하려면 이 Codelab에서 만든 리소스를 삭제하세요.

  1. 빠른 연결 리소스를 삭제합니다.
gcloud beta network-services express-links delete caller-to-destination --location=global --quiet
  1. Cloud Run 서비스 3개를 삭제합니다.
gcloud run services delete caller-express-link --region="$REGION" --quiet
gcloud run services delete caller-oidc --region="$REGION" --quiet
gcloud run services delete destination --region="$REGION" --quiet
  1. 프로젝트 수준 IAM 정책 바인딩을 삭제하고 서비스 계정 3개를 삭제합니다.
gcloud projects remove-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role="roles/trafficdirector.client" \
    --quiet

gcloud projects remove-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role="roles/cloudtrace.agent" \
    --quiet

gcloud iam service-accounts delete "caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" --quiet
gcloud iam service-accounts delete "caller-oidc-identity@${PROJECT_ID}.iam.gserviceaccount.com" --quiet
gcloud iam service-accounts delete "destination-identity@${PROJECT_ID}.iam.gserviceaccount.com" --quiet
  1. (선택사항) 이 Codelab 전용으로 Google Cloud 프로젝트를 만든 경우 전체 프로젝트를 삭제할 수 있습니다.
# Run only if you want to delete the entire project and all its resources
gcloud projects delete "$PROJECT_ID"

8. 축하합니다

비공개 Cloud Run 백엔드 서비스를 배포하고 Python에서 수동 OIDC 토큰 삽입을 사용하여 호출했습니다. 그런 다음 모든 애플리케이션 수준 인증 코드를 선언적 Cloud Run 빠른 연결로 대체했습니다.

학습한 내용

  • 수동 OIDC 토큰 삽입이 애플리케이션 비즈니스 로직을 플랫폼 인증 라이브러리 및 보안 모드에 결합하는 이유
  • 빠른 연결 사용 여부와 관계없이 변경 없이 작동하는 인증된 Cloud Run 대상 서비스를 배포하는 방법
  • 호출하는 Cloud Run 서비스에서 앰비언트 네트워킹(--ambient-networking with --ambient-scope=global)을 사용 설정하고 Traffic Director 클라이언트 권한(roles/trafficdirector.client)을 부여하는 방법
  • ID 토큰을 자동으로 삽입하고 컨테이너에서 암호화된 TLS 연결로의 일반 텍스트 http:// 호출을 업그레이드하는 Network Services ExpressLink 리소스를 만들고 검사하는 방법

다음 단계