arrow_back

Developer Essentials: Application Development with Secret Manager

로그인 가입
700개 이상의 실습 및 과정 이용하기

Developer Essentials: Application Development with Secret Manager

실습 30분 universal_currency_alt 크레딧 1개 show_chart 입문
info 이 실습에는 학습을 지원하는 AI 도구가 통합되어 있을 수 있습니다.
700개 이상의 실습 및 과정 이용하기

gem-secret-manager-cloud-run

Google Cloud self-paced labs logo

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:

Your Cloud Platform project in this session is set to YOUR_PROJECT_ID

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

  2. Your output should now look like this:

Output:

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = <project_ID>

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Overview

This lab guides you through developing and deploying a secure application on Google Cloud Run using Secret Manager to store and manage sensitive information. You will learn how to integrate Secret Manager with Cloud Run to inject secrets into your application at runtime, enhancing security and simplifying configuration management. This lab assumes familiarity with Docker, Cloud Run, and basic application development concepts. We'll be using Artifact Registry to store container images.

Task 1. Set Up Your Environment

Configure your Google Cloud environment for this lab by setting the project ID and enabling the necessary APIs.

  1. Set your Project ID:

    gcloud config set project {{{ project_0.project_id | "PROJECT_ID" }}} Note:
    This command configures the `gcloud` tool to use your project.
  2. Set your default region:

    gcloud config set run/region {{{ project_0.default_region | "REGION" }}} Note:
    This command sets your active cloud run region.
  3. Enable the Secret Manager, Cloud Run, and Artifact Registry APIs:

    gcloud services enable secretmanager.googleapis.com run.googleapis.com artifactregistry.googleapis.com Note:
    This command enables the required Google Cloud services for the lab.

Task 2. Create a Secret in Secret Manager

Create a secret in Secret Manager to store your sensitive data (e.g., API key, password).

  1. Create a new secret. Replace arcade-secret with the desired name for your secret.

    gcloud secrets create arcade-secret --replication-policy=automatic Note:
    This command creates a new secret in Secret Manager. The `automatic` replication policy ensures high availability.
  2. Add a secret version with your sensitive data.

    echo -n "t0ps3cr3t!" | gcloud secrets versions add arcade-secret --data-file=- Note:
    This command adds a new version to your secret, storing your sensitive data. Ensure the data is properly encoded.

Task 3. Python Application to to interact with Secret Manager

  1. Create a file app.py file to retrieve a secret

    import os from flask import Flask, jsonify, request from google.cloud import secretmanager import logging app = Flask(__name__) # Configure logging logging.basicConfig(level=logging.INFO) # Initialize Secret Manager client # The client will automatically use the service account credentials of the Cloud Run service secret_manager_client = secretmanager.SecretManagerServiceClient() # Hardcoded Project ID and Secret ID as per your request PROJECT_ID = "{{{ project_0.project_id | PROJECT_ID }}}" # Project ID SECRET_ID = "arcade-secret" # Secret Identifier @app.route('/') def get_secret(): """ Retrieves the specified secret from Secret Manager and returns its payload. The SECRET_ID and PROJECT_ID are now hardcoded in the application. """ if not SECRET_ID or not PROJECT_ID: logging.error("SECRET_ID or PROJECT_ID not configured (should be hardcoded).") return jsonify({"error": "Secret ID or Project ID not configured."}), 500 secret_version_name = f"projects/{PROJECT_ID}/secrets/{SECRET_ID}/versions/latest" try: logging.info(f"Accessing secret: {secret_version_name}") # Access the secret version response = secret_manager_client.access_secret_version(request={"name": secret_version_name}) secret_payload = response.payload.data.decode("UTF-8") # IMPORTANT: In a real application, you would process or use the secret # here, not return it directly in an HTTP response, especially if the # secret is sensitive. This example is for demonstration purposes only. return jsonify({"secret_id": SECRET_ID, "secret_value": secret_payload}) except Exception as e: logging.error(f"Failed to retrieve secret '{SECRET_ID}': {e}") return jsonify({"error": f"Failed to retrieve secret: {str(e)}"}), 500 if __name__ == '__main__': # When running locally, Flask will use the hardcoded values directly. # In Cloud Run, these values are used without needing environment variables. app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 8080))) Note:
    This is an example Python application to retrieve a secret.
  2. Create a requirements.txt

    Flask==3.* google-cloud-secret-manager==2.* Note:
    This `requirements.txt` file should list your application's Python dependencies.

Task 3. Build and Push the Application Container Image

