Python Entegrasyonu
Consul Guardian, Python uygulamanızın yanında sidecar olarak çalışır. Uygulamanız python-consul2 veya herhangi bir HTTP istemcisi ile Consul KV'den konfigürasyon okur. Guardian aynı anahtarları bağımsız olarak izler, her değişikliği Git'e commit eder ve herhangi bir anahtarı önceki değerine geri yüklemenizi sağlar.
Uygulama kodunuzda hiçbir değişiklik gerekmez.
Python uygulamaları Consul'dan nasıl okur
| Paket | Açıklama |
|---|---|
| python-consul2 | python-consul'un bakımı yapılan fork'u |
| requests | Consul API'ye doğrudan HTTP çağrıları |
Örnek: python-consul2
pip install python-consul2
import consul
c = consul.Consul(host="consul", port=8500)
def get_config(key, default=None):
_, data = c.kv.get(key)
if data is None:
return default
return data["Value"].decode("utf-8")
# Başlangıçta config okuma
DB_HOST = get_config("config/myapp/db_host", "localhost")
DB_PORT = int(get_config("config/myapp/db_port", "5432"))
CACHE_TTL = int(get_config("config/myapp/cache_ttl", "300"))
Örnek: Flask uygulaması
from flask import Flask
import consul
app = Flask(__name__)
c = consul.Consul(host="consul", port=8500)
def load_config():
"""Tüm config değerlerini Consul KV'den yükle."""
keys = {
"config/myapp/db_host": "DB_HOST",
"config/myapp/db_port": "DB_PORT",
"config/myapp/secret_key": "SECRET_KEY",
"config/myapp/debug": "DEBUG",
}
for consul_key, config_key in keys.items():
_, data = c.kv.get(consul_key)
if data is not None:
app.config[config_key] = data["Value"].decode("utf-8")
load_config()
@app.route("/health")
def health():
return {"status": "ok", "db_host": app.config.get("DB_HOST")}
Örnek: Django ayarları
# settings.py
import consul
c = consul.Consul(host="consul", port=8500)
def consul_get(key, default=""):
_, data = c.kv.get(key)
if data is None:
return default
return data["Value"].decode("utf-8")
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"HOST": consul_get("config/django/db_host", "localhost"),
"PORT": consul_get("config/django/db_port", "5432"),
"NAME": consul_get("config/django/db_name", "myapp"),
"USER": consul_get("config/django/db_user", "postgres"),
"PASSWORD": consul_get("config/django/db_password"),
}
}
CACHE_TTL = int(consul_get("config/django/cache_ttl", "300"))
Guardian ekleme
Docker Compose
version: "3.8"
services:
consul:
image: hashicorp/consul:1.17
ports:
- "8500:8500"
command: agent -dev -client=0.0.0.0
myapp:
build: .
ports:
- "5000:5000"
environment:
- CONSUL_HOST=consul
- CONSUL_PORT=8500
depends_on:
- consul
guardian:
image: ghcr.io/consul-guardian/consul-guardian:latest
environment:
- CONSUL_GUARDIAN_CONSUL_ADDRESS=http://consul:8500
- CONSUL_GUARDIAN_WATCH_PREFIXES=config/
- CONSUL_GUARDIAN_GIT_REPO_PATH=/data/repo
volumes:
- guardian-data:/data
depends_on:
- consul
volumes:
guardian-data:
Celery + Consul config
Celery worker'larınız broker URL ve görev konfigürasyonunu Consul KV'den okuyorsa, Guardian bu değerleri de korur:
version: "3.8"
services:
consul:
image: hashicorp/consul:1.17
command: agent -dev -client=0.0.0.0
redis:
image: redis:7
web:
build: .
command: gunicorn app:app --bind 0.0.0.0:5000
environment:
- CONSUL_HOST=consul
depends_on:
- consul
- redis
worker:
build: .
command: celery -A tasks worker --loglevel=info
environment:
- CONSUL_HOST=consul
depends_on:
- consul
- redis
guardian:
image: ghcr.io/consul-guardian/consul-guardian:latest
environment:
- CONSUL_GUARDIAN_CONSUL_ADDRESS=http://consul:8500
- CONSUL_GUARDIAN_WATCH_PREFIXES=config/,celery/
- CONSUL_GUARDIAN_GIT_REPO_PATH=/data/repo
volumes:
- guardian-data:/data
depends_on:
- consul
volumes:
guardian-data:
Guardian hem config/ hem de celery/ prefix'lerini izler. Biri celery/broker_url değerini yanlış bir Redis URL'si ile değiştirirse, saniyeler içinde geri yükleyebilirsiniz.
Geri yükleme senaryosu
Biri veritabanı host'unu kullanımdan kaldırılmış bir sunucuya yönlendirir:
consul kv put config/myapp/db_host "eski-db.internal"
Flask uygulamanız 500 hatası döndürmeye başlar. Django "OperationalError: could not connect to server" hatası verir.
1. Neyin değiştiğini bulun
consul-guardian log --key config/myapp/db_host
# 2024-03-15T16:00:00Z bad1234 config/myapp/db_host modified
# 2024-02-01T09:00:00Z good567 config/myapp/db_host modified
2. Geri yükleyin
consul-guardian restore --key config/myapp/db_host --commit good567
3. Uygulamanızı yeniden başlatın (Python uygulamaları genellikle başlangıçta config okur)
docker compose restart myapp
# veya: kill -HUP <gunicorn_pid>
Uygulama doğru veritabanı host'u ile geri gelir.
Kod değişikliği gerekmez
Guardian bir Python paketi yüklemez, requirements.txt dosyanızı değiştirmez ve WSGI/ASGI pipeline'ınıza müdahale etmez. Consul KV'yi bağımsız olarak izleyen ayrı bir süreçtir. Python uygulamanız ve Guardian birbirlerinden habersizdir.