Skip to main content

Overview

The Secret class represents a Kubernetes Secret, which is used to store and manage sensitive information such as passwords, OAuth tokens, SSH keys, and TLS certificates. Secrets are similar to ConfigMaps but are specifically intended for confidential data.

Class Definition

from ocp_resources.secret import Secret
API Version: v1

Constructor

Secret accepts all parameters from NamespacedResource, plus:
name
str | None
Secret name
namespace
str | None
Namespace where the secret will be created
client
DynamicClient | None
Dynamic client for cluster connection
accesskeyid
str | None
AWS access key ID (convenience parameter for AWS credentials)
secretkey
str | None
AWS secret key (convenience parameter for AWS credentials)
htpasswd
str | None
Htpasswd data (convenience parameter for basic auth)
data_dict
dict | None
Dictionary of base64-encoded data
string_data
dict | None
Dictionary of plain-text data (will be automatically base64-encoded)
type
str | None
Secret type (e.g., Opaque, kubernetes.io/service-account-token, kubernetes.io/dockercfg, kubernetes.io/tls)
teardown
bool
default:"True"
Whether to delete the secret on cleanup
yaml_file
str | None
Path to YAML file for the secret
delete_timeout
int
default:"TIMEOUT_4MINUTES"
Timeout for delete operations

Properties

certificate_not_after

@property
def certificate_not_after(self) -> str
Returns the certificate expiration date from the annotation auth.openshift.io/certificate-not-after.

certificate_not_before

@property
def certificate_not_before(self) -> str
Returns the certificate start date from the annotation auth.openshift.io/certificate-not-before.

keys_to_hash

@property
def keys_to_hash(self) -> list[str]
Returns keys that should be hashed in logs: ["data", "stringData"]

Inherited Methods

Secret inherits all methods from NamespacedResource and Resource.

Examples

Creating a Simple Opaque Secret

from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

secret = Secret(
    client=client,
    name="my-secret",
    namespace="default",
    string_data={
        "username": "admin",
        "password": "secretpassword123"
    }
)
secret.create()

print(f"Secret {secret.name} created")

Creating a Secret with Base64-Encoded Data

import base64
from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

# Manually base64 encode
username_encoded = base64.b64encode(b"admin").decode("utf-8")
password_encoded = base64.b64encode(b"secretpassword").decode("utf-8")

secret = Secret(
    client=client,
    name="encoded-secret",
    namespace="default",
    data_dict={
        "username": username_encoded,
        "password": password_encoded
    }
)
secret.create()

print("Secret with base64 data created")

Creating a Docker Registry Secret

import base64
import json
from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

# Create Docker config
docker_config = {
    "auths": {
        "https://index.docker.io/v1/": {
            "username": "myuser",
            "password": "mypassword",
            "email": "[email protected]",
            "auth": base64.b64encode(b"myuser:mypassword").decode()
        }
    }
}

secret = Secret(
    client=client,
    name="docker-registry-secret",
    namespace="default",
    type="kubernetes.io/dockerconfigjson",
    string_data={
        ".dockerconfigjson": json.dumps(docker_config)
    }
)
secret.create()

print("Docker registry secret created")

Creating a TLS Secret

from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

# Read certificate and key files
with open("/path/to/tls.crt", "r") as f:
    tls_cert = f.read()

with open("/path/to/tls.key", "r") as f:
    tls_key = f.read()

secret = Secret(
    client=client,
    name="tls-secret",
    namespace="default",
    type="kubernetes.io/tls",
    string_data={
        "tls.crt": tls_cert,
        "tls.key": tls_key
    }
)
secret.create()

print("TLS secret created")

Creating an SSH Key Secret

from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

with open("/path/to/id_rsa", "r") as f:
    ssh_private_key = f.read()

with open("/path/to/id_rsa.pub", "r") as f:
    ssh_public_key = f.read()

secret = Secret(
    client=client,
    name="ssh-key-secret",
    namespace="default",
    type="kubernetes.io/ssh-auth",
    string_data={
        "ssh-privatekey": ssh_private_key,
        "ssh-publickey": ssh_public_key
    }
)
secret.create()

print("SSH key secret created")

Creating an AWS Credentials Secret

from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

# Using convenience parameters
secret = Secret(
    client=client,
    name="aws-credentials",
    namespace="default",
    accesskeyid="AKIAIOSFODNN7EXAMPLE",
    secretkey="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
)
secret.create()

print("AWS credentials secret created")

Creating an htpasswd Secret

import base64
from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

