Utilizza i secret di Secret Manager

Questa pagina spiega come includere informazioni sensibili come password e chiavi API in Cloud Build.

Secret Manager è un servizio Google Cloud che archivia in modo sicuro chiavi API, password e altri dati sensibili. Per includere informazioni sensibili nelle tue build, puoi archiviare le informazioni in Secret Manager e poi configurare la build per accedere alle informazioni da Secret Manager.

Prima di iniziare

  • Abilita le API Cloud Build and Secret Manager.

    Abilita le API

  • Per utilizzare gli esempi a riga di comando in questa guida, installa e configura Google Cloud CLI.

  • Assicurati di aver archiviato il secret in Secret Manager. Per le istruzioni, consulta la pagina Creazione di un secret.

    • Prendi nota del nome e della versione del secret. Avrai bisogno di queste informazioni per configurare Cloud Build per accedere al secret.

Autorizzazioni IAM richieste

Concedi il ruolo IAM Funzione di accesso ai secret di Secret Manager (roles/secretmanager.secretAccessor) per il secret all'account di servizio che stai utilizzando per la build:

  1. Apri la pagina Secret Manager nella console Google Cloud:

    Vai alla pagina di Secret Manager

  2. Seleziona la casella di controllo del secret che vuoi utilizzare nella build.

  3. Se non è già aperto, fai clic su Mostra riquadro informazioni per aprirlo.

  4. Nel riquadro, in Autorizzazioni, fai clic su Aggiungi entità.

  5. Nel campo Nuove entità, inserisci l'indirizzo email del tuo account di servizio.

  6. Nella casella a discesa Seleziona un ruolo, seleziona Funzione di accesso ai secret di Secret Manager.

  7. Fai clic su Salva.

Configurazione delle build per l'accesso ai secret UTF-8 da Secret Manager

  1. Nella directory root del progetto, crea un file di configurazione di Cloud Build denominato cloudbuild.yaml o cloudbuild.json.

  2. Nel file di configurazione della build:

    • Dopo tutti i steps di build, aggiungi un campo availableSecrets per specificare la versione del secret e le variabili di ambiente da utilizzare per il secret. Puoi includere variabili di sostituzione nel valore del campo secretVersion. Puoi specificare più di un secret in una build.
    • Nel passaggio di build in cui vuoi specificare il secret:
      • Aggiungi un campo entrypoint che rimandi a bash per utilizzare lo strumento bash nel passaggio di build. Questo è obbligatorio per fare riferimento alla variabile di ambiente per il secret.
      • Aggiungi un campo secretEnv che specifichi la variabile di ambiente.
      • Nel campo args, aggiungi un flag -c come primo argomento. Qualsiasi stringa passata dopo -c viene trattata come un comando. Per ulteriori informazioni sull'esecuzione dei comandibash con -c, consulta la documentazionebash.
      • Quando specifichi il secret nel campo args, specificalo utilizzando la variabile di ambiente con prefisso $$.

    The following example build config file shows how to login to Docker using the Docker username and password stored in Secret Manager.

    YAML

    steps:
    - name: 'gcr.io/cloud-builders/docker'
      entrypoint: 'bash'
      args: ['-c', 'docker login --username=$$USERNAME --password=$$PASSWORD']
      secretEnv: ['USERNAME', 'PASSWORD']
    availableSecrets:
      secretManager:
      - versionName: projects/PROJECT_ID/secrets/DOCKER_PASSWORD_SECRET_NAME/versions/DOCKER_PASSWORD_SECRET_VERSION
        env: 'PASSWORD'
      - versionName: projects/PROJECT_ID/secrets/DOCKER_USERNAME_SECRET_NAME/versions/DOCKER_USERNAME_SECRET_VERSION
        env: 'USERNAME'
    

    JSON

    {
      "steps": [
      {
        "name": "gcr.io/cloud-builders/docker",
        "entrypoint": "bash",
        "args": [
          "-c",
          "docker login --username=$$USERNAME --password=$$PASSWORD"
        ],
        "secretEnv": [
          "USERNAME",
          "PASSWORD"
        ]
      }
      ],
      "availableSecrets": {
        "secretManager": [{
          "versionName": "projects/PROJECT_ID/secrets/DOCKER_PASSWORD_SECRET_NAME/versions/DOCKER_PASSWORD_SECRET_VERSION",
          "env": "PASSWORD"
      }, {
        "versionName": "projects/PROJECT_ID/secrets/DOCKER_USERNAME_SECRET_NAME/versions/DOCKER_USERNAME_SECRET_VERSION",
        "env": "USERNAME"
         }]
      }
    }
    

    Replace the placeholder values in the above commands with the following:

    • PROJECT_ID: The ID of the Google Cloud project where you've stored your secrets.
    • DOCKER_USERNAME_SECRET_NAME: The secret name corresponding to your Docker username. You can get the secret name from the Secret Manager page in the Google Cloud console.
    • DOCKER_USERNAME_SECRET_VERSION: The secret version of your Docker username. You can get the secret version by clicking on a secret name on the Secret Manager page in the Google Cloud console.
    • DOCKER_PASSWORD_SECRET_NAME: The secret name corresponding to your Docker password. You can get the secret name from the Secret Manager page in the Google Cloud console.
    • DOCKER_PASSWORD_SECRET_VERSION: The secret version of your Docker password. You can get the secret version by clicking on a secret name on the Secret Manager page in the Google Cloud console.
  3. Use the build config file to start a build using the command line or to automate builds using triggers.

