Using Create_Namespaced_Secret Api in Kubernetes Python Client

I have to create a secret like this, but with Python:

kubectl create secret generic mysecret -n mynamespace \
    --from-literal=etcdpasswd=$(echo -n "PASSWORD" | base64)

How do I do it using the create_namespaced_secret API of the kubernetes Python client library?

1 Answer

Try this:

from kubernetes import client, config
from kubernetes.client.rest import ApiException
import base64
import traceback
from pprint import pprint

secret_name = 'mysecret'
namespace = 'mynamespace'
data = {'etcdpasswd': base64.b64encode('<PASSWORD>')}

config.load_kube_config()
core_api_instance = client.CoreV1Api()
dry_run = None
pretty = 'true'
body = client.V1Secret()
body.api_version = 'v1'
body.data = data
body.kind = 'Secret'
body.metadata = {'name': secret_name}
body.type = 'Opaque'
try:
    if dry_run != None:
        api_response = core_api_instance.create_namespaced_secret(namespace, body, pretty=pretty, dry_run=dry_run)
    else:
        api_response = core_api_instance.create_namespaced_secret(namespace, body, pretty=pretty)
    pprint(api_response)
except ApiException as e:
    print("%s" % (str(e)))
    traceback.print_exc()
    raise
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest