<img src="https://ws.zoominfo.com/pixel/6169bf9791429100154fc0a2" width="1" height="1" style="display: none;">

Want to master Kubernetes access control? 🚀 Join our upcoming webinar!

Search
Close icon
Search bar icon

Kubernetes Secrets: Create, Manage, and Secure k8s Secrets

StrongDM manages and audits access to infrastructure.
  • Role-based, attribute-based, & just-in-time access to infrastructure
  • Connect any person or service to any infrastructure, anywhere
  • Logging like you've never seen

Kubernetes Secrets provide a secure way to manage sensitive data like API keys, passwords, and TLS certificates. This guide will help you securely manage Kubernetes Secrets, minimize security risks, and ensure compliance with best practices.

Key Takeaways

  • Kubernetes Secrets securely store sensitive data like passwords, API keys, and TLS certificates, offering better protection than ConfigMaps.
  • Types of Secrets include Opaque (default), TLS, docker-registry, basic-auth, and ssh-auth, each serving specific security needs.
  • Security & Structure: Data is stored in base64 but requires encryption and RBAC policies for true security.
  • Secret Management: Secrets can be created using kubectl, stored in YAML, or mounted as environment variables.
  • Best Practices: Use namespace isolation, automate secret rotation, and enforce access control policies.

What Is a Kubernetes Secret?

Kubernetes Secret is a Kubernetes object that securely stores and manages sensitive information such as passwords, API keys, and TLS certificates. Unlike ConfigMaps, Secrets keep data encoded in base64 and can be encrypted at rest, ensuring better security for confidential data within a cluster.

Types of Kubernetes Secrets

Kubernetes supports several built-in secret types, each designed for specific use cases in your infrastructure. The most common types include:

  • Opaque Secrets: The default type for storing arbitrary user-defined data like passwords and API keys
  • docker-registry: Used for storing credentials for container registry authentication
  • tls: Holds TLS certificates and associated private keys for secure communication
  • basic-auth: Stores credentials needed for basic authentication, containing username and password fields
  • ssh-auth: Manages SSH credentials for remote access to resources

When you create a secret using kubectl, you must specify the appropriate type to ensure proper validation and handling of your sensitive data. For example, using a tls type secret automatically validates the presence of required certificate files and keys.

Understanding Secret Data Structure

The data structure of a Secret follows a consistent format in the Kubernetes API server. Every Secret object contains mandatory fields like apiVersion and metadata, along with a data field that stores the actual sensitive information. When you create a new secret, the data is automatically encoded into base64 format for basic security through obscurity.

The stringData field provides a more convenient way to work with Secret values, allowing you to input plain text that Kubernetes automatically converts to base64. This field is particularly useful when creating Secrets through configuration files, as it eliminates the need for manual encoding.

For enhanced security, the API server enables encryption at rest, ensuring your sensitive data remains protected in the etcd storage. Each key-value pair within a Secret can hold up to 1MB of data, making Secrets suitable for storing certificates, tokens, and other authentication credentials.

Opaque Secrets vs Other Types

While Opaque serves as the default secret type, understanding when to use specialized types can strengthen your security architecture. When you create a secret using the generic subcommand in kubectl, you're working with Opaque secrets - perfect for storing arbitrary key-value pairs without structural constraints.

Specialized types like TLS secrets provide built-in validation to ensure your certificates and keys meet specific format requirements. Basic-auth secrets enforce username and password field validation, preventing configuration errors that could impact authentication. Docker-registry secrets specifically structure your container registry credentials, making them easier to manage across multiple deployments.

Your choice between Opaque and specialized types depends on your security needs. Use Opaque when flexibility matters most, but prefer specialized types when you need format validation and standardized structure across your organization.

Core Components of Kubernetes Secrets

Secret Namespace Management

Namespaces provide logical boundaries for your Kubernetes secrets, restricting access to sensitive data within specific cluster segments. By default, secrets exist only in the namespace where you create them, preventing unauthorized access from other namespaces.

đź’ˇMake it easy: StrongDM enhances this isolation by managing secret access across multiple namespaces through centralized controls. Teams can define granular permissions and maintain separate development, staging, and production environments without compromising security.