Example: Accessing secrets from scripts and processes

secretEnv field adds the value of the secret to the environment and you can access this value via environment variable from scripts or processes:

YAML

steps:
- name: python:slim
  entrypoint: python
  args: ['main.py']
  secretEnv: ['MYSECRET']
availableSecrets:
  secretManager:
  - versionName: projects/$PROJECT_ID/secrets/mySecret/versions/latest
    env: 'MYSECRET'

JSON

{
  "steps": [
  {
    "name": "python:slim",
    "entrypoint": "python",
    "args": [
        "main.py"
    ],
    "secretEnv": [
        "MYSECRET"
    ]
}
],
"availableSecrets": {
  "secretManager": [
    {
        "versionName": "projects/$PROJECT_ID/secrets/mySecret/versions/latest",
        "env": "MYSECRET"
    }
  ]
}
}

The following contents of main.py prints the first five characters of the secret:

import os
print(os.environ.get("MYSECRET", "Not Found")[:5], "...")

Example: authenticating to Docker

In some situations, before interacting with Docker images, your build would need to authenticate to Docker. For example, Docker authentication is required for builds to pull private images and push private or public images to Docker Hub. In these cases, you can store your Docker username and password in Secret Manager and then configure Cloud Build to access the username and password from Secret Manager. For instructions on doing this see Interacting with Docker Hub images.

Example: GitHub pull request creation

Another example where you might want to configure your build to access a sensitive information from Secret Manager is for creating a GitHub pull request in response to builds. To do this:

  • Create a GitHub token.
  • Store the GitHub token in Secret Manager.
  • In your build config file:
    • After all the build steps, add an availableSecrets field to specify the secret version and the environment variable to use for the GitHub token.
    • Add a build step to invoke the command to create a GitHub pull request.
  • Create a GitHub app trigger and use the build config file to invoke the trigger.

The following example config file shows how to create a GitHub pull request using the GitHub token:

YAML

steps:
- name: 'launcher.gcr.io/google/ubuntu1604'
  id: Create GitHub pull request
  entrypoint: bash
  args:
  - -c
  - curl -X POST -H "Authorization:Bearer $$GH_TOKEN" -H 'Accept:application/vnd.github.v3+json' https://api.github.com/repos/GITHUB_USERNAME/REPO_NAME/pulls -d '{"head":"HEAD_BRANCH","base":"BASE_BRANCH", "title":"NEW_PR"}'
  secretEnv: ['GH_TOKEN']
availableSecrets:
  secretManager:
  - versionName: projects/PROJECT_ID/secrets/GH_TOKEN_SECRET_NAME/versions/latest
    env: GH_TOKEN

JSON

