Store Data in Consul KV
In addition to providing service discovery, integrated health checking, and securing network traffic, Consul includes a key value store, which you can use to dynamically configure applications, coordinate services, manage leader election, or serve as a data backend for Vault, along with a myriad of other uses.
In this tutorial, you will explore the Consul key value store (Consul KV) using the
command line. The tutorial assumes that the Consul agent from the Run the Consul Agent tutorial is
still running. If not you can start a new one by running consul agent -dev
.
Consul KV is enabled automatically on Consul agents; you don't need to enable it
in Consul's configuration.
There are two ways to interact with the Consul KV store: the Consul CLI and UI. In this tutorial, you will use the CLI.
Launch Terminal
This tutorial includes a free interactive command-line lab that lets you follow along on actual cloud infrastructure.
Add data
First, insert or "put" some values into the KV store with the consul kv put
command. The first entry after the command is the key, and the second entry is
the value.
Here the key is redis/config/maxconns
and the value is set to 25
.
Notice that with the key entered below ("redis/config/users/admin"), you set
a flags
value of 42. Keys support setting a 64-bit integer flag value that
isn't used internally by Consul, but can be used by clients to add metadata to
any KV pair.
Query data
Now, query for the value of one of the keys you just entered.
Consul retains some additional metadata about the key-value pair. Retrieve the
some metadata (including the "flag" you set) using the -detailed
command line
flag.
List all the keys in the store using the recurse
options. Results are returned
in lexicographical order.
Delete data
Delete a key from the Consul KV store, issue a "delete" call.
Consul lets you interact with keys in a folder-like way. Although all the keys in the KV store are actually stored flat, Consul allows you to manipulate keys that share a certain prefix as a group, as if they were in folders or subfolders.
Delete all the keys with the redis
prefix using the recurse
option.
Modify existing data
Update the value of an existing key.
Get the updated key.
Put the new value at an extant "path".
Check the updated path.
Next steps
In this tutorial, you added, viewed, modified, and deleted entries in Consul's key value store.
Consul can perform atomic key updates using a Check-And-Set (CAS) operation, and
includes other sophisticated options for writing keys and values. You can
explore these options on the help page for the consul kv put
command.
These are only a few examples of what the API supports. For the complete documentation, please see the HTTP API documentation and CLI documentation.
Now that Consul contains some interesting data including service registrations, keys, values, and intentions, continue to the Explore the Consul UI tutorial to locate all this data in the Consul web UI.