# Generate htpasswd (e.g., using htpasswd command)
htpasswd_content = "admin:$apr1$xyz123$abc..."
htpasswd_encoded = base64.b64encode(htpasswd_content.encode()).decode()

secret = Secret(
    client=client,
    name="htpasswd-secret",
    namespace="default",
    htpasswd=htpasswd_encoded
)
secret.create()

print("htpasswd secret created")

Using Secret in a Pod (Volume Mount)

from ocp_resources.secret import Secret
from ocp_resources.pod import Pod
from ocp_resources.resource import get_client

client = get_client()

# Create Secret
secret = Secret(
    client=client,
    name="app-secret",
    namespace="default",
    string_data={
        "api-key": "my-api-key-123",
        "db-password": "db-secret-password"
    }
)
secret.create()

# Create Pod that mounts the Secret
pod = Pod(
    client=client,
    name="app-pod",
    namespace="default",
    containers=[{
        "name": "app",
        "image": "myapp:latest",
        "volumeMounts": [{
            "name": "secret-volume",
            "mountPath": "/etc/secrets",
            "readOnly": True
        }]
    }],
    volumes=[{
        "name": "secret-volume",
        "secret": {
            "secretName": "app-secret"
        }
    }]
)
pod.create()

print("Pod created with Secret volume")

Using Secret in a Pod (Environment Variables)

from ocp_resources.secret import Secret
from ocp_resources.pod import Pod
from ocp_resources.resource import get_client

client = get_client()

# Create Secret
secret = Secret(
    client=client,
    name="env-secret",
    namespace="default",
    string_data={
        "DATABASE_PASSWORD": "secret123",
        "API_KEY": "apikey456"
    }
)
secret.create()

# Create Pod that uses Secret as environment variables
pod = Pod(
    client=client,
    name="app-pod",
    namespace="default",
    containers=[{
        "name": "app",
        "image": "myapp:latest",
        "env": [
            {
                "name": "DB_PASSWORD",
                "valueFrom": {
                    "secretKeyRef": {
                        "name": "env-secret",
                        "key": "DATABASE_PASSWORD"
                    }
                }
            },
            {
                "name": "API_KEY",
                "valueFrom": {
                    "secretKeyRef": {
                        "name": "env-secret",
                        "key": "API_KEY"
                    }
                }
            }
        ]
    }]
)
pod.create()

print("Pod created with Secret environment variables")

Listing Secrets

from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

# List all secrets in a namespace
for secret in Secret.get(client=client, namespace="default"):
    print(f"Secret: {secret.name}")
    print(f"  Type: {secret.instance.type}")
    if secret.instance.data:
        print(f"  Keys: {list(secret.instance.data.keys())}")

Using Context Manager

from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

with Secret(
    client=client,
    name="temp-secret",
    namespace="default",
    string_data={"temp_key": "temp_value"}
) as secret:
    print(f"Secret {secret.name} is available")
    # Secret is automatically deleted when exiting this block

Creating from YAML

from ocp_resources.secret import Secret
from ocp_resources.resource import get_client

client = get_client()

secret = Secret(
    client=client,
    yaml_file="/path/to/secret.yaml"
)
secret.create()

Secret Types

Opaque (Default)

Arbitrary user-defined data. Most common type for generic secrets.

kubernetes.io/service-account-token

Service account token secret.

kubernetes.io/dockercfg

Serialized ~/.dockercfg file for Docker registry authentication.

kubernetes.io/dockerconfigjson

Serialized ~/.docker/config.json file for Docker registry authentication.

kubernetes.io/basic-auth

Credentials for basic authentication with username and password keys.

kubernetes.io/ssh-auth

Credentials for SSH authentication with ssh-privatekey key.

kubernetes.io/tls

TLS certificate and key with tls.crt and tls.key keys.

bootstrap.kubernetes.io/token

Bootstrap token data.

Security Best Practices

Access Control

  • Use RBAC to restrict access to secrets
  • Follow the principle of least privilege
  • Separate secrets by namespace

Encryption

  • Enable encryption at rest in etcd
  • Use external secret management systems (e.g., HashiCorp Vault, AWS Secrets Manager)

Secret Rotation

  • Regularly rotate secrets
  • Consider using external secret operators for automatic rotation

Avoid Hardcoding

  • Never commit secrets to source control
  • Use tools like git-secrets or pre-commit hooks

Immutability

  • Consider making secrets immutable for production environments
  • Recreate secrets instead of updating them

See Also

Build docs developers (and LLMs) love