Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Aprenda a criar um Secret e configurar seus serviços e revisões de Knative serving para usar esse Secret.
Um caso de uso comum de um serviço é acessar aplicativos de terceiros por meio de nomes de usuário e senhas. Para o Google Kubernetes Engine, é uma prática recomendada armazenar esse tipo de informação confidencial em um objeto Secret do Kubernetes.
Para dar aos seus contêineres acesso a secrets, ative cada secret como um volume, o que disponibiliza as entradas do secret para o contêiner como arquivos. Ative seu secret para garantir que você tenha a versão mais recente de cada secret quando ele for lido.
Nas etapas a seguir, demonstramos como criar um secret, mas há várias maneiras de criar um secret, conforme explicado no tópico Secret.
Ao criá-lo, certifique-se de criar no mesmo namespace que o
cluster que está executando o serviço do Knative serving. Nestes
exemplos, o namespace default é usado.
Para criar um secret no namespace default do cluster:
É possível associar secrets a um serviço usando o console do Google Cloud ou
as ferramentas de linha de comando ao implantar um novo
serviço ou atualizar um atual e
implantar uma revisão:
Console
Acesse o Knative serving no console do Google Cloud:
Clique em Criar serviço se estiver configurando um
novo serviço em que fará uma implantação. Se você estiver configurando um
serviço atual, clique nele e em
Editar e implantar uma nova revisão.
Em Configurações avançadas, clique em Variáveis e secrets.
Em Referenciar um secret, selecione o
secret que você quer no menu suspenso.
No menu suspenso Método de referência,
selecione a maneira como você quer usar
o secret, montado como um volume ou exposto como variáveis de ambiente.
Se você estiver usando a montagem como volume, especifique o caminho e clique em Concluído.
Se você estiver expondo como variáveis de ambiente:
forneça o Nome da variável e selecione o valor de secret
correspondente no menu suspenso Chave;
clique em Adicionar para adicionar outro valor de secret;
forneça o Nome da variável e selecione o valor de secret
correspondente no menu suspenso Chave;
Clique em Concluído.
Clique em Avançar para acessar a próxima seção.
Na seção Configurar como este serviço é acionado,
selecione qual conectividade você quer usar para invocar o serviço.
Clique em Criar para implantar a imagem no Knative serving e aguarde
até que a implantação seja concluída.
gcloud
Use a Google Cloud CLI para associar os secrets
a novos serviços ou atualizar serviços existentes:
Para os serviços atuais, atualize um secret executando o comando
gcloud run services update
com um dos seguintes parâmetros:
KEY1=VALUE1,KEY2=VALUE2 com uma lista separada
por vírgula de pares de nome e valor para cada secret.
Para cada KEY, você especifica
o caminho, começando com uma barra / para ativar um secret
como um arquivo. Se preferir, exclua a barra para ativar o secret
como uma variável de ambiente.
Para cada VALUE, especifique o nome do secret.
Como especificar vários parâmetros:
Opções de parâmetros de comando
Para especificar vários conjuntos de pares de chave-valor, é
possível especificar vários parâmetros de legibilidade. Exemplo:
IMAGE_URL por uma referência à imagem de contêiner. Por
exemplo, gcr.io/cloudrun/hello;
SERVICE pelo nome do serviço;
KEY1=VALUE1,KEY2=VALUE2 com uma lista separada
por vírgula de pares de nome e valor para cada secret.
Para cada KEY, você especifica
o caminho, começando com uma barra / para ativar um secret
como um arquivo. Se preferir, exclua a barra para ativar o secret
como uma variável de ambiente.
Para cada VALUE, especifique o nome do secret.
Como especificar vários parâmetros:
Opções de parâmetros de comando
Para especificar vários conjuntos de pares de chave-valor, é
possível especificar vários parâmetros de legibilidade. Exemplo:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 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"]]