For mission-critical applications, you can implement namespace-level resource quotas to prevent memory exhaustion from excessive secret creation. This approach ensures robust secret management while maintaining system performance across your Kubernetes infrastructure.

Service Account Integration

Service account integration with Kubernetes secrets enhances authentication workflows between applications and cluster resources. When you configure service account tokens, StrongDM ensures secure access while maintaining strict control over credential distribution. This approach prevents exposure of sensitive information during the authentication process.

Modern Kubernetes deployments no longer automatically generate secrets for service accounts, requiring explicit creation and management.

đź’ˇMake it easy: StrongDM simplifies this process by providing centralized control over service account tokens and their associated secrets, enabling seamless integration with your existing authentication mechanisms.

By leveraging projected volumes for service account tokens, your applications receive automatically invalidated credentials upon pod deletion, reducing the risk of compromised tokens. This dynamic token management strengthens your security posture while maintaining operational efficiency across your Kubernetes environment.

Base64 Encoding in Secrets

When working with Kubernetes Secrets, your sensitive data undergoes base64 encoding before storage in the cluster's etcd database. The encoding process converts binary data into ASCII text format, making it suitable for transmission and storage. Running echo -n 'your-secret' | base64 transforms plain text into encoded format, while the -n flag prevents unwanted newline characters from affecting the output.

đź’ˇMake it easy: StrongDM streamlines this process by handling the encoding automatically.

Base64 encoding serves as a data format standardization rather than an encryption method - your secrets require proper RBAC rules and encryption at rest for genuine security. For enhanced protection, consider using the stringData field in your secret manifests, allowing you to input plain text that Kubernetes automatically encodes.

Creating Secrets Using kubectl Command Line

Generic Secret Creation Methods

Creating generic secrets in Kubernetes offers multiple approaches to match your workflow needs. The kubectl create secret generic command serves as your primary tool for establishing new secrets, whether you're working with individual values or multiple credentials.

You can generate secrets from literal values for quick deployment, files for structured data, or entire directories for bulk secret management. For teams managing multiple environments, combining these methods allows for flexible secret creation - for example, using literal values for development credentials while loading production secrets from encrypted files.

When choosing your secret creation method, consider your deployment pipeline requirements and how secrets will be consumed by pods. This approach ensures consistent secret management across your Kubernetes infrastructure while maintaining security best practices.

Creating Secrets from Literal Values

The kubectl create secret generic command provides a straightforward method for passing sensitive data directly through environment variables. For example:

kubectl create secret generic db-credentials --from-literal=username=admin --from-literal=password=mysecret

This creates a secret named "db-credentials" with two key-value pairs. While convenient for testing, remember that shell history can expose these values.

đź’ˇMake it easy: StrongDM mitigates this risk by handling secret creation through secure channels that bypass shell history storage.

For multiple key-value pairs, you can chain the --from-literal flag as needed, each containing a separate piece of sensitive information. The secret demo-secret becomes immediately available for pod specifications and volume mounts after creation.

Using Files to Generate Secrets

Working with sensitive data stored in files provides a more secure approach to secret management than command-line literals. You can generate secrets from individual files using the --from-file flag, which maintains the content's integrity without exposing values in shell history. For example:

kubectl create secret generic my-certs --from-file=./tls.key --from-file=./tls.crt

When generating secrets from files, Kubernetes uses the filename as the default key in your secret. To specify a custom key name, use the key=source format: --from-file=custom-key=./mysecret.txt. Remember to ensure your input files don't contain extra newline characters, as these affect the final encoded value.

Directory-Based Secret Creation

Managing multiple secrets through directory-based creation streamlines the deployment process for teams handling numerous credentials or certificates. When you point kubectl to a directory, it automatically packages each file as a separate key-value pair in the secret, using filenames as keys:

kubectl create secret generic bulk-certs --from-file=/path/to/certs/directory

The directory approach proves particularly valuable for TLS certificate management and API key organization. Regular files become secret entries, while subdirectories and symbolic links are excluded from the packaging process. This built-in filtering ensures your secrets remain clean and properly structured.

