이 페이지에서는 Python 애플리케이션을 빌드 및 테스트하고, 아티팩트를 Artifact Registry에 업로드하고, 출처 정보를 생성하고, Cloud Storage에서 테스트 로그를 저장하는 방법을 설명합니다.
Cloud Build를 사용하면 공개적으로 사용 가능한 컨테이너 이미지를 사용하여 작업을 실행할 수 있습니다. Docker Hub의 공개 python 이미지는 python 및 pip 도구가 사전 설치된 상태로 제공됩니다. 종속 항목을 설치하기 위해 이러한 도구를 사용하도록 Cloud Build를 구성하고, 이러한 도구를 사용해서 단위 테스트를 빌드 및 실행할 수 있습니다.
시작하기 전에
이 페이지 안내에서는 사용자가 Python에 익숙하다고 가정합니다. 또한 다음 사항도 적용됩니다.
Enable the Cloud Build, Artifact Registry, and Cloud Storage APIs.
설치 요구사항: Docker Hub의 python 이미지는 pip가 사전 설치된 상태로 제공됩니다. pip에서 종속 항목을 설치하려면 다음 필드가 포함된 빌드 단계를 추가합니다.
name: 이 태스크에 대해 Docker Hub에서 Python 이미지를 사용하도록 이 필드의 값을 python 또는 python:<tag>로 설정합니다. 다른 Python 이미지에 사용할 수 있는 태그 목록을 보려면 Python 이미지에 대한 Docker Hub 참조를 참고하세요.
entrypoint: 이 필드를 설정하면 name에 참조된 이미지의 기본 진입점이 재정의됩니다. 빌드 단계의 진입점으로 pip를 호출하도록 이 필드의 값을 pip로 설정하고 pip 명령어를 실행합니다.
args: 빌드 단계의 args 필드는 인수 목록을 가져와서 name 필드로 참조되는 이미지에 전달합니다. 이 필드에서 pip install 명령어를 실행하도록 인수를 전달합니다. pip install 명령어의 --user 플래그는 후속 빌드 단계가 이 빌드 단계에서 설치된 모듈에 액세스할 수 있도록 합니다.
Cloud Storage에 테스트 로그 저장: 기존 버킷 위치 및 테스트 로그 경로를 지정하여 Cloud Storage에 테스트 로그를 저장하도록 Cloud Build를 구성할 수 있습니다.
다음 빌드 단계는 JUNIT XML 파일에 저장한 테스트 로그를 Cloud Storage 버킷에 저장합니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[[["\u003cp\u003eCloud Build can be configured to build and test Python applications using the publicly available \u003ccode\u003epython\u003c/code\u003e Docker image, which includes pre-installed \u003ccode\u003epython\u003c/code\u003e and \u003ccode\u003epip\u003c/code\u003e tools.\u003c/p\u003e\n"],["\u003cp\u003eYou can use Cloud Build to install Python dependencies, run unit tests with frameworks like \u003ccode\u003epytest\u003c/code\u003e, and save the test logs to a JUNIT XML file.\u003c/p\u003e\n"],["\u003cp\u003eCloud Build allows you to upload your built Python artifacts to Artifact Registry by specifying the repository details in your build configuration file, and you can specify where to save the built artifacts.\u003c/p\u003e\n"],["\u003cp\u003eYou can optionally enable verifiable build provenance metadata using Supply chain Levels for Software Artifacts (SLSA) by adding \u003ccode\u003erequestedVerifyOption: VERIFIED\u003c/code\u003e to your build configuration file.\u003c/p\u003e\n"],["\u003cp\u003eYou can save any test logs to a Cloud Storage bucket by specifying a bucket location and the paths to the log files in your build configuration.\u003c/p\u003e\n"]]],[],null,["# Build and test Python applications\n\nThis page describes how to configure Cloud Build to build and test your Python applications, upload your artifacts to Artifact Registry, generate provenance information, and save your test logs in Cloud Storage.\n\nCloud Build enables you to use any publicly available container image\nto execute your tasks. The public\n[`python` image from Docker Hub](https://hub.docker.com/_/python/)\ncomes preinstalled with `python` and `pip` tools. You can configure Cloud Build\nuse these tools to install dependencies, build, and run unit tests using these tools.\n\nBefore you begin\n----------------\n\nThe instructions on this page assume that you are familiar with Python. In addition:\n\n-\n\n\n Enable the Cloud Build, Artifact Registry, and Cloud Storage APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudbuild.googleapis.com,artifactregistry.googleapis.com,storage.googleapis.com&redirect=https://cloud.google.com/build/docs/building/build-python)\n- To run the `gcloud` commands on this page, install [Google Cloud CLI](/sdk).\n- Have your Python project handy.\n- Have a Python repository in Artifact Registry. If you don't have one, then [create a new repository](/artifact-registry/docs/repositories/create-repos).\n- If you want to store test logs in Cloud Storage, [create a bucket in Cloud Storage](/storage/docs/creating-buckets).\n\n### Required IAM permissions\n\n- To store test logs in Logging, grant the\n [Storage Object Creator (`roles/storage.objectCreator`)](/iam/docs/understanding-roles#storage-roles)\n role for the Cloud Storage bucket to your build service account.\n\n- To store built images in Artifact Registry, grant the [Artifact Registry Writer\n (`roles/artifactregistry.writer`) role](/artifact-registry/docs/access-control#grant)\n to the your build service account.\n\nFor instructions on granting these roles see\n[Granting a role using the IAM page](/build/docs/securing-builds/configure-access-for-cloud-build-service-account#granting_a_role_using_the_iam_page).\n\nConfiguring Python builds\n-------------------------\n\nThis section walks through an example build config file for a Python app. It has\nbuild steps to manage installation requirements, add unit tests, and after the tests pass, to build and deploy the app.\n\n1. In your project root directory, create [Cloud Build config file](/build/docs/build-config)\n named `cloudbuild.yaml`.\n\n2. **Install requirements** : The `python` image from Docker Hub comes preinstalled\n with `pip`. To install dependencies from `pip`, add a build step with the\n following fields:\n\n - `name`: Set the value of this field to `python` or `python:\u003ctag\u003e` to use the python image from Docker Hub for this task. To see a list of available tags for other Python images, see the [Docker Hub reference for the python image](https://hub.docker.com/_/python/tags).\n - `entrypoint`: Setting this field overrides the default entrypoint of the image referenced in `name`. Set the value of this field to `pip` to invoke `pip` as the entrypoint of the build step and run `pip` commands.\n - `args`: The `args` field of a build step takes a list of arguments and passes them to the image referenced by the `name` field. Pass the arguments to run the `pip install` command in this field. `--user` flag in the `pip install` command ensures that the subsequent build steps can access the modules installed in this build step.\n\n The following build step adds arguments to install requirements: \n\n steps:\n - name: 'python'\n entrypoint: 'python'\n args: ['-m', 'pip', 'install', '--upgrade', 'pip']\n - name: python\n entrypoint: python\n args: ['-m', 'pip', 'install', 'build', 'pytest', 'Flask', '--user']\n\n3. **Add unit tests** : If you've defined unit tests in your application using a\n testing framework such as `pytest`, you can configure Cloud Build\n to run the tests by adding the following fields in a build step:\n\n - `name`: Set the value of this field to `python` to use the python image from Docker Hub for your task.\n - `entrypoint`: Set the value of this field to `python` to run `python` commands.\n - `args`: Add the arguments for running the `python pytest` command.\n\n The following build step saves the `pytest` log output to a JUNIT XML file.\n The name of this file is constructed using `$SHORT_SHA`, [the short version of the commit ID associated\n with your build](/build/docs/configuring-builds/substitute-variable-values#using_default_substitutions).\n A subsequent build step will save the logs in this file to Cloud Storage. \n\n - name: 'python'\n entrypoint: 'python'\n args: ['-m', 'pytest', '--junitxml=${SHORT_SHA}_test_log.xml']\n\n4. **Build** : In your build config file, define the builder and the `args` to build your application:\n\n - `name`: Set the value of this field to `python` to use the python image from Docker Hub for your task.\n - `entrypoint`: Set the value of this field to `python` to run `python` commands.\n - `args`: Add the arguments for executing your build.\n\n The following build step starts the build: \n\n - name: 'python'\n entrypoint: 'python'\n args: ['-m', 'build']\n\n5. **Upload to Artifact Registry**:\n\n In your config file, add the `pythonPackages` field and specify your Python repository in Artifact Registry: \n\n artifacts:\n pythonPackages:\n - repository: 'https://\u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e-python.pkg.dev/\u003cvar translate=\"no\"\u003ePROJECT-ID\u003c/var\u003e/\u003cvar translate=\"no\"\u003eREPOSITORY\u003c/var\u003e'\n paths: ['dist/*']\n\n Replace the following values:\n - \u003cvar translate=\"no\"\u003ePROJECT-ID\u003c/var\u003e is the ID of the Google Cloud project that contains your Artifact Registry repository.\n - \u003cvar translate=\"no\"\u003eREPOSITORY\u003c/var\u003e is the ID of the repository.\n - \u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e is the regional or multi-regional [location](/artifact-registry/docs/repo-locations) for the repository.\n6. **Optional: Enable provenance generation**\n\n Cloud Build can generate verifiable\n [Supply chain Levels for Software Artifacts (SLSA)](https://slsa.dev/) build\n provenance metadata to help secure your continuous integration pipeline.\n\n To enable provenance generation, add\n [`requestedVerifyOption: VERIFIED`](/build/docs/build-config-file-schema#options)\n to the `options` section in your config file.\n7. **Save test logs to Cloud Storage**: You can configure Cloud Build\n to store any test logs in Cloud Storage by specifying an existing bucket\n location and path to the test logs.\n The following build step stores the test logs that you saved in the JUNIT XML\n file to a Cloud Storage bucket:\n\n artifacts:\n objects:\n location: 'gs://${_BUCKET_NAME}/'\n paths:\n - '${SHORT_SHA}_test_log.xml'\n\n8. **Start your build** : [manually](/build/docs/running-builds/start-build-manually) or\n [using build triggers](/build/docs/automating-builds/create-manage-triggers).\n\n Once your build completes, you can [view repository details](/artifact-registry/docs/repositories/list-repos)\n in Artifact Registry.\n\n You can also [view build provenance metadata](/build/docs/securing-builds/generate-validate-build-provenance#view) and [validate provenance](/build/docs/securing-builds/generate-validate-build-provenance#validate_provenance).\n\nWhat's next\n-----------\n\n- Learn how to [view build results](/build/docs/view-build-results).\n- Learn how to [safeguard builds](/software-supply-chain-security/docs/safeguard-builds).\n- Learn how to [build and containerize Python applications](/build/docs/building/build-containerize-python).\n- Learn how to [use private dependencies](/artifact-registry/docs/configure-cloud-build#python).\n- Learn how to [perform blue/green deployments on Compute Engine](/build/docs/deploying-builds/deploy-compute-engine).\n- Learn how to [troubleshoot build errors](/build/docs/troubleshooting)."]]