feat: add configmap-secret translation

This commit is contained in:
edsoncelio
2021-07-09 15:12:29 -03:00
parent 0a5d839101
commit 9822c9a4da
3 changed files with 123 additions and 135 deletions
@@ -1,8 +1,8 @@
--- ---
title: Managing Secret using Configuration File title: Gerenciando Secret usando Arquivo de Configuração
content_type: task content_type: task
weight: 20 weight: 20
description: Creating Secret objects using resource configuration file. description: Criando objetos Secret usando arquivos de configuração de recursos.
--- ---
<!-- overview --> <!-- overview -->
@@ -13,26 +13,24 @@ description: Creating Secret objects using resource configuration file.
<!-- steps --> <!-- steps -->
## Create the Config file ## Crie o arquivo de configuração
You can create a Secret in a file first, in JSON or YAML format, and then Você pode criar um Secret primeiramente em um arquivo, no formato JSON ou YAML, e depois
create that object. The criar o objeto. O recurso [Secret](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#secret-v1-core)
[Secret](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#secret-v1-core) contém dois *maps*: `data` e `stringData`.
resource contains two maps: `data` and `stringData`. O campo `data` é usado para armazenar dados arbitrários, codificados usando base64. O
The `data` field is used to store arbitrary data, encoded using base64. The campo `stringData` é usado por conveniência, e permite que você use dados para um Secret
`stringData` field is provided for convenience, and it allows you to provide como *strings* não codificadas.
Secret data as unencoded strings. As chaves para `data` e `stringData` precisam ser compostas por caracteres alfanuméricos,
The keys of `data` and `stringData` must consist of alphanumeric characters, `_`, `-` ou `.`.
`-`, `_` or `.`.
For example, to store two strings in a Secret using the `data` field, convert Por exemplo, para armazenar duas strings em um Secret usando o campo `data`, converta
the strings to base64 as follows: as strings para base64 da seguinte forma:
```shell ```shell
echo -n 'admin' | base64 echo -n 'admin' | base64
``` ```
A saída deve ser similar a:
The output is similar to:
``` ```
YWRtaW4= YWRtaW4=
@@ -42,14 +40,13 @@ YWRtaW4=
echo -n '1f2d1e2e67df' | base64 echo -n '1f2d1e2e67df' | base64
``` ```
The output is similar to: A saída deve ser similar a:
``` ```
MWYyZDFlMmU2N2Rm MWYyZDFlMmU2N2Rm
``` ```
Write a Secret config file that looks like this: Escreva o arquivo de configuração do Secret, que ser parecido com:
```yaml ```yaml
apiVersion: v1 apiVersion: v1
kind: Secret kind: Secret
@@ -61,27 +58,26 @@ data:
password: MWYyZDFlMmU2N2Rm password: MWYyZDFlMmU2N2Rm
``` ```
Note that the name of a Secret object must be a valid Perceba que o nome do objeto Secret precisa ser um
[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). [nome de subdomínio DNS](/docs/concepts/overview/working-with-objects/names#dns-subdomain-name) válido.
{{< note >}} {{< note >}}
The serialized JSON and YAML values of Secret data are encoded as base64 Os valores serializados dos dados JSON e YAML de um Secret são codificados em strings
strings. Newlines are not valid within these strings and must be omitted. When base64. Novas linhas não são válidas com essas strings e devem ser omitidas. Quando
using the `base64` utility on Darwin/macOS, users should avoid using the `-b` usar o utilitário `base64` em Darwin/MacOS, os usuários devem evitar usar a opção `-b`
option to split long lines. Conversely, Linux users *should* add the option para separar linhas grandes. Por outro lado, usuários de Linux *devem* adicionar a opção
`-w 0` to `base64` commands or the pipeline `base64 | tr -d '\n'` if the `-w` `-w 0` ao comando `base64` ou o *pipe* `base64 | tr -d '\n'` se a opção `w` não for disponível
option is not available.
{{< /note >}} {{< /note >}}
For certain scenarios, you may wish to use the `stringData` field instead. This Para cenários específicos, você pode querer usar o campo `stringData` ao invés de `data`.
field allows you to put a non-base64 encoded string directly into the Secret, Esse campo permite que você use strings não-base64 diretamente dentro do Secret,
and the string will be encoded for you when the Secret is created or updated. e a string vai ser codificada para você quando o Secret for criado ou atualizado.
A practical example of this might be where you are deploying an application Um exemplo prático para isso pode ser quando você esteja fazendo *deploy* de uma aplicação
that uses a Secret to store a configuration file, and you want to populate que usa um Secret para armazenar um arquivo de configuração, e você quer popular partes desse
parts of that configuration file during your deployment process. arquivo de configuração durante o processo de *deployment*.
For example, if your application uses the following configuration file: Por exemplo, se sua aplicação usa o seguinte arquivo de configuração:
```yaml ```yaml
apiUrl: "https://my.api.com/api/v1" apiUrl: "https://my.api.com/api/v1"
@@ -89,7 +85,7 @@ username: "<user>"
password: "<password>" password: "<password>"
``` ```
You could store this in a Secret using the following definition: Você pode armazenar isso em um Secret usando a seguinte definição:
```yaml ```yaml
apiVersion: v1 apiVersion: v1
@@ -104,30 +100,30 @@ stringData:
password: <password> password: <password>
``` ```
## Create the Secret object ## Crie o objeto Secret
Now create the Secret using [`kubectl apply`](/docs/reference/generated/kubectl/kubectl-commands#apply): Agora, crie o Secret usando [`kubectl apply`](/docs/reference/generated/kubectl/kubectl-commands#apply):
```shell ```shell
kubectl apply -f ./secret.yaml kubectl apply -f ./secret.yaml
``` ```
The output is similar to: A saída deve ser similar a:
``` ```
secret/mysecret created secret/mysecret created
``` ```
## Check the Secret ## Verifique o Secret
The `stringData` field is a write-only convenience field. It is never output when O campo `stringData` é um campo de conveniência apenas de leitura. Ele nunca vai ser exibido
retrieving Secrets. For example, if you run the following command: ao buscar um Secret. Por exemplo, se você executar o seguinte comando:
```shell ```shell
kubectl get secret mysecret -o yaml kubectl get secret mysecret -o yaml
``` ```
The output is similar to: A saída deve ser similar a:
```yaml ```yaml
apiVersion: v1 apiVersion: v1
@@ -143,14 +139,13 @@ data:
config.yaml: YXBpVXJsOiAiaHR0cHM6Ly9teS5hcGkuY29tL2FwaS92MSIKdXNlcm5hbWU6IHt7dXNlcm5hbWV9fQpwYXNzd29yZDoge3twYXNzd29yZH19 config.yaml: YXBpVXJsOiAiaHR0cHM6Ly9teS5hcGkuY29tL2FwaS92MSIKdXNlcm5hbWU6IHt7dXNlcm5hbWV9fQpwYXNzd29yZDoge3twYXNzd29yZH19
``` ```
The commands `kubectl get` and `kubectl describe` avoid showing the contents of a `Secret` by Os comandos `kubectl get` e `kubectl describe` omitem o conteúdo de um `Secret` por padrão.
default. This is to protect the `Secret` from being exposed accidentally to an onlooker, Isso para proteger o `Secret` de ser exposto acidentalmente para uma pessoa não autorizada,
or from being stored in a terminal log. ou ser armazenado em um log de terminal.
To check the actual content of the encoded data, please refer to Para verificar o conteúdo atual de um dado codificado, veja [decodificando secret](/docs/tasks/configmap-secret/managing-secret-using-kubectl/#decoding-secret).
[decoding secret](/docs/tasks/configmap-secret/managing-secret-using-kubectl/#decoding-secret).
If a field, such as `username`, is specified in both `data` and `stringData`, Se um campo, como `username`, é especificado em `data` e `stringData`,
the value from `stringData` is used. For example, the following Secret definition: o valor de `stringData` é o usado. Por exemplo, dado a seguinte definição do Secret:
```yaml ```yaml
apiVersion: v1 apiVersion: v1
@@ -164,7 +159,7 @@ stringData:
username: administrator username: administrator
``` ```
Results in the following Secret: Resulta no seguinte Secret:
```yaml ```yaml
apiVersion: v1 apiVersion: v1
@@ -180,11 +175,11 @@ data:
username: YWRtaW5pc3RyYXRvcg== username: YWRtaW5pc3RyYXRvcg==
``` ```
Where `YWRtaW5pc3RyYXRvcg==` decodes to `administrator`. Onde `YWRtaW5pc3RyYXRvcg==` é decodificado em `administrator`.
## Clean Up ## Limpeza
To delete the Secret you have created: Para apagar o Secret que você criou:
```shell ```shell
kubectl delete secret mysecret kubectl delete secret mysecret
@@ -192,7 +187,7 @@ kubectl delete secret mysecret
## {{% heading "whatsnext" %}} ## {{% heading "whatsnext" %}}
- Read more about the [Secret concept](/docs/concepts/configuration/secret/) - Leia mais sobre o [conceito do Secret](/docs/concepts/configuration/secret/)
- Learn how to [manage Secret with the `kubectl` command](/docs/tasks/configmap-secret/managing-secret-using-kubectl/) - Leia sobre como [gerenciar Secret com o comando `kubectl`](/docs/tasks/configmap-secret/managing-secret-using-kubectl/)
- Learn how to [manage Secret using kustomize](/docs/tasks/configmap-secret/managing-secret-using-kustomize/) - Leia sobre como [gerenciar Secret usando kustomize](/docs/tasks/configmap-secret/managing-secret-using-kustomize/)
@@ -1,8 +1,8 @@
--- ---
title: Managing Secret using kubectl title: kubectl Gerenciando Secret usando kubectl
content_type: task content_type: task
weight: 10 weight: 10
description: Creating Secret objects using kubectl command line. description: Criando objetos Secret usando a linha de comando kubectl.
--- ---
<!-- overview --> <!-- overview -->
@@ -13,25 +13,26 @@ description: Creating Secret objects using kubectl command line.
<!-- steps --> <!-- steps -->
## Create a Secret ## Criando um Secret
A `Secret` can contain user credentials required by Pods to access a database. Um `Secret` pode conter credenciais de usuário requeridas por Pods para acesso a um banco de dados.
For example, a database connection string consists of a username and password. Por exemplo, uma string de conexão de banco de dados é composta por um usuário e senha.
You can store the username in a file `./username.txt` and the password in a Você pode armazenar o usuário em um arquivo `./username.txt` e a senha em um
file `./password.txt` on your local machine. arquivo `./password.txt` na sua máquina local.
```shell ```shell
echo -n 'admin' > ./username.txt echo -n 'admin' > ./username.txt
echo -n '1f2d1e2e67df' > ./password.txt echo -n '1f2d1e2e67df' > ./password.txt
``` ```
The `-n` flag in the above two commands ensures that the generated files will A opção `-n` nos comandos acima garante que os arquivos criados não vão conter
not contain an extra newline character at the end of the text. This is uma nova linha extra no final do arquivo de texto. Isso é importante porque
important because when `kubectl` reads a file and encode the content into quando o `kubectl` lê um arquivo e codifica o conteúdo em uma string base64,
base64 string, the extra newline character gets encoded too. o caractere da nova linha extra também é codificado.
O comando `kubectl create secret` empacota os arquivos em um Secret e cria um
objeto no API server.
The `kubectl create secret` command packages these files into a Secret and creates
the object on the API server.
```shell ```shell
kubectl create secret generic db-user-pass \ kubectl create secret generic db-user-pass \
@@ -39,32 +40,28 @@ kubectl create secret generic db-user-pass \
--from-file=./password.txt --from-file=./password.txt
``` ```
The output is similar to: A saída deve ser similar a:
``` ```
secret/db-user-pass created secret/db-user-pass created
``` ```
Default key name is the filename. You may optionally set the key name using O nome da chave padrão é o nome do arquivo. Opcionalmente, você pode definir
`--from-file=[key=]source`. For example: o nome da chave usando `--from-file=[key=]source`. Por exemplo:
```shell ```shell
kubectl create secret generic db-user-pass \ kubectl create secret generic db-user-pass \
--from-file=username=./username.txt \ --from-file=username=./username.txt \
--from-file=password=./password.txt --from-file=password=./password.txt
``` ```
Você não precisa escapar o caractere especial em senhas a partir de arquivos (`--from-file`).
You do not need to escape special characters in passwords from files Você também pode prover dados para Secret usando a tag `--from-literal=<key>=<value>`.
(`--from-file`). Essa tag pode ser especificada mais de uma vez para prover múltiplos pares de chave-valor.
Observe que caracteres especiais como `$`, `\`, `*`, `=`, e `!` vão ser interpretados
You can also provide Secret data using the `--from-literal=<key>=<value>` tag. pelo seu [shell](https://en.wikipedia.org/wiki/Shell_(computing)) e precisam ser escapados.
This tag can be specified more than once to provide multiple key-value pairs. Na maioria dos shells, a forma mais fácil de escapar as senhas é usar aspas simples (`'`).
Note that special characters such as `$`, `\`, `*`, `=`, and `!` will be Por exemplo, se sua senha atual é `S!B\*d$zDsb=`, você precisa executar o comando dessa forma:
interpreted by your [shell](https://en.wikipedia.org/wiki/Shell_(computing))
and require escaping.
In most shells, the easiest way to escape the password is to surround it with
single quotes (`'`). For example, if your actual password is `S!B\*d$zDsb=`,
you should execute the command this way:
```shell ```shell
kubectl create secret generic dev-db-secret \ kubectl create secret generic dev-db-secret \
@@ -72,28 +69,27 @@ kubectl create secret generic dev-db-secret \
--from-literal=password='S!B\*d$zDsb=' --from-literal=password='S!B\*d$zDsb='
``` ```
## Verify the Secret ## Verificando o Secret
You can check that the secret was created: Você pode verificar se o secret foi criado:
```shell ```shell
kubectl get secrets kubectl get secrets
``` ```
The output is similar to: A saída deve ser similar a:
``` ```
NAME TYPE DATA AGE NAME TYPE DATA AGE
db-user-pass Opaque 2 51s db-user-pass Opaque 2 51s
``` ```
You can view a description of the `Secret`: Você pode ver a descrição do `Secret`:
```shell ```shell
kubectl describe secrets/db-user-pass kubectl describe secrets/db-user-pass
``` ```
A saída deve ser similar a:
The output is similar to:
``` ```
Name: db-user-pass Name: db-user-pass
@@ -109,39 +105,39 @@ password: 12 bytes
username: 5 bytes username: 5 bytes
``` ```
The commands `kubectl get` and `kubectl describe` avoid showing the contents Os comandos `kubectl get` e `kubectl describe` omitem o conteúdo de um `Secret` por padrão.
of a `Secret` by default. This is to protect the `Secret` from being exposed Isso para proteger o `Secret` de ser exposto acidentalmente para uma pessoa não autorizada,
accidentally to an onlooker, or from being stored in a terminal log. ou ser armazenado em um log de terminal.
## Decoding the Secret {#decoding-secret} ## Decodificando o Secret {#decoding-secret}
To view the contents of the Secret you created, run the following command: Para ver o conteúdo de um Secret que você criou, execute o seguinte comando:
```shell ```shell
kubectl get secret db-user-pass -o jsonpath='{.data}' kubectl get secret db-user-pass -o jsonpath='{.data}'
``` ```
The output is similar to: A saída deve ser similar a:
```json ```json
{"password":"MWYyZDFlMmU2N2Rm","username":"YWRtaW4="} {"password":"MWYyZDFlMmU2N2Rm","username":"YWRtaW4="}
``` ```
Now you can decode the `password` data: Agora, você pode decodificar os dados de `password`:
```shell ```shell
echo 'MWYyZDFlMmU2N2Rm' | base64 --decode echo 'MWYyZDFlMmU2N2Rm' | base64 --decode
``` ```
The output is similar to: A saída deve ser similar a:
``` ```
1f2d1e2e67df 1f2d1e2e67df
``` ```
## Clean Up ## Limpeza
To delete the Secret you have created: Para apagar o Secret que você criou:
```shell ```shell
kubectl delete secret db-user-pass kubectl delete secret db-user-pass
@@ -151,6 +147,6 @@ kubectl delete secret db-user-pass
## {{% heading "whatsnext" %}} ## {{% heading "whatsnext" %}}
- Read more about the [Secret concept](/docs/concepts/configuration/secret/) - Leia mais sobre o [conceito do Secret](/docs/concepts/configuration/secret/)
- Learn how to [manage Secret using config file](/docs/tasks/configmap-secret/managing-secret-using-config-file/) - Leia sobre como [gerenciar Secret com o comando `kubectl`](/docs/tasks/configmap-secret/managing-secret-using-kubectl/)
- Learn how to [manage Secret using kustomize](/docs/tasks/configmap-secret/managing-secret-using-kustomize/) - Leia sobre como [gerenciar Secret usando kustomize](/docs/tasks/configmap-secret/managing-secret-using-kustomize/)
@@ -17,12 +17,11 @@ de um diretório. Depois de gerar o Secret, você pode criar o Secret na API ser
<!-- steps --> <!-- steps -->
## Create the Kustomization file ## Criando um arquivo de Kustomization
Você pode criar um Secret definindo um `secretGenerator` em um
You can generate a Secret by defining a `secretGenerator` in a arquivo `kustomization.yaml` que referencia outros arquivos existentes.
`kustomization.yaml` file that references other existing files. Por exemplo, o seguinte arquivo kustomization referencia os
For example, the following kustomization file references the arquivos `./username.txt` e `./password.txt`:
`./username.txt` and the `./password.txt` files:
```yaml ```yaml
secretGenerator: secretGenerator:
@@ -32,10 +31,10 @@ secretGenerator:
- password.txt - password.txt
``` ```
You can also define the `secretGenerator` in the `kustomization.yaml` Você também pode definir o `secretGenerator`no arquivo `kustomization.yaml`
file by providing some literals. por meio de alguns *literais*.
For example, the following `kustomization.yaml` file contains two literals Por exemplo, o seguinte arquivo `kustomization.yaml` contém dois literais
for `username` and `password` respectively: para `username` e `password` respectivamente:
```yaml ```yaml
secretGenerator: secretGenerator:
@@ -45,48 +44,47 @@ secretGenerator:
- password=1f2d1e2e67df - password=1f2d1e2e67df
``` ```
Note that in both cases, you don't need to base64 encode the values. Observe que nos dois casos, você não precisa codificar os valores em base64.
## Create the Secret ## Criando o Secret
Apply the directory containing the `kustomization.yaml` to create the Secret. Aplique o diretório que contém o arquivo `kustomization.yaml` para criar o Secret.
```shell ```shell
kubectl apply -k . kubectl apply -k .
``` ```
The output is similar to: A saída deve ser similar a:
``` ```
secret/db-user-pass-96mffmfh4k created secret/db-user-pass-96mffmfh4k created
``` ```
Note that when a Secret is generated, the Secret name is created by hashing Observe que quando um Secret é gerado, o nome do segredo é criado usando o hash
the Secret data and appending the hash value to the name. This ensures that dos dados do Secret mais o valor do hash. Isso garante que
a new Secret is generated each time the data is modified. um novo Secret é gerado cada vez que os dados são modificados.
## Check the Secret created ## Verifique o Secret criado
You can check that the secret was created: Você pode verificar que o secret foi criado:
```shell ```shell
kubectl get secrets kubectl get secrets
``` ```
The output is similar to: A saída deve ser similar a:
``` ```
NAME TYPE DATA AGE NAME TYPE DATA AGE
db-user-pass-96mffmfh4k Opaque 2 51s db-user-pass-96mffmfh4k Opaque 2 51s
``` ```
You can view a description of the secret: Você pode ver a descrição de um secret:
```shell ```shell
kubectl describe secrets/db-user-pass-96mffmfh4k kubectl describe secrets/db-user-pass-96mffmfh4k
``` ```
A saída deve ser similar a:
The output is similar to:
``` ```
Name: db-user-pass-96mffmfh4k Name: db-user-pass-96mffmfh4k
@@ -102,15 +100,14 @@ password.txt: 12 bytes
username.txt: 5 bytes username.txt: 5 bytes
``` ```
The commands `kubectl get` and `kubectl describe` avoid showing the contents of a `Secret` by Os comandos `kubectl get` e `kubectl describe` omitem o conteúdo de um `Secret` por padrão.
default. This is to protect the `Secret` from being exposed accidentally to an onlooker, Isso para proteger o `Secret` de ser exposto acidentalmente para uma pessoa não autorizada,
or from being stored in a terminal log. ou ser armazenado em um log de terminal.
To check the actual content of the encoded data, please refer to Para verificar o conteúdo atual de um dado codificado, veja [decodificando secret](/docs/tasks/configmap-secret/managing-secret-using-kubectl/#decoding-secret).
[decoding secret](/docs/tasks/configmap-secret/managing-secret-using-kubectl/#decoding-secret).
## Clean Up ## Limpeza
To delete the Secret you have created: Para apagar o Secret que você criou:
```shell ```shell
kubectl delete secret db-user-pass-96mffmfh4k kubectl delete secret db-user-pass-96mffmfh4k
@@ -119,7 +116,7 @@ kubectl delete secret db-user-pass-96mffmfh4k
<!-- Optional section; add links to information related to this topic. --> <!-- Optional section; add links to information related to this topic. -->
## {{% heading "whatsnext" %}} ## {{% heading "whatsnext" %}}
- Read more about the [Secret concept](/docs/concepts/configuration/secret/) - Leia mais sobre o [conceito do Secret](/docs/concepts/configuration/secret/)
- Learn how to [manage Secret with the `kubectl` command](/docs/tasks/configmap-secret/managing-secret-using-kubectl/) - Leia sobre como [gerenciar Secret com o comando `kubectl`](/docs/tasks/configmap-secret/managing-secret-using-kubectl/)
- Learn how to [manage Secret using config file](/docs/tasks/configmap-secret/managing-secret-using-config-file/) - Leia sobre como [gerenciar Secret usando kustomize](/docs/tasks/configmap-secret/managing-secret-using-kustomize/)