creating a proper create_namespaced_secret command in kubernetes python client

4/24/2020

I have to create a secret like kubectl create secret generic mysecret -n mynamespace --from-literal=etcdpasswd=$(echo -n "PASSWORD>" | base64)

How do I do it using create_namespaced_secret API of kubernetes python client library.

-- user2553620
kubernetes
python

1 Answer

4/28/2020

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
-- pekowski
Source: StackOverflow