简体   繁体   中英

Encode JSON in order to create it as secret with Python k8s Client

I have a big yaml file that I want to store as a secret in my kubernetes cluster. The following command succeeds:

k create secret generic values --from-file=my-values.yaml

But in my code, I want to use the k8s python client. So I want to do something like this:

def make_k8s_client(kubeconig):
....

def create_secret(name, data, client_api):
    secret = client.V1Secret(
        api_version="v1",
        kind="Secret",
        metadata=client.V1ObjectMeta(name=name),
        data=data,
    )

    client_api.create_namespaced_secret(namespace="default",
                                              body=secret)

k8s_api = make_k8s_client("path-to-kubeconfig")

with open("path-to/my-values.yaml") as f:
    values = yaml.load(f)

If I pass the yaml like this:

create_secret("mysecret", values, k8s_api)

I get this error:

HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Secret in version \"v1\" cannot be handled as a Secret: v1.Secret.Data: decode base64: illegal base64 data at input byte 0, error found in #10 byte of ...|pe\": \"abc\", \"def|..., bigger context ...|{\"apiVersion\": \"v1\", \"data\": {\"k8sType\": \"abc\", \"secret\": \"mysecret\", \"type\": \"mytype","reason":"BadRequest","code":400}

If I pass the secret like this:

create_secret("mysecret", base64.urlsafe_b64encode(json.dumps(values).encode()).decode(), k8s_api)

I get this error:

HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Secret in version \"v1\" cannot be handled as a Secret: v1.Secret.Data: ReadMapCB: expect { or n, but found \", error found in #10 byte of ...| \"data\": \"eyJrOHNUeX|..., bigger context ...|{\"apiVersion\": \"v1\", \"data\": \"eyJrOHNUeXBlIjogImF3cyIsICJnYXJkZW5lclNlY3JldCI6IC|...","reason":"BadRequest","code":400}

How do I have to encode the json file in order to be able to pass it to the python k8s client?

Data contains the secret data. Each key must consist of alphanumeric characters, '-', '_' or '.'. The serialized form of the secret data is a base64 encoded string, representing the arbitrary (possibly non-string) data value here ( 1 ).

V1Secret(
    api_version="v1",
    kind="Secret",
    metadata=client.V1ObjectMeta(name=name),
    data={
    'my-values.yaml': base64.b64encode(json.dumps(values).encode()).decode("utf-8")
     },

How to create and use a Secret

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM