Kubernetes Secrets are objects designed to store and manage sensitive information required by applications running in a cluster. This includes credentials such as passwords, OAuth tokens, SSH keys, TLS certificates, and other confidential data that should not be embedded directly in application code or container images.

Secrets provide a native mechanism for decoupling sensitive data from application logic. By abstracting credentials into dedicated Kubernetes objects, teams can reduce the risk of accidental exposure, simplify credential rotation, and follow the principle of least privilege when granting access to protected resources.

Why are Kubernetes Secrets Important?

In a distributed, containerized environment, workloads are ephemeral by design. Pods can be created, destroyed, rescheduled, or scaled at any time, often across different nodes. Hardcoding credentials into images or application binaries is both unsafe and incompatible with this execution model.

Kubernetes Secrets support least-privilege designs (when paired with RBAC and careful ServiceAccount scoping).. Essentially, Kubernetes Secrets are placeholders for sensitive information like credentials, tokens, and certificates, a mechanism for abstracting them. Kubernetes Secrets act as separate objects – Pods consume Secrets via environment variables or mounted/projected volumes, providing credentials to the application for access to external resources. Separately, imagePullSecrets can be used by the kubelet to authenticate when pulling private images.

How Does Kubernetes Leverage Secrets?

Kubernetes exposes Secrets are first-class API resources. Each Secret consists of a set of key-value pairs, where values are base-64 encoded and stored in etcd. When creating a Secret, its purpose can be specified by defining the type field in the Secret manifest or via an equivalent kubectl command. 

The secret type informs Kubernetes and related tooling how the data is expected to be used. Some types are validated by the API server to ensure that required keys are present, while others are opaque and left entirely to the application. 

Secrets can be consumed by Pods in several ways, including volume mounts and environment variables. Kubernetes ensures that Secrets are only made available to Pods that explicitly reference them, helping prevent accidental exposure.

What are the different ways to create K8s Secrets?

Kubernetes offers several methods for creating Secrets depending on your workflow and automation needs:

Using kubectl create secret

Create a Secret directly from literal values or files:

kubectl create secret generic mysecret \

  --from-literal=username=admin \

  --from-literal=password=1f2d1e2e67df
  1. From files using kubectl create secret

    Useful for injecting credentials or certificates stored as files:

    kubectl create secret generic db-creds \
      --from-file=username.txt \
      --from-file=password.txt
  2. From a config file

    Define a Secret in YAML or JSON using the data or stringData field and apply it with:

    kubectl apply -f mysecret.yaml
  3. Using Kustomize

    Generate Secrets from files via a secretGenerator in a kustomization.yaml :

    secretGenerator:
      - name: db-user-pass
        files:
          - username.txt
          - password.txt

    Then apply with:

    kubectl apply -k .
  4. Creating a TLS Secret For HTTPS or Ingress use cases:

    kubectl create secret tls my-tls-secret \
      --cert=path/to/tls.crt \
      --key=path/to/tls.key

These methods support a wide range of use cases—from local development to production GitOps pipelines—while aligning with best practices for Kubernetes Secret management.

How is a Kubernetes Secret created using kubectl?

Kubernetes provides a range of tools and techniques for managing Secrets effectively at scale. Whether you're securing service credentials or API tokens, how you manage these objects will influence the security and stability of your workloads. Managing Secrets includes creating, viewing, updating, and rotating them over time.

Secrets can be managed manually using kubectl, declaratively with configuration files, or through GitOps-style workflows using tools like Kustomize. You can also integrate external secret management systems for centralized control and compliance.

Using tools like kubectl get secret, you can retrieve individual Secret objects, while commands like kubectl list secrets let you see all available Secrets in a given namespace. These tools help platform engineers and DevOps teams audit, troubleshoot, and validate that Secrets are configured as expected.

To create a Secret via kubectl, you’re going to want to first create a text file to store the contents of your Secret, in this case a username.txt and password.txt:

echo -n 'admin' > ./username.txt
echo -n '1f2d1e2e67df' > ./password.txt

Then you’ll want to leverage the kubectl create secret to package these files into a Secret, with the final command looking like this:

kubectl create secret generic db-user-pass \
  --from-file=./username.txt \
  --from-file=./password.txt

The output should look like this:

secret/db-user-pass created

