我在 docker-compose.yml 文件中有一个玩具领事。它填充了另一个运行和退出的服务。
version: '3.4'
services:
consul:
image: consul
consul-seed:
build:
context: consul/seed
environment:
HELLO: WORLD
consul/seed
包含一个运行 Python 脚本的 Dockerfile。FROM python:3-latest
RUN python3 -m pip install python-consul # Actually, this is via a requirements.txt. But for simplicity, this works too.
COPY seed.py ./
CMD python3 seed.py
python 脚本只是读取一些环境变量并用它们填充 Consul 的 KV。#!/usr/bin/env python3
import os
import consul
seed_keys=["HELLO"]
consul = consul.Consul()
for key in seed_keys:
value = os.environ.get(key, "")
if consul.kv.put(key=key, value=value, cas=0):
print("{}={}".format(key, value))
else:
print("! {}={}".format(key, value))
这样可行!当我这样做时:consul kv get HELLO
,内容为WORLD
.重要的是,种子脚本不会覆盖任何已经有键的值(证明 cas
选项受到尊重,并且种子脚本应该可以安全地使用“真正的”Consul 实例而不是玩具实例运行)。$ docker exec -ti consul /bin/sh
/ # consul kv get HELLO
WORLD
/ # consul kv put HELLO wOrLd
Success! Data written to: HELLO
/ # consul kv get HELLO
wOrLd
但是,如果我尝试使用 Consul CLI 播种值,它会提示 CAS 选项。$ docker exec -ti consul /bin/sh
/ # consul kv get HELLO
wOrLd
/ # consul kv delete HELLO
Success! Deleted key: HELLO
/ # consul kv put -cas HELLO world
Must specify -modify-index with -cas!
/ # consul kv put -cas 0 HELLO world
Error! Too many arguments (expected 1 or 2, got 3)
/ # consul kv put -cas -modify-index 0 HELLO world
Must specify -modify-index with -cas!
/ # consul kv put -cas -modify-index 1 HELLO world
Error! Did not write to HELLO: CAS failed
/ # consul kv get HELLO
Error! No key exists at: HELLO
如何使用代理 CLI 创建新的 KV 条目,但前提是它们尚不存在? 我在用:
$ docker pull consul
Using default tag: latest
latest: Pulling from library/consul
Digest: sha256:0e660ca8ae28d864e3eaaed0e273b2f8cd348af207e2b715237e869d7a8b5dcc
Status: Image is up to date for consul:latest
docker.io/library/consul:latest
$ docker image ls consul
REPOSITORY TAG IMAGE ID CREATED SIZE
consul latest 941109e2896d 4 weeks ago 122MB
$ docker run --rm -ti consul consul --version
Consul v1.8.0
Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)
最佳答案
我是 Consul 的产品经理。这是我们 CLI 中的一个错误。我们提交了https://github.com/hashicorp/consul/issues/8330跟踪修复此问题。
同时,如果 key 不存在,您可以直接使用 HTTP API 或通过 SDK 有条件地设置 key 。
关于python - 如何使用 Consul Agent CLI 创建新的 KV 条目,但前提是它们尚不存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62944057/