You can combine directory-based creation with custom key mapping to maintain consistent naming across environments: --from-file=custom-key=/path/to/directory/secret.txt. This flexibility allows teams to standardize secret structures while leveraging the efficiency of bulk operations.

Working with YAML Files for Secrets

Secret YAML File Structure

Kubernetes Secret YAML manifests follow a standardized v1 kind structure that defines metadata, type, and data fields. The core configuration requires a unique name within your namespace and the appropriate secret type specification:

apiVersion: v1 kind: Secret meta name: mysecret type: Opaque username: dXNlcg== password: cGFzc3dvcmQ=

For unencoded values, the stringData field allows direct string input while maintaining privilege access to secrets. This approach proves particularly valuable when managing sensitive content through version control systems, as it eliminates the need for manual base64 encoding steps before deployment.

Config File Implementation

Configuration files streamline secret deployment through declarative specifications in your Kubernetes cluster. Create a secret manifest with apiVersion: v1 and specify the type: Opaque field for standard secrets. Your YAML configuration must include the data field with base64-encoded values or use stringData for automatic encoding:

kubectl apply -f secret.yaml deploys your configuration, while kubectl replace -f secret.yaml updates existing secrets. For secure secret management, mount these configurations as volumes in your pods and implement strict RBAC policies to control access.

đź’ˇMake it easy: StrongDM enhances this process by providing automated secret rotation and centralized access controls.

Environment Variable Configuration

Setting up environment variables through Kubernetes secrets provides secure access to sensitive data while maintaining container portability. Your pods can reference secret values directly through the valueFrom field in container specifications:

  • Individual Variable Mapping: Configure specific environment variables by referencing secret keys using secretKeyRef, allowing granular control over which values containers can access.
  • Bulk Secret Loading: Use envFrom with secretRef to load all key-value pairs from a secret as environment variables, streamlining configuration for applications requiring multiple credentials.

When mounting secrets as environment variables, consider the security implications. Unlike volume mounts, environment variables persist in container memory and may appear in crash logs.

đź’ˇMake it easy: StrongDM offers secure secret injection with automatic rotation capabilities.

Managing Docker Registry Secrets

Image Pull Secret Configuration

Private container registries require proper authentication for Kubernetes to pull images. The kubectl create secret docker-registry command establishes these credentials, creating a secret that your Kubelet uses during image retrieval operations.

Configure the secret with your registry's server address, username, password, and email: kubectl create secret docker-registry my-registry-secret --docker-server=REGISTRY_SERVER --docker-username=USER --docker-password=PASSWORD --docker-email=EMAIL.

For enhanced security across multiple namespaces, specify the target namespace during creation and implement strict RBAC policies to control secret access. Remember that each node in your cluster needs these credentials to pull private images on behalf of your pods, making proper secret distribution essential for seamless container deployment.

Docker Registry Authentication

Many organizations maintain multiple private registries across different environments, making secure authentication management critical. The Kubelet on each node requires proper credentials to pull images on behalf of your pods. Your authentication strategy should account for both initial setup and ongoing maintenance.

When pods need access to multiple registries, create separate docker-registry secrets for each one. This approach enables fine-grained control over which pods can access specific registries through imagePullSecrets settings in your pod specifications.

đź’ˇMake it easy: For secure integration with your existing infrastructure, StrongDM streamlines registry authentication by centralizing credential management and automating secret rotation. This reduces the risk of expired credentials causing deployment failures while maintaining strict access controls across your container ecosystem.

JSON Configuration for Registry Access

The secret-o jsonpath command reveals the JSON structure of your Docker registry credentials, providing a clear view of your authentication configuration. When examining the output, you'll find an auths object containing server-specific credentials in base64 format.

For teams managing multiple registries, create a consolidated JSON configuration file that includes all registry credentials:

{ "auths": { "registry.example.com": { "auth": "base64_encoded_credentials", "email": "user@example.com" } } }

Generate a Kubernetes secret directly from this file using kubectl create secret generic registry-auth --from-file=.dockerconfigjson=config.json --type=kubernetes.io/dockerconfigjson. This approach streamlines access management while maintaining your existing security protocols through StrongDM's centralized platform.

