2015-06-29 46 views
3

假設我們有以下鍵值對進口領事:如何用consul原子地更新多個kv條目?

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 

我可以原子更新它們放在一起?

我問的原因是我們使用consule進行配置管理,並且不會因爲鍵值對只是部分更新而處於不一致的狀態。

回答

2

現在是不可能的。有一個開放的GitHub issue跟蹤這個。

+0

此功能是最近合併到主添加鍵值對。 – FuzzyAmi

0

爲它編寫一個shell腳本。 shell腳本樣本是這樣的:

#!/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 

添加所有要在setProperties方法

+0

如果密鑰已經存在於領事中,則值將被腳本中的值覆蓋 –