How is a Kubernetes Secret created from a config file?

You can create a Kubernetes Secret from a YAML or JSON config file by defining the apiVersion, kind, metadata, and data or stringData fields. The data field must contain base64-encoded values, while stringData accepts plain text and is easier for human editing.

You can also store your secure data in a JSON or YAML file and create a Secret object from that. The Secret resource contains two distinct maps:

  • data: used to store arbitrary data, encoded using base64

  • stringData: allows you to provide Secret data as unencoded strings

The keys of data and stringData must consist of alphanumeric characters, ‘-’ (dash), ‘_’ (underscore), or ‘.’ (period).

For example, to store two strings in a Secret using the data field, you can convert the strings to base64 as follows:

echo -n 'admin' | base64

The output should look like this:

YWRtaW4=

And for the next one:

echo -n '1f2d1e2e67df' | base64

The output should look similar to:

MWYyZDFlMmU2N2Rm

You can then write a secret config that looks like this:

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  username: YWRtaW4=
  password: MWYyZDFlMmU2N2Rm

How is a Kubernetes Secret created using kustomize?

You can also generate a Secret object by defining a secretGenerator in a kustomization.yaml file that references other existing files. For example, the following kustomization file references the ./username.txt and the ./password.txt files, for example:

secretGenerator:
- name: db-user-pass
  files:
  - username.txt
  - password.txt

Then apply the directory containing the kustomization.yaml to create the Secret:

kubectl apply -k .

The output should look similar to this:

secret/db-user-pass-96mffmfh4k created

How is a Kubernetes Secret edited?

You can edit an existing Secret with the following command:

kubectl edit secrets mysecret

This command opens the default configured editor and allows for updating the base64 encoded Secret values in the data field:

  # Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
data:
  username: YWRtaW4=
  password: MWYyZDFlMmU2N2Rm
kind: Secret
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: { ... }
  creationTimestamp: 2016-01-22T18:41:56Z
  name: mysecret
  namespace: default
  resourceVersion: "164619"
  uid: cfee02d6-c137-11e5-8d73-42010af00002
type: Opaque

How are Kubernetes Secrets used?

Secrets can be used in a variety of ways, such as being mounted as data volumes or exposed as environment variables to be used by a container in a Pod. Secrets can also be used by other parts of the system, without being directly exposed to the Pod. For example, Secrets can hold credentials that other parts of the system should use to interact with external systems on your behalf.

How can Kubernetes Secrets be used as environment variables in a Pod?

To use a secret in an environment variable in a Pod, you’ll want to:

  1. Create a secret or use an existing one. Multiple Pods can reference the same secret.

    1. Modify your Pod definition in each container that you wish to consume the value of a Secret key to add an environment variable for each Secret key you wish to consume. The environment variable that consumes the Secret key should populate the Secret’s name and key in  env[].valueFrom.secretKeyRef.

  2. Modify your image and/or command line so that the program looks for values in the specified environment variables.

This is an example of a Pod that uses secrets from environment variables:

apiVersion: v1
kind: Pod
metadata:
  name: secret-env-pod
spec:
  containers:
  - name: mycontainer
    image: redis
    env:
      - name: SECRET_USERNAME
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: username
      - name: SECRET_PASSWORD
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: password
  restartPolicy: Never


How to manage Kubernetes secrets

Managing Kubernetes Secrets effectively involves creating, storing, updating, and securing sensitive data throughout the lifecycle of your workloads. Secrets can be created using kubectl create secret, defined declaratively in YAML files, or generated automatically using tools like Kustomize or GitOps pipelines. You can view and audit secrets with kubectl get secret or kubectl describe secrets, and update them manually using kubectl edit secret or by reapplying updated configurations. Best practices for managing Secrets include encrypting them at rest, enforcing role-based access controls, rotating credentials regularly, and using external secret management systems when needed. Whether you're injecting Secrets as environment variables via secretKeyRef or mounting them into pods as volumes, Kubernetes offers flexible options to securely handle sensitive data at scale.

What are external Kubernetes secrets?

External Kubernetes Secrets refer to a pattern where sensitive data such as passwords, API tokens, or certificates are managed outside the Kubernetes cluster and synced into it when needed. Rather than storing credentials directly in the cluster via native Secret objects, external Secrets leverage third-party providers like HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, or Google Secret Manager to store and manage sensitive information securely.

This approach offers several benefits:

  • Centralized secret management across multiple clusters and environments

  • Improved compliance with organizational or regulatory policies

  • Fine-grained access controls outside of standard Kubernetes RBAC

  • Automatic secret rotation without manual intervention

To integrate external secrets into Kubernetes, the Kubernetes Secrets Store CSI Driver is commonly used. CSI Driver mounts secrets at runtime without storing them in etcd (unless you enable syncing to Kubernetes Secret objects). If you sync, you can then use secretKeyRef; if you don’t, you consume via the mounted files.. These secrets are mounted at runtime and kept out of the cluster's permanent storage, which aligns with best practices for least-privilege access and ephemeral secrets usage.

This model also supports kubernetes secretKeyRef indirectly, where once synced, the secrets can be exposed to applications via environment variables or volumes in the same way as native Kubernetes Secrets.

For teams managing secrets at enterprise scale or across hybrid/multi-cloud environments, using external Kubernetes secrets is a critical step in achieving secure, policy-driven, and auditable secret management.


What are immutable Kubernetes Secrets, and what are the benefits?

Kubernetes supports marking Secrets as immutable, preventing their data from being modified after creation. This feature is particularly useful for clusters that manage a large number of Secrets or where stability and predictability are critical. 

Immutable Secrets provides two primary benefits:

  • Improved safety by preventing accidental or unauthorized updates that could break running workloads

  • Better performance by reducing the number of API servers watches and updates required for Secret objects at scale

For clusters with tens of thousands of Secret-to-Pod mounts, immutability can significantly reduce the load on the kube-apiserver.

How are immutable Kubernetes Secrets created?

Kubernetes provides an option to mark Secrets as immutable by setting the immutable field to true. This feature has been enabled by default since Kubernetes 1.19 and prevents updates to Secret data after creation.

For example:

apiVersion: v1
kind: Secret
metadata:
  ...
data:
  ...
immutable: true


What are the built-in types of Kubernetes Secrets?

Kubernetes includes several built-in Secret types to support common authentication and configuration scenarios:

  • Opaque: The default type, used for arbitrary key-value pairs

  • Service Account Token: Stores tokens that authenticate Pods to the Kubernetes API

  • Docker Config: Holds credentials for authenticating to container registries

  • Basic Authentication: Stores username and password pairs

  • SSH Authentication: used for SSH private keys

  • TLS: Stores TLS certificates and private keys for secure communication

  • Bootstrap Token: Supports node bootstrap and cluster join operations

Using a specific Secret type helps Kubernetes validate required fields and improves interoperability with controllers, tooling, and platform integrations.

What are the limitations of Kubernetes Secrets?

While Kubernetes Secrets are a foundational security mechanism, they are not a complete security solution on their own. By default, Secret data is stored unencrypted in etcd and is only base64-encoded, not encrypted. 

Once a Secret is injected into a container as an environment variable or file, the data is accessible to any process within that container. This creates a risk if the container is compromised, since a single vulnerability can expose all Secrets. 

This means that Secrets should always be used alongside additional controls such as encryption at rest, strict RBAC policies, audit logging, or even external secrets management systems.

What are some best practices for maintaining and increasing the security of Kubernetes secrets?

To strengthen secret security in production environments, teams should keep the following best practices in mind:

Encrypt Secret data at rest

By default, etcd stores Kubernetes Secrets unencrypted. Enable at-rest encryption for your Secret objects, including the key-value data they contain.

Implement least-privilege access to Secrets

Follow RBAC best practices and only assign minimal rights to users and service accounts. Only allow the most privileged, system-level components to access watch or list, and only the components that require get access for Secrets to execute their normal functions should have it.

As for humans, only cluster admins should have access to etcd, and get, watch, and list access (including read-only access) to Secrets should be restricted. Third-party authorization solutions can provide more robust access control, such as restricting access to Secrets that have certain annotations.

Use annotations to enforce specific rules for Secret management

By annotating a ServiceAccount with kubernetes.io/enforce-mountable-secrets set to true, Kubernetes enforces specific rules for Pods running as this ServiceAccount, that require the ServiceAccount’s secrets field to include Secrets mounted as volumes as well as Secrets referenced in envFrom for containers. Additionally, the ServiceAccount’s imagePullSecrets field must include Secrets referenced in a Pod’s imagePullSecrets. These rules are enforced whenever a Pod is created or updated.