TLS Certificate Management in Secrets

Creating TLS Secrets

Transport Layer Security secrets require both a certificate and private key file for secure HTTPS connections in your Kubernetes cluster. To create a TLS secret, use the dedicated kubectl create secret tls command with your certificate and key files: kubectl create secret tls my-tls-secret --cert=path/to/tls.crt --key=path/to/tls.key.

Your public key certificate must be PEM-encoded and match the provided private key. When working with certificate chains, ensure proper order from leaf to intermediate to root certificates to prevent import errors. The resulting secret becomes available as type kubernetes.io/tls, making it ready for use in Ingress resources and other TLS-enabled services.

For specialized certificate configurations, consider using the stringData field in your YAML definitions to handle complex certificate chains while maintaining proper formatting.

Certificate File Requirements

Kubernetes validates specific formatting rules when you create TLS secrets. The public key certificate must be PEM-encoded in base64 DER format and match its corresponding private key. The certificate chain needs proper ordering, with your server certificate first, followed by any intermediate certificates, and the root CA certificate last.

When working with certificate bundles, verify the absence of extra newlines or whitespace that could corrupt the encoding. Your private key file should contain only the key material without additional headers or metadata.

đź’ˇMake it easy: StrongDM automates these validation checks, preventing common certificate configuration errors before they impact your production environment.

Managing Multiple Certificates

When your infrastructure spans across environments, managing multiple TLS certificates becomes a critical operational challenge. You can synchronize certificates across namespaces using tools like kubed or custom controllers that handle certificate distribution.

For production environments, implement a systematic approach by creating separate secrets for different certificate types and purposes. Use clear naming conventions like tls-frontend-secret and tls-backend-secret to maintain organization. Configure your certificate secrets with appropriate annotations that define their scope and usage.

Remember to validate certificate chains when working with multiple CA authorities. Store root certificates separately from leaf certificates to simplify rotation and updates. This separation allows for independent management of different certificate levels while maintaining secure HTTPS connections across your cluster.

Secret Access and Retrieval

Getting Secret Values

Retrieving secret values from your Kubernetes cluster requires specific considerations for secure access. The kubectl get secret command provides the base64-encoded format of your secrets, which you can decode using pipeline commands. For secure retrieval in production environments, combine the view and decode operations: kubectl get secret db-user-pass -o jsonpath='{.data.password}' | base64 --decode.

When accessing secrets across different namespaces, specify the target namespace using the -n flag. Your kubeconfig scope determines which secrets you can access, following the principle of least privilege. For automated secret retrieval in applications, mount secrets as volumes or environment variables rather than accessing them directly through the API.

Viewing Secret Details

Detailed inspection of Kubernetes secrets provides essential visibility into your configuration and security status. The kubectl describe secret command reveals metadata, labels, annotations, and the number of data fields without exposing sensitive values. For secure secret examination in production environments, StrongDM offers granular audit logging and session monitoring.

When troubleshooting secret configurations, use the --show-labels flag to verify proper secret organization and the -o yaml option to examine the full secret structure. Remember that direct secret inspection should follow your organization's security policies and access controls.

đź’ˇMake it easy: StrongDM enhances secret visibility by providing centralized management and detailed audit trails, helping teams maintain security compliance while streamlining secret inspection workflows across their Kubernetes infrastructure.

Secret Key Reference Methods

Referencing secret keys in Kubernetes requires understanding the relationship between secret names and their corresponding keys. When mounting secrets as volumes, each key in the secret becomes a file in the mounted directory. Your pod specifications need to include the secretKeyRef field, which points to both the secret name and the specific key you want to access.

For secure implementations, use the optional key parameter when creating secrets from files: kubectl create secret generic custom-secret --from-file=config-key=./config.json. This approach allows you to define meaningful key names instead of defaulting to filenames, making secret management more intuitive across your infrastructure.

Consider using namespaced references when working with secrets across different environments. The format secretKeyRef.name combined with secretKeyRef.key ensures precise targeting of specific data within your secret objects, reducing the risk of accidental exposure through overly broad access patterns.

