# Secret

## [About](https://kubernetes.io/docs/reference/kubernetes-api/config-and-storage-resources/secret-v1/)

A **Secret** in Kubernetes stores **confidential data** (in key-value pairs).

They allow you to:

* Keep sensitive info **out of Pod specs** and **Docker images**.
* Inject secrets into Pods securely (as env vars or mounted files).

## Types of Secrets

* **Opaque** (default) → generic key-value secrets
* **docker-registry** → for private container registry credentials
* **tls** → for SSL certificates
* **service-account-token** → automatically created for service accounts

{% hint style="danger" %}
By default, Secrets are just **base64-encoded** → not real encryption.

To protect Secrets in production:

1. Enable **encryption at rest** in the cluster.
2. Use **RBAC** to restrict access (`kubectl get secret` should not be open to all).
3. Consider external secret managers (Vault, AWS Secrets Manager, GCP Secret Manager, Azure Key Vault).
   {% endhint %}

{% hint style="warning" %}
Inside the Pod, secrets ends up as regular decoded Environment variables.
{% endhint %}

## Commands

Create Secret from literal values:

```bash
kubectl create secret generic <secret-name> \
  --from-literal=db_password=123456\
  --from-literal=api_key=abcd1234
```

Create Secret from a file:

```bash
kubectl create secret generic <secret-name> --from-file=cert.pem
```

## Example

{% hint style="success" %}
You must **base64 encode values** when defining Secrets in YAML.

Ex.: `echo -n "123456" | base64`
{% endhint %}

{% code title="secret.yaml" %}

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
data:
  db_password: MTIzNDU2   # "123456" base64 encoded
  api_key: YWJjZDEyMzQ=   # "abcd1234" base64 encoded
```

{% endcode %}

How to use in Deployment example 1 (Individual env variables):

{% code title="deployment.yaml" %}

```yaml
...
spec:
  template:
    ...
    spec:
      containers:
        - name: myapp-container
          image: nginx:1.25
          ports:
            - containerPort: 80
          env:
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysecret   # name of the Secret
                  key: db_password
```

{% endcode %}

How to use in Deployment example 2 (Injected as a volume):

{% code title="deployment.yaml" %}

```yaml
...
spec:
  template:
    ...
    spec:
      containers:
        - name: myapp-container
          image: nginx:1.25
          ports:
            - containerPort: 80
          volumeMounts:
            - mountPath: /etc/secret
              name: secret-volume
              readOnly: true
      volumes:
        - name: secret-volume
          secret:
            secretName: mysecret
```

{% endcode %}

> This will mount files inside `/etc/secret/db_user` and `/etc/secret/db_pass`.