Create a simple application (e.g., a basic web server) that utilizes the secret from Secret Manager. Build a Docker image for the application and push it to Artifact Registry.

  1. Create a Dockerfile for your application. This example assumes a simple Python Flask app. Ensure your application code is in the same directory as your Dockerfile.

    FROM python:3.9-slim-buster WORKDIR /app COPY requirements.txt . RUN pip3 install -r requirements.txt COPY . . CMD ["python3", "app.py"] Note:
    This is an example Dockerfile. Adjust it based on your application's needs. A `requirements.txt` file should list your application's Python dependencies.
  2. Initialize Artifact Registry as a Docker registry.

    gcloud artifacts repositories create arcade-images --repository-format=docker --location={{{ project_0.default_region | "REGION" }}} --description="Docker repository" Note:
    Creates an Artifact Registry repository to store Docker images. Choose a meaningful name for the repository.
  3. Build the Container image.

    docker build -t {{{ project_0.default_region | "REGION" }}}-docker.pkg.dev/{{{ project_0.project_id | "PROJECT_ID" }}}/arcade-images/arcade-secret:latest . Note:
    Builds a Docker image from the Dockerfile in the current directory. The tag includes the Artifact Registry path.
  4. Test the Container image.

    docker run --rm -p 8080:8080 {{{ project_0.default_region | "REGION" }}}-docker.pkg.dev/{{{ project_0.project_id | "PROJECT_ID" }}}/arcade-images/arcade-secret:latest
  5. Access the running container using the Cloudshell web preview on the port 8080.

    Note:
    Verify the Container image is working as specified.
  6. Stop the running container using ctrl-c.

  7. Push the Container image to Artifact Registry.

    docker push {{{ project_0.default_region | "REGION" }}}-docker.pkg.dev/{{{ project_0.project_id | "PROJECT_ID" }}}/arcade-images/arcade-secret:latest Note:
    Pushes the built Docker image to your Artifact Registry repository. Ensure you have Docker installed and configured.

Task 4. Deploy to Cloud Run with Secret Manager Integration

Deploy your application to Cloud Run and configure it to access the secret from Secret Manager.

  1. Create a Service Account for Secret Manager application.

    gcloud iam service-accounts create arcade-service \ --display-name="Arcade Service Account" \ --description="Service account for Cloud Run application" Note:
    This command creates a service account for the Cloud Run application.
  2. Grant the Cloud Run service account access to the Secret Manager secret.

    gcloud secrets add-iam-policy-binding arcade-secret \ --member="serviceAccount:arcade-service@{{{ project_0.project_id | "PROJECT_ID" }}}.iam.gserviceaccount.com" \ --role="roles/secretmanager.secretAccessor" Note:
    This command grants the Cloud Run service account permission to access the secret.
  3. Deploy the application to Cloud Run.

    gcloud run deploy arcade-service \ --image={{{ project_0.default_region | "REGION" }}}-docker.pkg.dev/{{{ project_0.project_id | "PROJECT_ID" }}}/arcade-images/arcade-secret:latest \ --region={{{ project_0.default_region | "REGION" }}} \ --set-secrets SECRET_ENV_VAR=arcade-secret:latest \ --service-account arcade-service@{{{ project_0.project_id | "PROJECT_ID" }}}.iam.gserviceaccount.com \ --allow-unauthenticated Note:
    This command deploys the Container image to Cloud Run. The `--set-secrets` flag injects the secret from Secret Manager into your application as an environment variable (`SECRET_ENV_VAR`). i

Task 5. Verify the Deployment

Access the deployed application and verify that it can successfully retrieve the secret from Secret Manager.

  1. Get the URL of your deployed Cloud Run service.

    gcloud run services describe arcade-service --region={{{ project_0.default_region | "REGION" }}} --format='value(status.url)' Note:
    This command retrieves the URL where your service is accessible.
  2. Access the URL in your browser or using curl and verify that the application can access the secret.

    curl $(gcloud run services describe arcade-service --region={{{ project_0.default_region | "REGION" }}} --format='value(status.url)') | jq Note:
    Verify that the application output includes the value of the secret you stored in Secret Manager. The exact output depends on how you implemented secret retrieval in your application.

Congratulations!

You have successfully developed and deployed a secure application on Cloud Run using Secret Manager to manage sensitive information. You learned how to create secrets, build a Docker image, push it to Artifact Registry, deploy to Cloud Run, and configure the application to access the secret at runtime. This approach enhances the security of your application by separating sensitive data from your codebase and configuration files.

Additional Resources

Manual Last Updated Jul 25, 2025

Lab Last Tested Jul 25, 2025

시작하기 전에

  1. 실습에서는 정해진 기간 동안 Google Cloud 프로젝트와 리소스를 만듭니다.
  2. 실습에는 시간 제한이 있으며 일시중지 기능이 없습니다. 실습을 종료하면 처음부터 다시 시작해야 합니다.
  3. 화면 왼쪽 상단에서 실습 시작을 클릭하여 시작합니다.

시크릿 브라우징 사용

  1. 실습에 입력한 사용자 이름비밀번호를 복사합니다.
  2. 비공개 모드에서 콘솔 열기를 클릭합니다.

콘솔에 로그인

    실습 사용자 인증 정보를 사용하여
  1. 로그인합니다. 다른 사용자 인증 정보를 사용하면 오류가 발생하거나 요금이 부과될 수 있습니다.
  2. 약관에 동의하고 리소스 복구 페이지를 건너뜁니다.
  3. 실습을 완료했거나 다시 시작하려고 하는 경우가 아니면 실습 종료를 클릭하지 마세요. 이 버튼을 클릭하면 작업 내용이 지워지고 프로젝트가 삭제됩니다.

현재 이 콘텐츠를 이용할 수 없습니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.

감사합니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.

한 번에 실습 1개만 가능

모든 기존 실습을 종료하고 이 실습을 시작할지 확인하세요.

시크릿 브라우징을 사용하여 실습 실행하기

이 실습을 실행하려면 시크릿 모드 또는 시크릿 브라우저 창을 사용하세요. 개인 계정과 학생 계정 간의 충돌로 개인 계정에 추가 요금이 발생하는 일을 방지해 줍니다.