Updating and Editing Secrets

Modifying Existing Secrets

When working with your Kubernetes cluster, you'll need to update secrets as credentials change or configurations evolve. Use kubectl edit secret [secret-name] to modify values directly in your default editor, or apply changes through YAML manifests with kubectl apply -f updated-secret.yaml.

For targeted updates to specific fields, the kubectl patch command offers precise control: kubectl patch secret mysql-credentials -p '{"data":{"password":"encoded-value"}}'. Remember that all values must be base64 encoded before updating.

đź’ˇMake it easy: StrongDM streamlines this process by handling secret modifications through a centralized interface, eliminating manual encoding steps and reducing the risk of configuration errors. 

When modifying secrets mounted as volumes, Kubernetes automatically propagates changes to pods using that secret, though there may be a brief delay for updates to take effect.

Adding Labels and Annotations

Labels and annotations serve distinct purposes in Kubernetes secret management. Labels help organize and select secrets based on key-value pairs, making them searchable and filterable across your cluster. While kubectl create secret doesn't support direct label assignment during creation, you can add labels afterward using kubectl label secret my-secret environment=production.

Annotations provide non-identifying metadata for your secrets, supporting larger data strings and special characters that labels don't allow. Use annotations to store deployment details, owner information, or policy requirements: kubectl annotate secret my-secret owner=platform-team. For structured data in annotations, you can include JSON strings that detail secret rotation schedules or compliance requirements.

Remember to maintain consistent labeling schemes across your secret ecosystem, as this facilitates automated secret management and policy enforcement through your infrastructure access controls.

Secret Version Control

Version control for Kubernetes secrets demands specialized approaches beyond standard Git workflows. Storing raw secrets in version control creates security risks, even when using private repositories. A robust solution combines encrypted secrets with sealed-secrets controllers in your cluster, allowing secure version tracking while maintaining secret integrity.

When implementing version-controlled secrets, use tools that encrypt sensitive data before committing to your repository. Your deployment pipeline can then safely decrypt these values during application rollout. For multi-environment setups, maintain separate sealed secret keys per cluster, ensuring production secrets remain isolated from development and staging environments.

đź’ˇMake it easy: StrongDM streamlines this process by managing secret versioning through secure, audited workflows that integrate with your existing CI/CD pipeline.

Best Practices for Secret Management

Security Considerations

Base64 encoding in Kubernetes Secrets provides basic obfuscation but not encryption, making proper security measures critical. According to recent CNCF data, 43% of respondents consider DevOps as the role most responsible for Kubernetes security, highlighting the need for robust protection strategies.

Secure your Secrets by implementing encryption at rest in etcd, using HTTPS connections for API server communication, and maintaining strict RBAC policies. The skip-tls verification flag should never be enabled in your kubeconfig cluster settings, as this compromises certificate authority validation.

đź’ˇMake it easy: StrongDM enhances these protections by providing automated secret rotation, granular access controls, and comprehensive audit trails. 

Configure your volume mountpath permissions carefully to prevent unauthorized access to mounted Secret files.

Access Control Strategies

Effective access control for Kubernetes secrets requires a multi-layered strategy that balances security with operational efficiency. Role-Based Access Control serves as your foundation, allowing you to define granular permissions based on job functions and responsibilities.

Consider implementing attribute-based policies alongside RBAC to create more dynamic access rules. For example, you might restrict secret access based on time of day, location, or security clearance level.

When managing access across multiple clusters, namespace isolation becomes crucial.

đź’ˇMake it easy: StrongDM helps you maintain consistent access policies across environments while providing detailed audit trails of all secret access attempts.

Secret Rotation Policies

Regular secret rotation strengthens your security posture by limiting the exposure window of compromised credentials. Most organizations rotate their secrets every quarter or twice a year, balancing security needs with operational overhead. When implementing rotation schedules, consider using short-lived credentials that automatically expire rather than static passwords requiring manual updates.

