Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Questa pagina descrive come configurare Cloud Build per creare e testare le applicazioni Python, caricare gli artefatti in Artifact Registry, generare informazioni sulla provenienza e salvare i log di test in Cloud Storage.
Cloud Build ti consente di utilizzare qualsiasi immagine container disponibile pubblicamente
per eseguire le tue attività. L'immagine pubblica
python da Docker Hub
viene preinstallata con gli strumenti python e pip. Puoi configurare Cloud Build
per utilizzare questi strumenti per installare le dipendenze, eseguire la build ed eseguire test delle unità.
Prima di iniziare
Le istruzioni riportate in questa pagina presuppongono che tu abbia familiarità con Python. Inoltre:
Enable the Cloud Build, Artifact Registry, and Cloud Storage APIs.
Questa sezione illustra un file di configurazione della build di esempio per un'app Python. Contiene
passaggi di build per gestire i requisiti di installazione, aggiungere test delle unità e, dopo il superamento dei test, per creare e implementare l'app.
Installa i requisiti: l'immagine python di Docker Hub è preinstallata
con pip. Per installare le dipendenze da pip, aggiungi un passaggio di build con i seguenti campi:
name: imposta il valore di questo campo su python o python:<tag> per utilizzare l'immagine Python di Docker Hub per questa attività. Per visualizzare un elenco dei tag disponibili
per altre immagini Python, consulta la documentazione di riferimento di Docker Hub per l'immagine Python.
entrypoint: l'impostazione di questo campo sostituisce il punto di ingresso predefinito dell'immagine
a cui viene fatto riferimento in name. Imposta il valore di questo campo su pip per richiamare pip
come punto di ingresso del passaggio di build ed esegui i comandi pip.
args: il campo args di un passaggio di build accetta un elenco di argomenti e
li passa all'immagine a cui fa riferimento il campo name. Inserisci gli argomenti
per eseguire il comando pip install in questo campo. Il flag --user nel comando pip install
garantisce che i passaggi di compilazione successivi possano accedere ai moduli
installati in questo passaggio di compilazione.
Il seguente passaggio di build aggiunge argomenti per installare i requisiti:
Aggiungi test delle unità: se hai definito test delle unità nella tua applicazione utilizzando un framework di test come pytest, puoi configurare Cloud Build per eseguire i test aggiungendo i seguenti campi in un passaggio di build:
name: imposta il valore di questo campo su python per utilizzare l'immagine Python da
Docker Hub per l'attività.
entrypoint: imposta il valore di questo campo su python per eseguire i comandi python.
args: aggiungi gli argomenti per l'esecuzione del comando python pytest.
Il seguente passaggio di build salva l'output del log pytest in un file XML JUNIT.
Il nome di questo file viene creato utilizzando $SHORT_SHA, la versione breve dell'ID commit associato
alla build.
Un passaggio di build successivo salverà i log in questo file in Cloud Storage.
Per attivare la generazione della provenienza, aggiungi
requestedVerifyOption: VERIFIED
alla sezione options del file di configurazione.
Salva i log di test in Cloud Storage: puoi configurare Cloud Build
in modo da archiviare tutti i log di test in Cloud Storage specificando un percorso e una posizione del bucket esistenti per i log di test.
Il seguente passaggio di build archivia i log dei test salvati nel file XML JUNIT in un bucket Cloud Storage:
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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)."]]