I was working with kubernetes and there is a tool
named etcd
used in kubernetes architecture, so I checked wikipedia for it:
etcd is a persistent, lightweight, distributed, key-value data store developed by CoreOS …
And I was like, so this etcd
thingy can
be used to store keys and some values?
So I gave it a try, the binaries for etcd
are here and you can run etcd
simply by ./etcd
command.
etcdctl
In compressed file there is a executable named etcdctl
which can be used to work with a running etcd
service:
# set values
$ ./etcdctl set key value
value
$ ./etcdctl set key1 value1
value1
# get values
$ ./etcdctl get key
value
# set values but expire them after 5 seconds
./etcdctl set expire_me value --ttl 5
value
# list existing keys
$ ./etcdctl ls
/key
/key1
A you have seen in above samples etcd
uses a file-system-like structure
to represent keys, therefore you can create directories in etcd:
$ ./etcdctl set /the/parent/directories/key value
value
$ ./etcdctl get /the # or the
/the: is a directory
$ ./etcdctl set /the value # or the
Error: 102: Not a file (/the)
$ ./etcdctl set /the/topkey topvalue
topvalue
$ ./etcdctl ls /the -r
/the/parent
/the/parent/directories
/the/parent/directories/key
/the/topkey
API
etcdctl
is cool and all but I need something to set values
in etcd
from my code, some kind of API to work
with etcd
, something like this. here are the curl
samples from API guide:
# set key
curl http://127.0.0.1:2379/v2/keys/message -XPUT -d value="Hello world"
# get key
curl http://127.0.0.1:2379/v2/keys/message
So here is the python snippet to set a key:
# set.py
import requests
resp = requests.put(
"http://127.0.0.1:2379/v2/keys/message",
data={"value": "this is the value"},
)
print(resp.status_code)
print(resp.json())
# 201
# {
# 'action': 'set',
# 'node': {
# 'key': '/message',
# 'value': 'this is the value',
# 'modifiedIndex': 15,
# 'createdIndex': 15
# }
# }
And here is the snippet to get that key:
# get.py
import requests
resp = requests.get("http://127.0.0.1:2379/v2/keys/message")
print(resp.status_code)
print(resp.json())
# 200
# {
# 'action': 'get',
# 'node': {
# 'key': '/message',
# 'value': 'this is the value',
# 'modifiedIndex': 15,
# 'createdIndex': 15
# }
# }
Let’s use etcdctl
just to be sure:
$ ./etcdctl get /message
this is the value
So what?
That’s it. If you are confused by seeing many different names
in kubernetes architecture this small post was trying you
help you see etcd
as a simple key/value store.
I hope this post cleared something up for you.