Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nesta página, descrevemos como configurar o Cloud Build para criar e testar aplicativos Python, fazer upload de artefatos para o Artifact Registry, gerar informações de procedência e salvar os registros de teste no Cloud Storage.
O Cloud Build permite que você use qualquer imagem de contêiner disponível publicamente para executar suas tarefas. A imagem pública python do Docker Hub vem com as ferramentas python e pip pré-instaladas. É possível configurar o Cloud Build para usar essas ferramentas para instalar dependências, criar e executar testes de unidade usando essas ferramentas.
Antes de começar
Nas instruções desta página, pressupomos que você está familiarizado com o Python. Além disso:
Enable the Cloud Build, Artifact Registry, and Cloud Storage APIs.
Nesta seção, você vai conferir um exemplo de arquivo de configuração de build para um app Python. Ele tem etapas de build para gerenciar requisitos de instalação, adicionar testes de unidade e, depois que os testes forem aprovados, criar e implantar o app.
Requisitos de instalação: a imagem python do Docker Hub vem pré-instalada com pip. Para instalar dependências de pip, adicione uma etapa de versão com os
seguintes campos:
name: defina o valor desse campo como python ou python:<tag> para usar a imagem Python do Docker Hub nesta tarefa. Para conferir uma lista de tags disponíveis para outras imagens do Python, consulte a referência do Docker Hub para a imagem do Python.
entrypoint: a definição desse campo substitui o ponto de entrada padrão da imagem referenciada em name. Defina o valor desse campo como pip para invocar pip como o entrypoint da etapa de versão e execute comandos pip.
args: o campo args de uma etapa de criação recebe uma
lista de argumentos e os passa para a imagem referenciada pelo campo name. Transmita os argumentos
para executar o comando pip install nesse campo. A sinalização --user no comando pip install garante que as etapas subsequentes de versão possam acessar os módulos instalados nesta etapa de versão.
A etapa de criação a seguir adiciona argumentos para instalar requisitos:
Adicionar testes de unidade: se você definiu testes de unidade no aplicativo usando um
framework de teste, como pytest, configure o Cloud Build
para executar os testes adicionando os campos a seguir em uma etapa do build:
name: defina o valor desse campo como python para usar a imagem Python
do Docker Hub na tarefa.
entrypoint: defina o valor desse campo como python para executar comandos python.
args: adicione os argumentos para executar o comando python pytest.
A etapa de criação a seguir salva a saída do registro pytest em um arquivo XML JUNIT.
O nome desse arquivo é construído usando $SHORT_SHA, a versão curta do ID de confirmação associada
ao seu build.
Uma próxima etapa de versão salvará os registros nesse arquivo no Cloud Storage.
Salvar registros de teste no Cloud Storage: é possível configurar o Cloud Build para armazenar todos os registros de teste no Cloud Storage especificando um local e um caminho do bucket existente para os registros de teste.
A etapa de criação a seguir armazena os registros de teste que você salvou no arquivo XML JUNIT em um bucket do Cloud Storage:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 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)."]]