# 创建Secret

## 使用Kubectl命令行创建Secret

假设有些Pod需要访问数据库，可以将账户、密码存储在**username.txt**和**password.txt**文件中，然后以文件的形式创建Secret供Pod使用。

首先创建账户信息文件：

```bash
echo -n "admin" > username.txt
echo -n "123456" > password.txt
```

然后以文件**username.txt**和**password.txt**创建Secret，创建方式和ConfigMap一致：

{% code overflow="wrap" %}

```properties
$ kubectl create secret generic db-user-pass --from-file=password.txt --from-file=username.txt
secret/db-user-pass created
```

{% endcode %}

查看Secret：

```properties
$ kubectl get secret db-user-pass -o yaml
apiVersion: v1
data:
  password.txt: MTIzNDU2
  username.txt: YWRtaW4=
kind: Secret
metadata:
  creationTimestamp: "2023-11-29T08:17:54Z"
  name: db-user-pass
  namespace: default
  resourceVersion: "163805"
  uid: 889c6503-86d4-417c-8452-a809a3a44ff9
type: Opaque
```

<mark style="color:blue;">**默认情况下，get和describe命令都不会显示文件的内容，这是为了防止Secret中的内容被意外暴露。**</mark>

## 通过YAML文件创建Secret

<mark style="color:orange;">**手动创建Secret时，每一项内容必须是base64编码的，所以要先对明文内容进行编码：**</mark>

```bash
$ echo -n 'admin' | base64
YWRtaW4=

$ echo -n '123456' | base64
MTIzNDU2
```

然后创建一个YAML文件，格式如下：

<details>

<summary>db-user-pass.yaml</summary>

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: db-user-pass-yaml
type: Opaque
data:
  username: YWRtaW4=
  password: MTIzNDU2
```

</details>

```properties
$ kubectl get secret db-user-pass-yaml -o yaml
apiVersion: v1
data:
  password: MTIzNDU2
  username: YWRtaW4=
kind: Secret
metadata:
  creationTimestamp: "2023-11-29T08:24:34Z"
  name: db-user-pass-yaml
  namespace: default
  resourceVersion: "164645"
  uid: ce6fa2fc-b05a-4b2f-9a4f-9879702d2b7f
type: Opaque
```

## 解码Secret

<mark style="color:blue;">**Secret被创建后，会以加密的方式存储于Kubernetes集群中**</mark>，可以对其进行解码并查看内容：

首先以YAML的形式获取刚才创建的Secret：

```properties
$ kubectl get secret db-user-pass-yaml -o yaml
apiVersion: v1
data:
  password: MTIzNDU2
  username: YWRtaW4=
kind: Secret
metadata:
  creationTimestamp: "2023-11-29T08:24:34Z"
  name: db-user-pass-yaml
  namespace: default
  resourceVersion: "164645"
  uid: ce6fa2fc-b05a-4b2f-9a4f-9879702d2b7f
type: Opaque
```

然后**通过base64的--decode参数或-d参数解码**即可：

```bash
$ echo "MTIzNDU2" | base64 --decode
123456
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bohans.gitbook.io/devops/kubernetes/ji-chu-zhi-shi/kubernetes-pei-zhi-guan-li/secret/chuang-jian-secret.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
