How to atomize multiple kv records with consul?
Suppose we have the following value key pairs imported into consul:
curl -X PUT -d 'val1' http://localhost:8500/v1/kv/stuff/key1
curl -X PUT -d 'val2' http://localhost:8500/v1/kv/stuff/key2
curl -X PUT -d 'val3' http://localhost:8500/v1/kv/stuff/key3
Can I atomically update them all together?
The reason I am asking is because we are using consule for configuration management and will not have key pair-dependent ones only partially updated and therefore in an inconsistent state.
+3
source to share
2 answers
Write a shell script for it. An example shell script looks like this:
#!/bin/bash
# This script is used to bootstrap the following properties into the
# Consul KV store under the config/size key context.
setproperty()
{
# Defines the property in the Consul KV if the key is undefined.
#
# Arguments:
# 1 - Consul KV property value
# 2 - Consul KV property URL
# 3 - Optional boolean that specifies whether the an updated value
# should be echoed (defaults to true).
# Returns
# N/A
local key_value=$1
local key_url=$2
local echo_is_enabled=true
if [ $# == 3 ]
then
local echo_is_enabled=$3
fi
# Note:
# The ?case=0 flag means to turn the PUT into a Check-And-Set operation,
# so that the value will only be put if the key does not already exist.
local was_updated=$(curl -s -X PUT -d "$key_value" $key_url?cas=0)
if [ true == $echo_is_enabled ] && [ true == $was_updated ]
then
echo "ConsulKV[URL=$key_url][value=$key_value]"
fi
}
readonly -f setproperty
setproperties()
{
local val1="val1"
local url_val1="http://localhost:8500/v1/kv/stuff/key1"
if [ -z "$kv_val1" ] && [ -n "$val1" ]
then
setproperty "$val1" "$url_val1"
fi
}
main()
{
local url="http://localhost:8500"
# HTTP response code
local http_response_code=0
# timeout in units of seconds to wait for Consul KV to respond
timeout_sec=120
# while loop sleep time in units of seconds
local sleep_time_sec=5
# URL of the consul health service endpoint
url_health_service_consul="$url/v1/health/service/consul"
# wait until Consul is available or max wait exceeded
while [ 200 -ne $http_response_code ] && [ $SECONDS -lt $timeout_sec ]
do
http_response_code=$(curl -w %{response_code} -s --output /dev/null $url_health_service_consul)
if [ 200 -eq $http_response_code ]
then
break
fi
sleep $sleep_time_sec
done
if [ 200 -eq $http_response_code ]
then
# set properties if not already defined in Consul KV
setproperties
else
echo "Unable to access: $url_health_service_consul"
fi
}
readonly -f main
main
Add any key value pairs you want to add in the setproperties method.
0
user6209038
source
to share