{
  "steps": [
  {
    "name": "launcher.gcr.io/google/ubuntu1604",
    "id": "Create GitHub pull request",
    "entrypoint": "bash",
    "args": [
      "-c",
       "curl -X POST -H \"Authorization:Bearer $$GH_TOKEN\" -H 'Accept:application/vnd.github.v3+json' https://api.github.com/repos/GITHUB_USERNAME/REPO_NAME -d '{\"head\":\"HEAD_BRANCH\",\"base\":\"BASE_BRANCH\", \"title\":\"NEW_PR\"}'
    ],
    "secretEnv": ['GH_TOKEN']
}
],
"availableSecrets": {
  "secretManager": [
  {
    "versionName": "projects/PROJECT_ID/secrets/GH_TOKEN_SECRET_NAME/versions/latest",
    "env": "GH_TOKEN"
  }
  ]
}
}

Sostituisci i valori segnaposto nei comandi precedenti con i seguenti:

  • PROJECT_ID: l'ID del progetto Google Cloud in cui hai archiviato i tuoi secret.
  • GITHUB_USERNAME: il nome utente GitHub del proprietario del repository.
  • REPO_NAME: il nome del repository GitHub.
  • HEAD_BRANCH: il nome del ramo in cui sono implementate le modifiche. Per le richieste di pull tra repository nella stessa rete, spazio dei nomi head con un utente come questo: username:branch.
  • BASE_BRANCH: il nome del ramo in cui vuoi inserire le modifiche. Deve essere un ramo esistente nel repository attuale. Non puoi inviare una richiesta di pull a un repository che richiede l'unione con una base di un altro repository.
  • GH_TOKEN_SECRET_NAME: il nome del secret corrispondente al tuo token GitHub.
  • NEW_PR: la nuova richiesta di pull che vuoi creare.

Configurazione delle build per accedere ai secret non UTF-8 da Secret Manager

  1. Nel file di configurazione della build, aggiungi un passaggio di build per accedere alla versione del secret in Secret Manager e archiviarla in un file. Il seguente passaggio di build accede a secret-name e lo archivia in un file denominato decrypted-data.txt:

    YAML

    steps:
    - name: gcr.io/cloud-builders/gcloud
      entrypoint: 'bash'
      args: [ '-c', "gcloud secrets versions access latest --secret=secret-name --format='get(payload.data)' | tr '_-' '/+' | base64 -d > decrypted-data.txt" ]
    

    JSON

    {
      "steps": [
      {
        "name": "gcr.io/cloud-builders/gcloud",
        "entrypoint": "bash",
        "args": [
          "-c",
          "gcloud secrets versions access latest --secret=secret-name --format='get(payload.data)' | tr '_-' '/+' | base64 -d > decrypted-data.txt"
        ]
      }
      ]
    }
    
  2. Utilizza il file con i dati decriptati in un passaggio di build. Il seguente snippet di codice utilizza decrypted-data.txt per accedere a un registro Docker privato:

    YAML

    steps:
    - name: gcr.io/cloud-builders/gcloud
      entrypoint: 'bash'
      args: [ '-c', "gcloud secrets versions access latest --secret=secret-name --format='get(payload.data)' | tr '_-' '/+' | base64 -d > decrypted-data.txt" ]
    - name: gcr.io/cloud-builders/docker
      entrypoint: 'bash'
      args: [ '-c', 'docker login --username=my-user --password-stdin < decrypted-data.txt']
    

    JSON

    {
      "steps": [
      {
        "name": "gcr.io/cloud-builders/gcloud",
        "entrypoint": "bash",
        "args": [
          "-c",
          "gcloud secrets versions access latest --secret=secret-name --format='get(payload.data)' | tr '_-' '/+' | base64 -d > password.txt"
         ]
      },
      {
        "name": "gcr.io/cloud-builders/docker",
        "entrypoint": "bash",
        "args": [
          "-c",
          "docker login --username=my-user --password-stdin < decrypted-data.txt"
         ]
      }
      ]
    }
    
  3. Utilizza il file di configurazione di compilazione per avviare una build utilizzando la riga di comando o per automatizzare le build utilizzando i trigger.

Passaggi successivi