Strengthen etcd management policies

Any durable storage used by etcd that is no longer needed should be wiped or shredded. For deployments with multiple etc instances, protect Secret data in transit by encrypting SSL/TLS communication between the instances.

Use 3rd-party Secrets store providers

Keep confidential credentials and other sensitive data outside your cluster by using external Secrets store providers that Pods can access. These solutions leverage the Kubernetes Secrets Store CSI Driver.


Kubernetes secrets use cases

Kubernetes Secrets are a foundational part of secure application deployment and platform automation. They provide a flexible, built-in mechanism for managing sensitive data that needs to be accessed by applications, infrastructure components, and CI/CD pipelines within a Kubernetes environment.

Here are some of the most common use cases for Kubernetes Secrets:

  1. Storing application credentials

    Store database usernames and passwords, API tokens, or third-party service keys as Secrets. These can be injected into containers as environment variables using secretKeyRef, or mounted as files in a volume. This pattern is widely used when integrating apps with databases or cloud services in a secure, repeatable way.

  2. TLS termination for Ingress

    With kubectl create secret tls, you can store TLS private keys and certificates for use in Ingress controllers. This allows for secure HTTPS communication to your services without embedding sensitive credentials in your configurations.

    kubectl create secret tls my-tls-secret \
      --cert=./tls.crt \
      --key=./tls.key
  3. Authenticating to container registries

    Use Secrets to store Docker registry credentials and access private container images securely. These Secrets can be referenced in a Pod's imagePullSecrets field and managed using kubectl or declarative YAML.

  4. Dynamic secrets via external providers

    When used with external secrets management tools, Kubernetes Secrets enable dynamic credential injection into Pods without persisting data in etcd. This pattern is ideal for organizations enforcing compliance with zero trust and audit-friendly infrastructure policies.

  5. Configuration across environments

    By using different Secrets for dev, staging, and production environments, teams can abstract away environment-specific data without changing application code. Updating a Secret with kubernetes update secret can trigger redeployments that automatically pick up new credentials.

  6. Secure environment variable injection

    For applications that rely on environment-level configuration, Secrets allow injecting runtime values securely. This is commonly seen in microservices that need to pass secure tokens or API keys between services. These values are typically defined using the kubernetes environment variables from secret pattern in a Pod spec.

  7. CI/CD and GitOps pipelines

    Secrets play a key role in build and deployment pipelines. Whether authenticating to artifact repositories or signing images, Secrets can be used securely and programmatically via kubectl create secret, kubectl get secret, or through GitOps tools like ArgoCD or Flux.

How are Kubernetes Secrets managed using Lens Desktop?

Lens Desktop makes it easy to create Kubernetes Secrets for a cluster using a dialog menu. Simply enter the parameters, and click Create.

After creating Kubernetes Secrets, you can view, filter, and search through a table of Secrets for each cluster and click on each item to view further details, edit, or delete it.

Simplifying Kubernetes Secrets management with Mirantis

Managing Kubernetes Secrets effectively requires visibility, precision, and confidence. As clusters grow and environments multiply, interacting with Secrets purely through CLI commands and YAML files can slow teams down and increase the risk of a misconfiguration. Lens, the Mirantis Kubernetes IDE, provides a more intuitive way to manage Secrets. With Lens, simply enter the parameters and click Create; after creating Kubernetes Secrets, you can view, filter, and search through a table of Secrets for each cluster and click on each item to view further details, edit, or delete it.

Key capabilities include:

  • Visual Secret Management: Create and manage Kubernetes Secrets through a guided UI that reduces YAML errors and simplifies day-to-day operations

  • Improved Visibility and Auditability: Quickly search, filter, and inspect Secrets across clusters and namespaces to understand configuration state and usage

  • Safer Day-to-Day Operations: reduce the risk of accidental misconfiguration by managing Secrets in context, alongside Pods, Deployments, and Services

Download Lens today and explore how Mirantis helps teams streamline Kubernetes Secrets management.

FREE EBOOK

Learn Kubernetes 5 Minutes at a Time

A hands-on introduction to Kubernetes for developers

DOWNLOAD NOW