Organízate con las colecciones
Guarda y clasifica el contenido según tus preferencias.
En esta página se describe cómo configurar Cloud Build para compilar y probar tus aplicaciones Python, subir tus artefactos a Artifact Registry, generar información de procedencia y guardar tus registros de pruebas en Cloud Storage.
Cloud Build te permite usar cualquier imagen de contenedor disponible públicamente para ejecutar tus tareas. La imagen pública python de Docker Hub viene con las herramientas python y pip preinstaladas. Puedes configurar Cloud Build para usar estas herramientas con el fin de instalar dependencias, compilar y ejecutar pruebas unitarias.
Antes de empezar
En las instrucciones de esta página se presupone que tienes conocimientos de Python. Además, también ocurre lo siguiente:
Enable the Cloud Build, Artifact Registry, and Cloud Storage APIs.
En esta sección se explica un archivo de configuración de compilación de ejemplo para una aplicación de Python. Incluye pasos de compilación para gestionar los requisitos de instalación, añadir pruebas unitarias y, una vez superadas las pruebas, compilar y desplegar la aplicación.
Instala los requisitos: la imagen python de Docker Hub viene con pip preinstalado. Para instalar las dependencias de pip, añade un paso de compilación con los siguientes campos:
name: asigna el valor python o python:<tag> a este campo para usar la imagen de Python de Docker Hub en esta tarea. Para ver una lista de las etiquetas disponibles de otras imágenes de Python, consulta la referencia de Docker Hub para la imagen de Python.
entrypoint: al definir este campo, se anula el punto de entrada predeterminado de la imagen a la que se hace referencia en name. Asigna el valor pip a este campo para invocar pip
como punto de entrada del paso de compilación y ejecuta los comandos pip.
args: el campo args de un paso de compilación toma una lista de argumentos y los transfiere a la imagen a la que hace referencia el campo name. Introduce los argumentos
para ejecutar el comando pip install en este campo. La marca --user del comando pip install
asegura que los pasos de compilación posteriores puedan acceder a los módulos
instalados en este paso de compilación.
El siguiente paso de compilación añade argumentos para instalar los requisitos:
Añadir pruebas unitarias: si has definido pruebas unitarias en tu aplicación mediante un framework de pruebas como pytest, puedes configurar Cloud Build para que ejecute las pruebas añadiendo los siguientes campos en un paso de compilación:
name: asigna el valor python a este campo para usar la imagen de Python de Docker Hub en tu tarea.
entrypoint: asigna el valor python a este campo para ejecutar comandos python.
args: añade los argumentos para ejecutar el comando python pytest.
El siguiente paso de compilación guarda la salida del registro pytest en un archivo XML de JUNIT.
El nombre de este archivo se crea con $SHORT_SHA, la versión corta del ID de la confirmación asociada a tu compilación.
En un paso de compilación posterior, se guardarán los registros de este archivo en Cloud Storage.
Para habilitar la generación de procedencia, añade
requestedVerifyOption: VERIFIED
a la sección options de tu archivo de configuración.
Guardar registros de pruebas en Cloud Storage: puedes configurar Cloud Build para que almacene los registros de pruebas en Cloud Storage. Para ello, especifica la ubicación de un segmento y la ruta de los registros de pruebas.
El siguiente paso de compilación almacena los registros de prueba que has guardado en el archivo XML de JUNIT en un segmento de Cloud Storage:
[[["Es fácil de entender","easyToUnderstand","thumb-up"],["Me ofreció una solución al problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Es difícil de entender","hardToUnderstand","thumb-down"],["La información o el código de muestra no son correctos","incorrectInformationOrSampleCode","thumb-down"],["Me faltan las muestras o la información que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-21 (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)."]]