Utilizzare l'editor di Cloud Shell come ambiente per creare il servizio e il secret con Cloud Run. L'editor viene caricato preventivamente con gli strumenti necessari per lo sviluppo cloud.
Per creare il tuo servizio:
Nella barra di stato di Cloud Code, fai clic sul nome del progetto attivo.
Nel menu Quick Pick visualizzato, seleziona Nuova applicazione e poi fai clic su Applicazione Cloud Run.
Dall'elenco degli esempi Cloud Run, seleziona Python (Flask): Cloud Run.
Seleziona una cartella per l'esempio e fai clic su Crea nuova applicazione.
Dopo che Cloud Shell Editor ha caricato il servizio in un nuovo workspace, visualizza i relativi file nella vista Explorer.
Crea un secret
Secret Manager ti consente di
archiviare e gestire secret, come blob binari o stringhe di testo, e di accedervi in sicurezza.
Inoltre, gestisce i tuoi secret, il che significa che non devi gestire
macchine virtuali o servizi operativi.
Per creare un secret con l'integrazione di Secret Manager con Cloud Code:
Fai clic su
Secret
Manager e attendi il caricamento.
Se viene richiesto di autorizzare Cloud Shell a effettuare chiamate API Google Cloud, fai clic su Autorizza.
Fai clic su AggiungiCrea
secret.
Se richiesto, seleziona il progetto Google Cloud dal selettore a discesa.
Se richiesto, abilita l'API Secret Manager.
Nella scheda Secret Manager - Crea secret visualizzata, inserisci quanto segue nel campo Nome:
my-secret
Nel campo Valore secret, inserisci:
Hello secret!
Fai clic su Crea secret. Verrà visualizzato un messaggio che indica che il secret è stato creato correttamente.
Aggiungi un secret al codice
I secret sono utili per l'archiviazione di informazioni relative alla configurazione, come database
password, chiavi API o certificati TLS richiesti da un'applicazione in fase di runtime.
Per aggiungere un secret al codice:
Apri la vista
API
Cloud e seleziona
API Secret Manager.
Viene visualizzata una scheda Dettagli API Google Cloud con API Secret Manager come orientamento.
Nella sezione Installa libreria client, fai clic sulla scheda Python e
su play_arrowEsegui nel terminale.
Questa operazione installa la libreria client google-cloud-secret-manager.
Apri
requirements.txt
e aggiungi la seguente riga in fondo al file:
google-cloud-secret-manager==VERSION_NUMBER
Puoi trovare il numero di versione nella console dopo aver eseguito l'installazione nel passaggio precedente. Ad esempio, la console potrebbe mostrare:
Successfully installed google-cloud-secret-manager-2.23.1
Le tue modifiche vengono salvate automaticamente.
Per ottenere il valore più recente del secret, apri
app.py
, copia e incolla la seguente funzione:
dopo la funzione hello:
defaccess_secret_version(secret_version_id):"""Return the value of a secret's version"""fromgoogle.cloudimportsecretmanager# Create the Secret Manager client.client=secretmanager.SecretManagerServiceClient()# Access the secret version.response=client.access_secret_version(name=secret_version_id)# Return the decoded payload.returnresponse.payload.data.decode('UTF-8')
Per chiamare la funzione access_secret_version, sostituisci la
variabile messaggio
con quanto segue:
Se la scheda Secret Manager - Crea secret è ancora aperta,
file_copyCopia l'ID.
Per ottenere l'ID di una versione del secret in qualsiasi momento, vai a
Secret
Manager > [SECRET_NAME] > Versioni, mantieni il
puntatore sopra la versione e fai clic su
Copia ID risorsa.
Per aggiungere l'ID versione, sostituisci il segnaposto
<SECRET_VERSION_ID>
con l'ID versione copiato.
Esegui nell'emulatore Cloud Run
Per testare il nuovo secret, esegui il servizio Cloud Run localmente nell'emulatore Cloud Run.
Avvia il menu Cloud Code dalla barra di stato.
Per creare il tuo servizio ed eseguirne il deployment nell'emulatore, seleziona
Esegui
nell'emulatore Cloud Run.
Nella scheda Esegui/Esegui il debug nell'emulatore di Cloud Run visualizzata, fai clic su
Esegui.
Quando esegui la configurazione per la prima volta, il processo può richiedere
fino a 5 minuti. Il riquadro
Output
mostra lo stato di avanzamento della creazione e del deployment della tua app.
Dopo aver creato l'app, avviala facendo clic sul link localhost visualizzato nel riquadro
Output. Il valore del segreto viene visualizzato sotto l'immagine di successo.
Visualizza e crea una nuova versione del secret
La visualizzazione Secret Manager di Cloud Code ti consente di dare un'occhiata rapida ai secret del tuo progetto, con le azioni per gestirli.
Visualizzazione del valore di una versione del secret
Fai clic sulla visualizzazione
Secret
Manager.
Espandi il secret facendoci clic sopra.
Nella cartella Versioni, fai clic con il pulsante destro del mouse sulla versione numerata che ti interessa.
per visualizzare il valore, poi seleziona Mostra valore versione.
Tieni presente che non puoi modificare una versione del secret. Per aggiornare il valore di un secret, devi creare una nuova versione.
Crea una nuova versione del secret
Il valore di un secret è archiviato in una versione del secret. Un secret può avere molte versioni. Questa operazione è utile in situazioni in cui un secret cambia. Se aggiorni un secret con una nuova versione, non devi aggiornare il codice.
Fai clic sulla visualizzazione
Secret
Manager.
Fai clic con il tasto destro del mouse sul nome del secret e seleziona Crea versione del secret.
Nella scheda Secret Manager - Crea versione visualizzata, inserisci un nuovo valore e fai clic su Crea versione.
Dopo aver aperto la scheda Secret Manager - Crea secret, fai clic su
file_copyCopia per copiare l'ID.
Per aggiungere l'ID versione più recente, sostituisci la versione attuale visualizzata nella variabile messaggio in
app.py
con l'ID versione più recente che hai copiato.
Se vuoi che il codice utilizzi sempre l'ultima versione,
sostituisci il numero di versione alla fine dell'ID versione con
latest.
Visualizza e gestisci i secret
Disattiva una versione del secret
Le versioni dei secret vengono attivate per impostazione predefinita dopo la creazione, il che significa che vi si può accedere. Un secret disattivato è inaccessibile, ma puoi sempre ripristinarne l'accesso in qualsiasi momento.
Per disabilitare una versione del secret:
Fai clic su Cloud Code ed espandi la sezione Secret Manager.
Espandi il secret facendoci clic sopra.
Nella cartella Versioni, fai clic con il tasto destro del mouse sulla versione numerata che vuoi
disattivare.
Seleziona Disattiva versione.
Elimina una versione del secret
Quando elimini una versione del secret, non è possibile accedervi. L'eliminazione di una versione del secret è definitiva.
Fai clic su Cloud Code ed espandi la sezione Secret Manager.
Espandi il secret facendoci clic sopra.
Nella cartella Versioni, fai clic con il tasto destro del mouse sulla versione da eliminare.
Seleziona Elimina versione.
Pulizia
Per eliminare solo il cluster che hai creato per questa guida rapida:
Fai clic su Cloud Code ed espandi la sezione Kubernetes.
Tieni il puntatore sopra il nome del cluster e poi fai clic su
open_in_newApri nella console Google Cloud .
Fai clic su Elimina e quindi su Elimina.
Per eliminare il progetto (e le risorse associate, inclusi eventuali cluster):
Vai alla pagina Progetti nella console Google Cloud :
[[["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\u003eThis guide explains how to use Cloud Code's Secret Manager integration to create, store, and manage secrets within your Google Cloud project.\u003c/p\u003e\n"],["\u003cp\u003eYou will learn how to create a secret, add it to your application code, and access its value at runtime using the Secret Manager API.\u003c/p\u003e\n"],["\u003cp\u003eThe guide demonstrates how to use the Cloud Run emulator to test your application locally after adding the secret, ensuring your secret is accessed correctly.\u003c/p\u003e\n"],["\u003cp\u003eYou can manage different versions of a secret, view their values, and disable or destroy specific secret versions as needed, allowing you to update your secrets without changing your code.\u003c/p\u003e\n"],["\u003cp\u003eInstructions are included on how to clean up resources by deleting either the cluster or the entire project created for this process, once you are done with the tutorial.\u003c/p\u003e\n"]]],[],null,["Learn how to create and manage secrets using Cloud Code's Secret Manager\nintegration.\n\n*** ** * ** ***\n\nTo follow step-by-step guidance for this task directly in the\nCloud Shell Editor, click **Guide me**:\n\n[Guide me](https://console.cloud.google.com/?walkthrough_id=shell--secret_manager_cloud_code_create_secret)\n\n*** ** * ** ***\n\nBefore you begin\n\n1. In the Google Cloud console, go to the project selector page.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n2. Select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\nCreate your Cloud Run service\n3. Use Cloud Shell Editor as your environment for creating your Cloud Run service and secret. The editor comes preloaded with the tools needed for cloud development.\n4. To create your service:\n 1. In the Cloud Code status bar, click the active project name.\n\n 2. In the Quick Pick menu that appears, select click **New Application** , and\n then click **Cloud Run Application**.\n\n 3. From the list of Cloud Run samples, select **Python (Flask): Cloud Run**.\n\n 4. Select a folder for your sample and then click **Create New Application**.\n\n5. After Cloud Shell Editor loads your service in a new workspace, view its files in the explorer view.\n\nCreate a secret\n6. [Secret Manager](https://cloud.google.com/secret-manager/) allows you to securely store, manage, and access secrets as binary blobs or text strings. Additionally, it manages your secrets, meaning you don't have to deal with virtual machines or operating services.\n7. To create a secret with Cloud Code's Secret Manager integration:\n 1. Click Secret Manager and give it a moment to load.\n 2. If prompted to authorize Cloud Shell to make Google Cloud API calls, click **Authorize**.\n 3. Click add Create Secret.\n 4. If prompted, select your Google Cloud project from the dropdown selector.\n 5. If prompted, enable the Secret Manager API.\n 6. In the **Secret Manager - Create Secret** tab that appears, enter the\n following in the **Name** field:\n\n my-secret\n\n 7. In the **Secret Value** field, enter:\n\n Hello secret!\n\n 8. Click **Create Secret** and a message that your secret was successfully\n created appears.\n\nAdd a secret to your code\n8. Secrets are great for storing configuration information such as database passwords, API keys, or TLS certificates needed by an application at runtime.\n9. To add a secret to your code:\n 1. Open the\n Cloud API view and select the\n Secret Manager API.\n\n This opens a Google Cloud API Detail tab with **Secret Manager API** as the\n heading.\n 2. In the **Install Client Library** section, click the **Python** tab and\n click play_arrow **Run in terminal** .\n This installs the `google-cloud-secret-manager` client library.\n\n 3. Open\n requirements.txt\n and add the following line to the bottom of the file:\n\n google-cloud-secret-manager==\u003cvar translate=\"no\"\u003eVERSION_NUMBER\u003c/var\u003e\n\n You can find the version number in the console after you run the\n installation in the previous step. For example, the console might show:\n `Successfully installed google-cloud-secret-manager-2.23.1`\n\n Your changes are automatically saved.\n 4. To get the latest value of your secret, open\n app.py\n and copy and paste the following function:\n after the hello function:\n\n def access_secret_version(secret_version_id):\n \"\"\"Return the value of a secret's version\"\"\"\n from google.cloud import secretmanager\n\n # Create the Secret Manager client.\n client = secretmanager.https://cloud.google.com/python/docs/reference/secretmanager/latest/google.cloud.secretmanager_v1.services.secret_manager_service.SecretManagerServiceClient.html()\n\n # Access the secret version.\n response = client.https://cloud.google.com/python/docs/reference/secretmanager/latest/google.cloud.secretmanager_v1.services.secret_manager_service.SecretManagerServiceClient.html#google_cloud_secretmanager_v1_services_secret_manager_service_SecretManagerServiceClient_access_secret_version(name=secret_version_id)\n\n # Return the decoded payload.\n return response.payload.data.decode('UTF-8')\n\n 5. To call the `access_secret_version` function, replace the\n message variable\n with the following:\n\n message = access_secret_version(\"\u003cSECRET_VERSION_ID\u003e\")\n\n 6. If you still have the **Secret Manager - Create Secret** tab open,\n file_copy **Copy** the ID.\n\n To get the ID of a secret version at any time, navigate to\n Secret Manager \\\u003e \\[SECRET_NAME\\] \\\u003e Versions, hold the\n pointer over over your version, and click\n\n **Copy resource ID**.\n 7. To add the version ID, replace the placeholder\n `\u003cSECRET_VERSION_ID\u003e`\n with your copied version ID.\n\nRun on Cloud Run emulator\n10. To test your new secret, run your Cloud Run service locally on the Cloud Run emulator.\n 1. Launch the Cloud Code menu from the status bar.\n 2. To build and deploy your service to the emulator, select **Run\n on Cloud Run Emulator**.\n 3. In the Run/Debug on Cloud Run Emulator tab that appears, click **Run**.\n 4. When running the configuration for the first time, this process can take up\n to 5 minutes. The\n **Output**\n panel displays the progress as your app is built and deployed.\n\n 5. After your app is built, launch your app by clicking the localhost link that\n appears in your\n **Output**\n panel. Your secret's value is displayed under the success graphic.\n\nView and create a new secret version\n11. Cloud Code's Secret Manager view gives you a quick look at your project's secrets, with actions for managing them.\n\nViewing the value of a secret version\n 1. Click the Secret Manager view.\n 2. Expand your secret by clicking on it.\n 3. In the **Versions** folder, right-click the numbered version that you want to view the value of and select **Show Version Value**.\n12. Note that you can't edit a secret version. To update a secret's value, you must create a new *version*.\n\nCreate a new secret version\n13. The value of a secret is stored in a secret version. A secret can have many versions. This is helpful in situations where a secret changes. Updating a secret with a new version means you don't have to update your code.\n 1. Click the Secret Manager view.\n 2. Right-click your secret's name and select **Create Secret Version**.\n 3. In the **Secret Manager - Create Version** tab that appears, enter a new value and click **Create Version**.\n 4. After the **Secret Manager - Create Secret** tab opens, click file_copy **Copy** top copy the ID.\n 5. To add the newer version ID, replace the current version that appears the message variable in app.py with the newer version ID that you copied.\n14. If you always want your code to use the latest version, replace the version number at the end of your version ID with `latest`.\n\nView and manage secrets\n\nDisable a secret version\n15. Secret versions are enabled by default after creation, meaning they can be accessed. A disabled secret is inaccessible, but you can always restore access to it at any time.\n16. To disable a secret version:\n 1. Click **Cloud Code** and then expand the **Secret Manager** section.\n 2. Expand your secret by clicking on it.\n 3. Under the **Versions** folder, right-click the numbered version you want to disable.\n 4. Select **Disable Version**.\n\nDestroy a secret version\n17. When you destroy a secret version, it can't be accessed. Destroying a secret version is permanent.\n 1. Click **Cloud Code** and then expand the **Secret Manager** section.\n 2. Expand your secret by clicking on it.\n 3. Under the **Versions** folder, right-click the version you want to destroy.\n 4. Select **Destroy Version**.\n\nCleaning up\n18. To delete just the cluster you created for this quickstart:\n 1. Click **Cloud Code** and then expand the **Kubernetes** section.\n 2. Hold the pointer over your cluster name and then click open_in_new **Open in Google Cloud console**.\n 3. Click **Delete** and then click **Delete**.\n19. To delete your project (and associated resources, including any clusters):\n 1. Go to the Projects page in the Google Cloud console:\n\n [Go to the Projects page](https://console.cloud.google.com/project)\n 2. Select the project that you created for this quickstart and then click\n **Delete**.\n\n 3. Type the project ID to confirm and then click **Shut down**.\n\n This shuts down the project and schedules it for deletion."]]