Automated rotation mechanisms help prevent service disruptions by seamlessly updating secrets across your infrastructure. Your rotation strategy should account for application dependencies, ensuring all services can handle credential changes without downtime. Consider implementing a phased approach where new secrets remain valid alongside existing ones during transition periods.

đź’ˇMake it easy: StrongDM manages the entire rotation lifecycle, from scheduling to validation, while maintaining detailed audit trails of each rotation event.

How StrongDM Simplifies Kubernetes Secret Management

StrongDM transforms secret management through its protocol-aware proxy architecture, injecting credentials during the "last mile" hop between proxy and target systems. This approach ensures sensitive credentials never touch client infrastructure in any form. By integrating with your existing third-party secret stores, StrongDM creates a secure bridge between your secret management tools and infrastructure access needs.

The platform's unified access management capabilities extend beyond basic secret storage. When users need to access protected resources, StrongDM's just-in-time delivery system automatically provisions the required credentials, eliminating the risk of standing access. Your teams maintain their existing workflows while StrongDM handles the complexity of secret distribution and access control.

Through its custom secrets integration, StrongDM seamlessly connects with tools like AWS Secrets Manager and GCP Secret Manager to reinforce secure credential handling across multi-cloud environments. This flexibility lets you leverage your preferred secret store provider without compromising on security or operational efficiency.

See how StrongDM simplifies secret management—book a demo today.

Kubernetes Secrets: Frequently Asked Questions

How to create a docker secret in Kubernetes?

Use the following command to create a Docker registry secret:

kubectl create secret docker-registry my-docker-secret \ --docker-server=<REGISTRY_SERVER> \ --docker-username=<USERNAME> \ --docker-password=<PASSWORD> \ --docker-email=<EMAIL> 

Then, reference it in your pod configuration using imagePullSecrets.

How to create tls secret in Kubernetes?

To create a TLS secret from a certificate and key file, run:

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

This secret can be used in Kubernetes Ingress or other TLS-enabled services.


About the Author

, Zero Trust Privileged Access Management (PAM), the StrongDM team is building and delivering a Zero Trust Privileged Access Management (PAM), which delivers unparalleled precision in dynamic privileged action control for any type of infrastructure. The frustration-free access stops unsanctioned actions while ensuring continuous compliance.

StrongDM logo
đź’™ this post?
Then get all that StrongDM goodness, right in your inbox.

You May Also Like

What Are Microservices in Kubernetes? Architecture, Example & More
What Are Microservices in Kubernetes? Architecture, Example & More
Microservices make applications more scalable and resilient, and Kubernetes is the backbone that keeps them running smoothly. By orchestrating containers, handling service discovery, and automating scaling, Kubernetes simplifies microservices management—but it also introduces complexity. This guide covers key principles, deployment strategies, and security best practices to help you navigate microservices in Kubernetes. Plus, see a modern way of simplifying access and security, so your teams can build faster—without compromising control. Let’s dive in.
What Is Kubernetes Observability? Best Practices, Tools & More
Kubernetes observability is the practice of monitoring and analyzing a Kubernetes environment through metrics, logs, and traces to gain visibility into system performance and health. It enables teams to detect and resolve issues proactively, optimize resource utilization, and maintain cluster reliability through real-time insights and automated monitoring tools.
What Is Kubernetes Ingress? Guide to K8s Traffic Management
What Is Kubernetes Ingress? Guide to K8s Traffic Management
This article breaks down Kubernetes Ingress, explaining how it manages external access to services, routing configurations, and best practices. You’ll learn how Ingress differs from Load Balancers, how controllers enforce routing rules, and how to choose the right setup for your needs.
15 Kubernetes Security Best Practices
Kubectl Cheat Sheet - Kubernetes Commands (Basic to Advanced)
Kubectl Cheat Sheet - Kubernetes Commands (Basic to Advanced)
Kubernetes is a popular tool for managing synchronized groups, or clusters, of computers. Users employ it to configure and deploy applications in parallel across clusters on your networks. The kubectl command line tool in Kubernetes lets you send instructions to and receive information from your clusters. This kubectl cheat sheet is a quick guide to getting started with kubectl, including installation, configuration, key commands, and efficiency tips.