> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/RedHatQE/openshift-python-wrapper/llms.txt
> Use this file to discover all available pages before exploring further.

# Secret

> Secret resource for storing sensitive data

## 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

```python theme={null}
from ocp_resources.secret import Secret
```

**API Version:** `v1`

## Constructor

Secret accepts all parameters from [NamespacedResource](/api-reference/namespaced-resource), plus:

<ParamField path="name" type="str | None">
  Secret name
</ParamField>

<ParamField path="namespace" type="str | None">
  Namespace where the secret will be created
</ParamField>

<ParamField path="client" type="DynamicClient | None">
  Dynamic client for cluster connection
</ParamField>

<ParamField path="accesskeyid" type="str | None">
  AWS access key ID (convenience parameter for AWS credentials)
</ParamField>

<ParamField path="secretkey" type="str | None">
  AWS secret key (convenience parameter for AWS credentials)
</ParamField>

<ParamField path="htpasswd" type="str | None">
  Htpasswd data (convenience parameter for basic auth)
</ParamField>

<ParamField path="data_dict" type="dict | None">
  Dictionary of base64-encoded data
</ParamField>

<ParamField path="string_data" type="dict | None">
  Dictionary of plain-text data (will be automatically base64-encoded)
</ParamField>

<ParamField path="type" type="str | None">
  Secret type (e.g., `Opaque`, `kubernetes.io/service-account-token`, `kubernetes.io/dockercfg`, `kubernetes.io/tls`)
</ParamField>

<ParamField path="teardown" type="bool" default="True">
  Whether to delete the secret on cleanup
</ParamField>

<ParamField path="yaml_file" type="str | None">
  Path to YAML file for the secret
</ParamField>

<ParamField path="delete_timeout" type="int" default="TIMEOUT_4MINUTES">
  Timeout for delete operations
</ParamField>

## Properties

### certificate\_not\_after

```python theme={null}
@property
def certificate_not_after(self) -> str
```

Returns the certificate expiration date from the annotation `auth.openshift.io/certificate-not-after`.

### certificate\_not\_before

```python theme={null}
@property
def certificate_not_before(self) -> str
```

Returns the certificate start date from the annotation `auth.openshift.io/certificate-not-before`.

### keys\_to\_hash

```python theme={null}
@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](/api-reference/namespaced-resource) and [Resource](/api-reference/resource).

## Examples

### Creating a Simple Opaque Secret

```python theme={null}
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

```python theme={null}
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

```python theme={null}
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": "myemail@example.com",
            "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

```python theme={null}
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

```python theme={null}
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

```python theme={null}
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

```python theme={null}
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)

```python theme={null}
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)

```python theme={null}
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

```python theme={null}
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

```python theme={null}
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

```python theme={null}
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

* [NamespacedResource](/api-reference/namespaced-resource) - Base class
* [ConfigMap](/api-reference/configmap) - For non-sensitive configuration data
* [Pod](/api-reference/pod) - For using Secrets in workloads
* [Kubernetes Secrets](https://kubernetes.io/docs/concepts/configuration/secret/) - Official documentation
