Created
February 18, 2019 16:28
-
-
Save bofm/2aad31130caba6ef3128888f1dd6f6c8 to your computer and use it in GitHub Desktop.
consul kv atomic bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
consul_kv_put_cas() { | |
local key="$1" | |
local value="$2" | |
local cas="$3" | |
test "$(curl -sq -X PUT -d "$value" "http://localhost:8500/v1/kv/${key}?cas=${cas}")" = "true" | |
} | |
consul_kv_put_if_not_exists() { | |
local key="$1" | |
local value="$2" | |
consul_kv_put_cas "$key" "$value" 0 | |
} | |
consul_kv_get_with_index() { | |
# returns <value>:<modify_index> | |
# Usage: | |
# $ consul_kv_get_with_index foo | |
# bar:3800 | |
local key="$1" | |
local response="$(curl -sq "http://localhost:8500/v1/kv/${key}?pretty")" | |
if [ "$response" = "" ]; then | |
return 1 | |
fi | |
local value="$(echo "$response" | grep -Po '(?<="Value": ")[^"]+(?=")' | base64 -d)" | |
local cas_index="$(echo "$response" | grep -Po '(?<="ModifyIndex": )\d+')" | |
echo "${value}:${cas_index}" | |
} | |
# root@server1:/# consul_kv_put_if_not_exists a c && echo OK || echo ERROR | |
# ERROR | |
# root@server1:/# consul kv delete a | |
# Success! Deleted key: a | |
# root@server1:/# consul_kv_put_if_not_exists a c && echo OK || echo ERROR | |
# OK | |
# root@server1:/# consul_kv_put_if_not_exists a b && echo OK || echo ERROR | |
# ERROR | |
# root@server1:/# consul_kv_get_with_index a | |
# c:4795 | |
# root@server1:/# val_idx="$(consul_kv_get_with_index a)" | |
# root@server1:/# echo "$val_idx" | |
# c:4795 | |
# root@server1:/# val="$(echo "$val_idx" | cut -d : -f 1)" | |
# root@server1:/# echo "$val" | |
# c | |
# root@server1:/# idx="$(echo "$val_idx" | cut -d : -f 2)" | |
# root@server1:/# echo "$idx" | |
# 4795 | |
# root@server1:/# consul_kv_put_cas a b 99 && echo OK || echo ERROR | |
# ERROR | |
# root@server1:/# consul_kv_put_cas a "${val}-updated" 99 && echo OK || echo ERROR | |
# ERROR | |
# root@server1:/# consul_kv_put_cas a "${val}-updated" "$idx" && echo OK || echo ERROR | |
# OK | |
# root@server1:/# consul_kv_get_with_index a | |
# c-updated:4832 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment