如何用consul自动更新多个kv条目?

时间:2015-06-29 15:10:48

标签: 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

我可以一起原子地更新它们吗?

我问的原因是我们使用consule进行配置管理,并且不会因为依赖的键值对仅部分更新而因此处于不一致状态。

2 个答案:

答案 0 :(得分:2)

现在不可能。有一个开放的GitHub issue跟踪这个。

答案 1 :(得分: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方法中添加要添加的所有键值对