Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Aprende a crear un Secret y configurar los servicios y revisiones de Knative serving para usar ese Secret.
Un caso de uso común para un servicio es acceder a aplicaciones de terceros a través de nombres de usuario y contraseñas. Para Google Kubernetes Engine, se recomienda almacenar este tipo de información sensible en un objeto Secret de Kubernetes.
Para proporcionar a tus contenedores acceso a los secretos, puedes activar cada secreto como un volumen, lo que hace que las entradas del secreto estén disponibles para el contenedor como archivos. Debes activar tu secreto para asegurarte de obtener la versión más reciente de cada secreto cuando se lea.
En los pasos siguientes, simplemente se demuestra cómo crear un Secret, pero existen varias formas de crear un Secret, como se explica en el tema Secret.
Cuando crees un Secret, asegúrate de crearlo en el mismo espacio de nombres en el que se encuentra el clúster que ejecuta tu servicio de Knative serving. En estas instrucciones, se usa el espacio de nombres default.
Para crear un Secret en el espacio de nombres default de tu clúster, sigue estos pasos:
Haz que un Secret esté disponible para un servicio
Puedes asociar secretos con un servicio mediante la consola de Google Cloud o las herramientas de línea de comandos cuando implementas un servicio nuevo o actualizas un servicio existente e implementas una revisión:
Console
Ve a Knative serving en la consola de Google Cloud:
Haz clic en Crear servicio si quieres configurar un servicio nuevo en el que realizarás la implementación. Si quieres configurar un servicio existente, haz clic en el servicio y, luego, haz clic en Implementar y editar una nueva revisión.
En Configuración avanzada, haz clic en Variables and Secrets.
En Reference a Secret (Crear una referencia a un secreto), selecciona el secreto deseado en el menú desplegable.
En el menú desplegable Reference Method (Método de referencia), selecciona la forma en la que deseas usar el secreto, activado como un volumen o expuesto como variables de entorno.
Si usas la opción de activarlo como un volumen, especifica la ruta de acceso y haz clic en Listo.
Si deseas exponer como variables de entorno, sigue estos pasos:
Proporciona el Nombre de la variable y selecciona el valor de secreto correspondiente en el menú desplegable Clave.
Haz clic en Agregar para agregar otro valor de secreto.
Proporciona el Nombre de la variable y selecciona el valor de secreto correspondiente en el menú desplegable Clave.
Haz clic en Listo.
Haz clic en Siguiente para pasar a la siguiente sección.
En la sección Configura la forma en que se activa el servicio, selecciona la conectividad que deseas usar para invocar el servicio.
Haz clic en Crear para implementar la imagen en Knative serving y espera a que termine la implementación.
gcloud
Puedes usar Google Cloud CLI para asociar Secrets con servicios nuevos o actualizar los existentes:
Para los servicios existentes, ejecuta el comando gcloud run services update con uno de los siguientes parámetros a fin de actualizar un Secret:
KEY1=VALUE1,KEY2=VALUE2 por una lista de pares de valores y nombres separados por comas para cada Secret.
Para cada KEY, debes especificar la ruta de acceso comenzando con una barra diagonal / a fin de activar un Secret como un archivo. De manera opcional, puedes excluir la barra diagonal para activar el Secret como una variable de entorno.
Para cada VALUE, especifica el nombre del secreto.
Cómo especificar varios parámetros.
Opciones de parámetros de comando
A fin de especificar varios conjuntos de pares clave-valor, puedes especificar varios parámetros para facilitar la lectura. Ejemplo:
IMAGE_URL por una referencia a la imagen del contenedor, como gcr.io/cloudrun/hello
SERVICE por el nombre de tu servicio
KEY1=VALUE1,KEY2=VALUE2 por una lista de pares de valores y nombres separados por comas para cada Secret.
Para cada KEY, debes especificar la ruta de acceso comenzando con una barra diagonal / a fin de activar un Secret como un archivo. De manera opcional, puedes excluir la barra diagonal para activar el Secret como una variable de entorno.
Para cada VALUE, especifica el nombre del secreto.
Cómo especificar varios parámetros.
Opciones de parámetros de comando
A fin de especificar varios conjuntos de pares clave-valor, puedes especificar varios parámetros para facilitar la lectura. Ejemplo:
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-04-22 (UTC)"],[],[],null,["# Using secrets\n\nLearn how to create a Secret and configure your Knative serving\nservices and revisions to use that Secret.\n\nA common use case for a service is to access third-party applications through\nusernames and passwords. For Google Kubernetes Engine, it's a best practice to\nstore this type of sensitive information in a Kubernetes\n[Secret](https://kubernetes.io/docs/concepts/configuration/secret/) object.\n\nTo provide your containers with access to Secrets, you can mount each Secret as\na volume, which makes the entries in the Secret available to the container as\nfiles. You should mount your Secret to ensure that you get the latest version of\neach Secret when it is read.\n\nYou can also pass a Secret using\n[environment variables](/kubernetes-engine/enterprise/knative-serving/docs/configuring/environment-variables).\n| **Caution:** Do not use environment variables for sensitive information because environment variables are stored as text and are accessible to the cluster.\n\nCreating a Secret\n-----------------\n\nThe following steps simply demonstrate how to create a Secret but there are\nseveral ways to create a Secret, as explained in the\n[Secret](https://kubernetes.io/docs/concepts/configuration/secret/#creating-a-secret)\ntopic.\n\nWhen you create a Secret, make sure you create it in the same namespace as the\ncluster that is running your Knative serving service. In these\nexamples, the `default` namespace is used.\n\nTo create a Secret in the `default` namespace of your cluster:\n\n- Create a Secret using a file:\n\n echo -n 'devuser' \u003e ./username.txt\n echo -n 'S!B\\*d$zDsb' \u003e ./password.txt\n kubectl create secret generic user-creds --from-file=./username.txt --from-file=./password.txt\n\n- Create a Secret using a `kubectl` command only:\n\n kubectl create secret generic user-creds --from-literal=username=devuser --from-literal=password='S!B\\*d$zDsb'\n\nMaking a Secret available to a service\n--------------------------------------\n\nYou can associate secrets with a service using the Google Cloud console or\ncommand-line tools when you deploy a new\n[service](/kubernetes-engine/enterprise/knative-serving/docs/deploying#service) or update an existing service and\ndeploy a [revision](/kubernetes-engine/enterprise/knative-serving/docs/deploying#revision): \n\n### Console\n\n\n1. Go to Knative serving in the Google Cloud console:\n\n [Go to Knative serving](https://console.cloud.google.com/kubernetes/run)\n2. Click **Create Service** if you are configuring a\n new service you are deploying to. If you are configuring an\n existing service, click on the service, then click\n **Edit \\& Deploy New Revision**.\n\n3. Under *Advanced settings* , click **Variables and Secrets**.\n\n4. Under *Reference a Secret*, select the\n desired Secret from the pulldown menu.\n\n - In the *Reference method* pulldown menu, select the way you want to use your Secret, mounted as a volume or exposed as environment variables.\n - If you are using mount as a volume, specify the path, then click **Done**.\n - If you are exposing as environment variables:**Caution** : Do not use [environment\n | variables](/kubernetes-engine/enterprise/knative-serving/docs/configuring/environment-variables) for sensitive information.\n 1. Supply the *Name* of the variable and select the corresponding Secret value from the *Key* pulldown menu.\n 2. Click **Add** to add another secret value.\n 3. Supply the *Name* of the variable and select the corresponding Secret value from the *Key* pulldown menu.\n 4. Click **Done**.\n\n \u003cbr /\u003e\n\n5. Click **Next** to continue to the next section.\n\n6. In the **Configure how this service is triggered** section,\n select which connectivity you would like to use to invoke the service.\n\n7. Click **Create** to deploy the image to Knative serving and wait\n for the deployment to finish.\n\n### gcloud\n\n\nYou can use the Google Cloud CLI to associate Secrets\nwith new services or to update existing services:\n\n\u003cbr /\u003e\n\n- For existing services, update a Secret by running the\n [`gcloud run services update`](/sdk/gcloud/reference/run/services/update)\n command with one of the following parameters:\n\n - [`--clear-secrets`](/sdk/gcloud/reference/run/services/update#--clear-secrets)\n - [`--remove-secrets`](/sdk/gcloud/reference/run/services/update#--remove-secrets)\n - [`--set-secrets`](/sdk/gcloud/reference/run/services/update#--set-secrets)\n - [`--update-secrets`](/sdk/gcloud/reference/run/services/update#--update-secrets)\n\n Example: \n\n ```bash\n gcloud run services update SERVICE --update-secrets KEY1=VALUE1,KEY2=VALUE2\n ```\n\n Replace:\n - \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with the name of your service.\n - \u003cvar translate=\"no\"\u003eKEY1=VALUE1,KEY2=VALUE2\u003c/var\u003e with a comma separated list of name and value pairs for each Secret. For each \u003cvar translate=\"no\"\u003eKEY\u003c/var\u003e you specify the path by starting with a forward slash `/` to mount a Secret as a file. Optionally, you can exclude the forward slash to mount the Secret as an [environment variable](/kubernetes-engine/enterprise/knative-serving/docs/configuring/environment-variables). For each \u003cvar translate=\"no\"\u003eVALUE\u003c/var\u003e, specify the secret name. [How to specify multiple parameters](#command-line). \n\n ### Command parameter options\n\n To specify several sets of key-value pairs, you can specify multiple parameters for readability. Example: \n\n ```bash\n [...]\n --update-secrets \"KEY=VALUE1\" \\\n --update-secrets \"KEY=VALUE2\" \\\n --update-secrets \"KEY=VALUE3\"\n ``` \n OK\n- For new services, associate a Secret by running the\n `gcloud run deploy` command with the\n [`--set-secrets`](/sdk/gcloud/reference/run/deploy#--set-secrets)\n parameter:\n\n ```bash\n gcloud run deploy SERVICE --image=IMAGE_URL --set-secrets KEY1=VALUE1,KEY2=VALUE2\n ```\n\n Replace:\n - \u003cvar translate=\"no\"\u003eIMAGE_URL\u003c/var\u003e with a reference to the container image, for example, `gcr.io/cloudrun/hello`.\n - \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with the name of your service.\n - \u003cvar translate=\"no\"\u003eKEY1=VALUE1,KEY2=VALUE2\u003c/var\u003e with a comma separated list of name and value pairs for each Secret. For each \u003cvar translate=\"no\"\u003eKEY\u003c/var\u003e you specify the path by starting with a forward slash `/` to mount a Secret as a file. Optionally, you can exclude the forward slash to mount the Secret as an [environment variable](/kubernetes-engine/enterprise/knative-serving/docs/configuring/environment-variables). For each \u003cvar translate=\"no\"\u003eVALUE\u003c/var\u003e, specify the secret name. [How to specify multiple parameters](#command-line). \n\n ### Command parameter options\n\n To specify several sets of key-value pairs, you can specify multiple parameters for readability. Example: \n\n ```bash\n [...]\n --update-secrets \"KEY=VALUE1\" \\\n --update-secrets \"KEY=VALUE2\" \\\n --update-secrets \"KEY=VALUE3\"\n ``` \n OK"]]