Search code examples
pythonpython-3.xetcd

Get value of a key in etcd if key contains binary value?


I have an etcd key, which contains binary value:

/person/��h��1Ðn��;�Fx/timestamp
20230301091005

I query that key-value by:

env ETCDCTL_API=3 etcdctl --endpoints=server:2379 --cert ca.pem --key ca.key --cacert cacert.pem get /person/ --prefix

I wish to delete that particular key ��h��1Ðn��;�Fx from the etcd, but cannot refer to this key in Python etcd API function:

import etcd3

client = etcd3.client(host="server", port="2379", cert_cert="ca.pem", ca_cert="cacert.pem", cert_key="ca.key")
print(client.get_prefix_response(key_prefix="/person/", keys_only=True))

Outputs that /person/��h��1Ðn��;�Fx/timestamp looks like /person/\377\273h\260\2731\303\220n\031\271\235;\233Fx/timestamp And querying for that value:

client.get(key="/person/\377\273h\260\2731\303\220n\031\271\235;\233Fx/timestamp")

I get:

(None, None)

How could I query these binary keys in etcd?


Solution

  • Try this out:

    dataJson = subprocess.run(("env", "ETCDCTL_API=3", "etcdctl", "--endpoints=server:2379", "--cert", "ca.pem", "--key", "ca.key", "--cacert", "cacert.pem", "get", "/person/", "--prefix", "-w", "json"), stdout=subprocess.PIPE, check=True)
    
    pyDict = json.loads(dataJson.stdout)
    

    Note, that pyDict is already a Python data type, so you can perform all search operations on that dict freely.

    Inside pyDict all etcd keys are stored as base64. So when you wish to query that so called binary key's value, just decode it as:

    print(client.get(base64.b64decode(yourkey)))
    

    Don't forget to import base64, json, subprocess :)