infra/stacks/trading-bot/main.tf

631 lines
18 KiB
Terraform
Raw Normal View History

/*
# TRADING-BOT STACK COMMENTED OUT - 2026-04-06
# Deployments scaled to 0, infrastructure disabled to prevent re-creation on apply
# To re-enable: uncomment this entire block
variable "tls_secret_name" {
type = string
sensitive = true
}
variable "nfs_server" { type = string }
variable "postgresql_host" { type = string }
variable "redis_host" { type = string }
locals {
common_env = {
TRADING_REDIS_URL = "redis://${var.redis_host}:6379/4"
TRADING_LOG_LEVEL = "INFO"
TRADING_ALPACA_BASE_URL = "https://paper-api.alpaca.markets"
TRADING_PAPER_TRADING = "true"
TRADING_REDDIT_USER_AGENT = "trading-bot/0.1"
TRADING_WATCHLIST = "[\"AAPL\",\"TSLA\",\"NVDA\",\"MSFT\",\"GOOGL\"]"
TRADING_BAR_TIMEFRAME = "5Min"
TRADING_POLL_INTERVAL_SECONDS = "60"
TRADING_HISTORICAL_BARS = "100"
TRADING_SNAPSHOT_INTERVAL_SECONDS = "60"
TRADING_FUNDAMENTALS_CACHE_TTL_HOURS = "24"
TRADING_RP_ID = "trading.viktorbarzin.me"
TRADING_RP_NAME = "Trading Bot"
TRADING_RP_ORIGIN = "https://trading.viktorbarzin.me"
TRADING_CORS_ORIGINS = "[\"https://trading.viktorbarzin.me\"]"
}
}
resource "kubernetes_namespace" "trading-bot" {
metadata {
name = "trading-bot"
labels = {
tier = local.tiers.edge
}
}
}
module "tls_secret" {
source = "../../modules/kubernetes/setup_tls_secret"
namespace = kubernetes_namespace.trading-bot.metadata[0].name
tls_secret_name = var.tls_secret_name
}
resource "kubernetes_manifest" "external_secret" {
manifest = {
apiVersion = "external-secrets.io/v1beta1"
kind = "ExternalSecret"
metadata = {
name = "trading-bot-secrets"
namespace = "trading-bot"
}
spec = {
refreshInterval = "15m"
secretStoreRef = {
name = "vault-kv"
kind = "ClusterSecretStore"
}
target = {
name = "trading-bot-secrets"
template = {
data = {
TRADING_ALPACA_API_KEY = "{{ .alpaca_api_key }}"
TRADING_ALPACA_SECRET_KEY = "{{ .alpaca_secret_key }}"
TRADING_JWT_SECRET_KEY = "{{ .jwt_secret }}"
TRADING_REDDIT_CLIENT_ID = "{{ .reddit_client_id }}"
TRADING_REDDIT_CLIENT_SECRET = "{{ .reddit_client_secret }}"
TRADING_ALPHA_VANTAGE_API_KEY = "{{ .alpha_vantage_api_key }}"
TRADING_FMP_API_KEY = "{{ .fmp_api_key }}"
DBAAS_ROOT_PASSWORD = "{{ .dbaas_root_password }}"
}
}
}
data = [
{ secretKey = "alpaca_api_key", remoteRef = { key = "trading-bot", property = "alpaca_api_key" } },
{ secretKey = "alpaca_secret_key", remoteRef = { key = "trading-bot", property = "alpaca_secret_key" } },
{ secretKey = "jwt_secret", remoteRef = { key = "trading-bot", property = "jwt_secret" } },
{ secretKey = "reddit_client_id", remoteRef = { key = "trading-bot", property = "reddit_client_id" } },
{ secretKey = "reddit_client_secret", remoteRef = { key = "trading-bot", property = "reddit_client_secret" } },
{ secretKey = "alpha_vantage_api_key", remoteRef = { key = "trading-bot", property = "alpha_vantage_api_key" } },
{ secretKey = "fmp_api_key", remoteRef = { key = "trading-bot", property = "fmp_api_key" } },
{ secretKey = "dbaas_root_password", remoteRef = { key = "trading-bot", property = "dbaas_root_password" } },
]
}
}
depends_on = [kubernetes_namespace.trading-bot]
}
# DB credentials from Vault database engine (rotated every 24h)
resource "kubernetes_manifest" "db_external_secret" {
manifest = {
apiVersion = "external-secrets.io/v1beta1"
kind = "ExternalSecret"
metadata = {
name = "trading-bot-db-creds"
namespace = "trading-bot"
}
spec = {
refreshInterval = "15m"
secretStoreRef = {
name = "vault-database"
kind = "ClusterSecretStore"
}
target = {
name = "trading-bot-db-creds"
template = {
data = {
TRADING_DATABASE_URL = "postgresql+asyncpg://trading:{{ .password }}@${var.postgresql_host}:5432/trading"
DB_PASSWORD = "{{ .password }}"
}
}
}
data = [{
secretKey = "password"
remoteRef = {
key = "static-creds/pg-trading"
property = "password"
}
}]
}
}
depends_on = [kubernetes_namespace.trading-bot]
}
# Database init job - creates the trading database and user in PostgreSQL
resource "kubernetes_job" "db_init" {
metadata {
name = "trading-bot-db-init"
namespace = kubernetes_namespace.trading-bot.metadata[0].name
}
spec {
template {
metadata {}
spec {
container {
name = "db-init"
image = "postgres:16-alpine"
command = [
"sh", "-c",
<<-EOT
set -e
# Create role if not exists
PGPASSWORD="$DBAAS_ROOT_PASSWORD" psql -h ${var.postgresql_host} -U root -tc "SELECT 1 FROM pg_roles WHERE rolname='trading'" | grep -q 1 || \
PGPASSWORD="$DBAAS_ROOT_PASSWORD" psql -h ${var.postgresql_host} -U root -c "CREATE ROLE trading WITH LOGIN PASSWORD '$DB_PASSWORD'"
# Create database if not exists
PGPASSWORD="$DBAAS_ROOT_PASSWORD" psql -h ${var.postgresql_host} -U root -tc "SELECT 1 FROM pg_database WHERE datname='trading'" | grep -q 1 || \
PGPASSWORD="$DBAAS_ROOT_PASSWORD" psql -h ${var.postgresql_host} -U root -c "CREATE DATABASE trading OWNER trading"
# Grant privileges
PGPASSWORD="$DBAAS_ROOT_PASSWORD" psql -h ${var.postgresql_host} -U root -c "GRANT ALL PRIVILEGES ON DATABASE trading TO trading"
# Try to enable timescaledb (allow failure)
PGPASSWORD="$DBAAS_ROOT_PASSWORD" psql -h ${var.postgresql_host} -U root -d trading -c "CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE" || true
echo "Database init complete"
EOT
]
env_from {
secret_ref {
name = "trading-bot-secrets"
}
}
env_from {
secret_ref {
name = "trading-bot-db-creds"
}
}
}
restart_policy = "Never"
}
}
backoff_limit = 3
}
wait_for_completion = true
timeouts {
create = "2m"
}
}
# Migrations job - runs alembic migrations
resource "kubernetes_job" "migrations" {
metadata {
name = "trading-bot-migrations"
namespace = kubernetes_namespace.trading-bot.metadata[0].name
}
spec {
template {
metadata {}
spec {
container {
name = "migrations"
image = "viktorbarzin/trading-bot-service:latest"
image_pull_policy = "Always"
command = ["python", "-m", "alembic", "upgrade", "head"]
env {
name = "TRADING_REDIS_URL"
value = "redis://${var.redis_host}:6379/4"
}
env_from {
secret_ref {
name = "trading-bot-secrets"
}
}
env_from {
secret_ref {
name = "trading-bot-db-creds"
}
}
}
restart_policy = "Never"
}
}
backoff_limit = 3
}
wait_for_completion = true
timeouts {
create = "5m"
}
depends_on = [kubernetes_job.db_init]
}
# Frontend deployment - dashboard + api-gateway
resource "kubernetes_deployment" "trading-bot-frontend" {
metadata {
name = "trading-bot-frontend"
namespace = kubernetes_namespace.trading-bot.metadata[0].name
labels = {
app = "trading-bot-frontend"
tier = local.tiers.edge
}
annotations = {
"reloader.stakater.com/auto" = "true"
}
}
spec {
replicas = 1
strategy {
type = "RollingUpdate"
rolling_update {
max_unavailable = 0
max_surge = 1
}
}
selector {
match_labels = {
app = "trading-bot-frontend"
}
}
template {
metadata {
labels = {
app = "trading-bot-frontend"
}
annotations = {
"dependency.kyverno.io/wait-for" = "postgresql.dbaas:5432,redis-master.redis:6379"
}
}
spec {
container {
name = "dashboard"
image = "viktorbarzin/trading-bot-dashboard:latest"
image_pull_policy = "Always"
port {
container_port = 80
protocol = "TCP"
}
resources {
requests = {
cpu = "10m"
memory = "64Mi"
}
limits = {
memory = "64Mi"
}
}
}
container {
name = "api-gateway"
image = "viktorbarzin/trading-bot-service:latest"
image_pull_policy = "Always"
command = ["python", "-m", "services.api_gateway.main"]
port {
container_port = 8000
protocol = "TCP"
}
dynamic "env" {
for_each = local.common_env
content {
name = env.key
value = env.value
}
}
env_from {
secret_ref {
name = "trading-bot-secrets"
}
}
env_from {
secret_ref {
name = "trading-bot-db-creds"
}
}
resources {
requests = {
cpu = "50m"
memory = "128Mi"
}
limits = {
memory = "128Mi"
}
}
}
}
}
}
lifecycle {
[infra] Document intended ignore_changes drift-workarounds [ci skip] ## Context The infra repo has 31 `ignore_changes` blocks. Phase 1 of the state-drift consolidation audit classified 21 as legitimate (immutable fields, cloud-computed values) and 10 as intentional workarounds for known drift sources. The remaining 10 were indistinguishable from accidental/forgotten drift suppression without reading the surrounding context. This commit adds a uniform `# DRIFT_WORKAROUND: <reason>, reviewed 2026-04-18` marker above the 8 intended-workaround blocks (6 CI image-tag decoupling + 2 non-deterministic secret hashes) so they are easy to distinguish from accidental drift suppression during future audits. ## What is NOT in this change - Functional behavior — `ignore_changes` lists are byte-identical. - The Kyverno `dns_config` ignore paths (covered by Wave 3 shared module). - Workarounds being removed — the CI decoupling is intentional by user decision. ## Files touched CI image-tag decoupling (6): - stacks/k8s-portal/modules/k8s-portal/main.tf (also has dns_config for Kyverno) - stacks/novelapp/main.tf - stacks/claude-memory/main.tf - stacks/plotting-book/main.tf - stacks/trading-bot/main.tf (api deployment) - stacks/trading-bot/main.tf (workers deployment — 6 containers) Non-deterministic secret hashes (2): - stacks/owntracks/main.tf (htpasswd bcrypt) - stacks/mailserver/modules/mailserver/main.tf (postfix-accounts.cf) ## Test Plan ### Automated ``` $ rg DRIFT_WORKAROUND stacks/ | wc -l 8 $ terraform fmt -recursive stacks/k8s-portal stacks/novelapp stacks/claude-memory \ stacks/plotting-book stacks/trading-bot stacks/owntracks stacks/mailserver (no output — already formatted) $ git diff --stat stacks/claude-memory/main.tf | 1 + stacks/k8s-portal/modules/k8s-portal/main.tf | 1 + stacks/mailserver/modules/mailserver/main.tf | 3 ++- stacks/novelapp/main.tf | 1 + stacks/owntracks/main.tf | 1 + stacks/plotting-book/main.tf | 1 + stacks/trading-bot/main.tf | 2 ++ 7 files changed, 9 insertions(+), 1 deletion(-) ``` ### Manual Verification No apply required — HCL comments only, zero effect on plan output. ## Reproduce locally 1. `cd infra && git pull` 2. `rg "DRIFT_WORKAROUND.*reviewed 2026-04-18" stacks/ | wc -l` → expect 8 3. `terraform fmt -check -recursive stacks/` → expect clean exit Closes: code-yrg Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 14:08:10 +00:00
# DRIFT_WORKAROUND: CI pipeline owns image tags for api + migrations containers. Reviewed 2026-04-18.
ignore_changes = [
spec[0].template[0].spec[0].container[0].image,
spec[0].template[0].spec[0].container[1].image,
[infra] Sweep dns_config ignore_changes across all pod-owning resources [ci skip] ## Context Wave 3A (commit c9d221d5) added the `# KYVERNO_LIFECYCLE_V1` marker to the 27 pre-existing `ignore_changes = [...dns_config]` sites so they could be grepped and audited. It did NOT address pod-owning resources that were simply missing the suppression entirely. Post-Wave-3A sampling (2026-04-18) found that navidrome, f1-stream, frigate, servarr, monitoring, crowdsec, and many other stacks showed perpetual `dns_config` drift every plan because their `kubernetes_deployment` / `kubernetes_stateful_set` / `kubernetes_cron_job_v1` resources had no `lifecycle {}` block at all. Root cause (same as Wave 3A): Kyverno's admission webhook stamps `dns_config { option { name = "ndots"; value = "2" } }` on every pod's `spec.template.spec.dns_config` to prevent NxDomain search-domain flooding (see `k8s-ndots-search-domain-nxdomain-flood` skill). Without `ignore_changes` on every Terraform-managed pod-owner, Terraform repeatedly tries to strip the injected field. ## This change Extends the Wave 3A convention by sweeping EVERY `kubernetes_deployment`, `kubernetes_stateful_set`, `kubernetes_daemon_set`, `kubernetes_cron_job_v1`, `kubernetes_job_v1` (+ their `_v1` variants) in the repo and ensuring each carries the right `ignore_changes` path: - **kubernetes_deployment / stateful_set / daemon_set / job_v1**: `spec[0].template[0].spec[0].dns_config` - **kubernetes_cron_job_v1**: `spec[0].job_template[0].spec[0].template[0].spec[0].dns_config` (extra `job_template[0]` nesting — the CronJob's PodTemplateSpec is one level deeper) Each injection / extension is tagged `# KYVERNO_LIFECYCLE_V1: Kyverno admission webhook mutates dns_config with ndots=2` inline so the suppression is discoverable via `rg 'KYVERNO_LIFECYCLE_V1' stacks/`. Two insertion paths are handled by a Python pass (`/tmp/add_dns_config_ignore.py`): 1. **No existing `lifecycle {}`**: inject a brand-new block just before the resource's closing `}`. 108 new blocks on 93 files. 2. **Existing `lifecycle {}` (usually for `DRIFT_WORKAROUND: CI owns image tag` from Wave 4, commit a62b43d1)**: extend its `ignore_changes` list with the dns_config path. Handles both inline (`= [x]`) and multiline (`= [\n x,\n]`) forms; ensures the last pre-existing list item carries a trailing comma so the extended list is valid HCL. 34 extensions. The script skips anything already mentioning `dns_config` inside an `ignore_changes`, so re-running is a no-op. ## Scale - 142 total lifecycle injections/extensions - 93 `.tf` files touched - 108 brand-new `lifecycle {}` blocks + 34 extensions of existing ones - Every Tier 0 and Tier 1 stack with a pod-owning resource is covered - Together with Wave 3A's 27 pre-existing markers → **169 greppable `KYVERNO_LIFECYCLE_V1` dns_config sites across the repo** ## What is NOT in this change - `stacks/trading-bot/main.tf` — entirely commented-out block (`/* … */`). Python script touched the file, reverted manually. - `_template/main.tf.example` skeleton — kept minimal on purpose; any future stack created from it should either inherit the Wave 3A one-line form or add its own on first `kubernetes_deployment`. - `terraform fmt` fixes to pre-existing alignment issues in meshcentral, nvidia/modules/nvidia, vault — unrelated to this commit. Left for a separate fmt-only pass. - Non-pod resources (`kubernetes_service`, `kubernetes_secret`, `kubernetes_manifest`, etc.) — they don't own pods so they don't get Kyverno dns_config mutation. ## Verification Random sample post-commit: ``` $ cd stacks/navidrome && ../../scripts/tg plan → No changes. $ cd stacks/f1-stream && ../../scripts/tg plan → No changes. $ cd stacks/frigate && ../../scripts/tg plan → No changes. $ rg -c 'KYVERNO_LIFECYCLE_V1' stacks/ --include='*.tf' --include='*.tf.example' \ | awk -F: '{s+=$2} END {print s}' 169 ``` ## Reproduce locally 1. `git pull` 2. `rg 'KYVERNO_LIFECYCLE_V1' stacks/ | wc -l` → 169+ 3. `cd stacks/navidrome && ../../scripts/tg plan` → expect 0 drift on the deployment's dns_config field. Refs: code-seq (Wave 3B dns_config class closed; kubernetes_manifest annotation class handled separately in 8d94688d for tls_secret) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 21:19:48 +00:00
spec[0].template[0].spec[0].dns_config, # KYVERNO_LIFECYCLE_V1: Kyverno admission webhook mutates dns_config with ndots=2
]
}
depends_on = [kubernetes_job.migrations]
}
# Workers deployment - all background microservices
resource "kubernetes_deployment" "trading-bot-workers" {
metadata {
name = "trading-bot-workers"
namespace = kubernetes_namespace.trading-bot.metadata[0].name
labels = {
app = "trading-bot-workers"
tier = local.tiers.edge
}
annotations = {
"reloader.stakater.com/auto" = "true"
}
}
spec {
replicas = 1
strategy {
type = "Recreate"
}
selector {
match_labels = {
app = "trading-bot-workers"
}
}
template {
metadata {
labels = {
app = "trading-bot-workers"
}
annotations = {
"dependency.kyverno.io/wait-for" = "postgresql.dbaas:5432,redis-master.redis:6379"
}
}
spec {
container {
name = "news-fetcher"
image = "viktorbarzin/trading-bot-service:latest"
image_pull_policy = "Always"
command = ["python", "-m", "services.news_fetcher.main"]
dynamic "env" {
for_each = local.common_env
content {
name = env.key
value = env.value
}
}
env {
name = "TRADING_OTEL_METRICS_PORT"
value = "9091"
}
env_from {
secret_ref {
name = "trading-bot-secrets"
}
}
env_from {
secret_ref {
name = "trading-bot-db-creds"
}
}
resources {
requests = {
cpu = "10m"
memory = "128Mi"
}
limits = {
memory = "256Mi"
}
}
}
container {
name = "sentiment-analyzer"
image = "viktorbarzin/trading-bot-service:latest"
image_pull_policy = "Always"
command = ["python", "-m", "services.sentiment_analyzer.main"]
dynamic "env" {
for_each = local.common_env
content {
name = env.key
value = env.value
}
}
env {
name = "TRADING_OTEL_METRICS_PORT"
value = "9092"
}
env_from {
secret_ref {
name = "trading-bot-secrets"
}
}
env_from {
secret_ref {
name = "trading-bot-db-creds"
}
}
resources {
requests = {
cpu = "100m"
memory = "512Mi"
}
limits = {
memory = "512Mi"
}
}
}
container {
name = "signal-generator"
image = "viktorbarzin/trading-bot-service:latest"
image_pull_policy = "Always"
command = ["python", "-m", "services.signal_generator.main"]
dynamic "env" {
for_each = local.common_env
content {
name = env.key
value = env.value
}
}
env {
name = "TRADING_OTEL_METRICS_PORT"
value = "9093"
}
env_from {
secret_ref {
name = "trading-bot-secrets"
}
}
env_from {
secret_ref {
name = "trading-bot-db-creds"
}
}
resources {
requests = {
cpu = "10m"
memory = "128Mi"
}
limits = {
memory = "256Mi"
}
}
}
container {
name = "trade-executor"
image = "viktorbarzin/trading-bot-service:latest"
image_pull_policy = "Always"
command = ["python", "-m", "services.trade_executor.main"]
dynamic "env" {
for_each = local.common_env
content {
name = env.key
value = env.value
}
}
env {
name = "TRADING_OTEL_METRICS_PORT"
value = "9094"
}
env_from {
secret_ref {
name = "trading-bot-secrets"
}
}
env_from {
secret_ref {
name = "trading-bot-db-creds"
}
}
resources {
requests = {
cpu = "10m"
memory = "128Mi"
}
limits = {
memory = "256Mi"
}
}
}
container {
name = "learning-engine"
image = "viktorbarzin/trading-bot-service:latest"
image_pull_policy = "Always"
command = ["python", "-m", "services.learning_engine.main"]
dynamic "env" {
for_each = local.common_env
content {
name = env.key
value = env.value
}
}
env {
name = "TRADING_OTEL_METRICS_PORT"
value = "9095"
}
env_from {
secret_ref {
name = "trading-bot-secrets"
}
}
env_from {
secret_ref {
name = "trading-bot-db-creds"
}
}
resources {
requests = {
cpu = "10m"
memory = "128Mi"
}
limits = {
memory = "256Mi"
}
}
}
container {
name = "market-data"
image = "viktorbarzin/trading-bot-service:latest"
image_pull_policy = "Always"
command = ["python", "-m", "services.market_data.main"]
dynamic "env" {
for_each = local.common_env
content {
name = env.key
value = env.value
}
}
env {
name = "TRADING_OTEL_METRICS_PORT"
value = "9096"
}
env_from {
secret_ref {
name = "trading-bot-secrets"
}
}
env_from {
secret_ref {
name = "trading-bot-db-creds"
}
}
resources {
requests = {
cpu = "10m"
memory = "128Mi"
}
limits = {
memory = "256Mi"
}
}
}
}
}
}
lifecycle {
[infra] Document intended ignore_changes drift-workarounds [ci skip] ## Context The infra repo has 31 `ignore_changes` blocks. Phase 1 of the state-drift consolidation audit classified 21 as legitimate (immutable fields, cloud-computed values) and 10 as intentional workarounds for known drift sources. The remaining 10 were indistinguishable from accidental/forgotten drift suppression without reading the surrounding context. This commit adds a uniform `# DRIFT_WORKAROUND: <reason>, reviewed 2026-04-18` marker above the 8 intended-workaround blocks (6 CI image-tag decoupling + 2 non-deterministic secret hashes) so they are easy to distinguish from accidental drift suppression during future audits. ## What is NOT in this change - Functional behavior — `ignore_changes` lists are byte-identical. - The Kyverno `dns_config` ignore paths (covered by Wave 3 shared module). - Workarounds being removed — the CI decoupling is intentional by user decision. ## Files touched CI image-tag decoupling (6): - stacks/k8s-portal/modules/k8s-portal/main.tf (also has dns_config for Kyverno) - stacks/novelapp/main.tf - stacks/claude-memory/main.tf - stacks/plotting-book/main.tf - stacks/trading-bot/main.tf (api deployment) - stacks/trading-bot/main.tf (workers deployment — 6 containers) Non-deterministic secret hashes (2): - stacks/owntracks/main.tf (htpasswd bcrypt) - stacks/mailserver/modules/mailserver/main.tf (postfix-accounts.cf) ## Test Plan ### Automated ``` $ rg DRIFT_WORKAROUND stacks/ | wc -l 8 $ terraform fmt -recursive stacks/k8s-portal stacks/novelapp stacks/claude-memory \ stacks/plotting-book stacks/trading-bot stacks/owntracks stacks/mailserver (no output — already formatted) $ git diff --stat stacks/claude-memory/main.tf | 1 + stacks/k8s-portal/modules/k8s-portal/main.tf | 1 + stacks/mailserver/modules/mailserver/main.tf | 3 ++- stacks/novelapp/main.tf | 1 + stacks/owntracks/main.tf | 1 + stacks/plotting-book/main.tf | 1 + stacks/trading-bot/main.tf | 2 ++ 7 files changed, 9 insertions(+), 1 deletion(-) ``` ### Manual Verification No apply required — HCL comments only, zero effect on plan output. ## Reproduce locally 1. `cd infra && git pull` 2. `rg "DRIFT_WORKAROUND.*reviewed 2026-04-18" stacks/ | wc -l` → expect 8 3. `terraform fmt -check -recursive stacks/` → expect clean exit Closes: code-yrg Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 14:08:10 +00:00
# DRIFT_WORKAROUND: CI pipeline owns image tags for all 6 worker containers. Reviewed 2026-04-18.
ignore_changes = [
spec[0].template[0].spec[0].container[0].image,
spec[0].template[0].spec[0].container[1].image,
spec[0].template[0].spec[0].container[2].image,
spec[0].template[0].spec[0].container[3].image,
spec[0].template[0].spec[0].container[4].image,
spec[0].template[0].spec[0].container[5].image,
[infra] Sweep dns_config ignore_changes across all pod-owning resources [ci skip] ## Context Wave 3A (commit c9d221d5) added the `# KYVERNO_LIFECYCLE_V1` marker to the 27 pre-existing `ignore_changes = [...dns_config]` sites so they could be grepped and audited. It did NOT address pod-owning resources that were simply missing the suppression entirely. Post-Wave-3A sampling (2026-04-18) found that navidrome, f1-stream, frigate, servarr, monitoring, crowdsec, and many other stacks showed perpetual `dns_config` drift every plan because their `kubernetes_deployment` / `kubernetes_stateful_set` / `kubernetes_cron_job_v1` resources had no `lifecycle {}` block at all. Root cause (same as Wave 3A): Kyverno's admission webhook stamps `dns_config { option { name = "ndots"; value = "2" } }` on every pod's `spec.template.spec.dns_config` to prevent NxDomain search-domain flooding (see `k8s-ndots-search-domain-nxdomain-flood` skill). Without `ignore_changes` on every Terraform-managed pod-owner, Terraform repeatedly tries to strip the injected field. ## This change Extends the Wave 3A convention by sweeping EVERY `kubernetes_deployment`, `kubernetes_stateful_set`, `kubernetes_daemon_set`, `kubernetes_cron_job_v1`, `kubernetes_job_v1` (+ their `_v1` variants) in the repo and ensuring each carries the right `ignore_changes` path: - **kubernetes_deployment / stateful_set / daemon_set / job_v1**: `spec[0].template[0].spec[0].dns_config` - **kubernetes_cron_job_v1**: `spec[0].job_template[0].spec[0].template[0].spec[0].dns_config` (extra `job_template[0]` nesting — the CronJob's PodTemplateSpec is one level deeper) Each injection / extension is tagged `# KYVERNO_LIFECYCLE_V1: Kyverno admission webhook mutates dns_config with ndots=2` inline so the suppression is discoverable via `rg 'KYVERNO_LIFECYCLE_V1' stacks/`. Two insertion paths are handled by a Python pass (`/tmp/add_dns_config_ignore.py`): 1. **No existing `lifecycle {}`**: inject a brand-new block just before the resource's closing `}`. 108 new blocks on 93 files. 2. **Existing `lifecycle {}` (usually for `DRIFT_WORKAROUND: CI owns image tag` from Wave 4, commit a62b43d1)**: extend its `ignore_changes` list with the dns_config path. Handles both inline (`= [x]`) and multiline (`= [\n x,\n]`) forms; ensures the last pre-existing list item carries a trailing comma so the extended list is valid HCL. 34 extensions. The script skips anything already mentioning `dns_config` inside an `ignore_changes`, so re-running is a no-op. ## Scale - 142 total lifecycle injections/extensions - 93 `.tf` files touched - 108 brand-new `lifecycle {}` blocks + 34 extensions of existing ones - Every Tier 0 and Tier 1 stack with a pod-owning resource is covered - Together with Wave 3A's 27 pre-existing markers → **169 greppable `KYVERNO_LIFECYCLE_V1` dns_config sites across the repo** ## What is NOT in this change - `stacks/trading-bot/main.tf` — entirely commented-out block (`/* … */`). Python script touched the file, reverted manually. - `_template/main.tf.example` skeleton — kept minimal on purpose; any future stack created from it should either inherit the Wave 3A one-line form or add its own on first `kubernetes_deployment`. - `terraform fmt` fixes to pre-existing alignment issues in meshcentral, nvidia/modules/nvidia, vault — unrelated to this commit. Left for a separate fmt-only pass. - Non-pod resources (`kubernetes_service`, `kubernetes_secret`, `kubernetes_manifest`, etc.) — they don't own pods so they don't get Kyverno dns_config mutation. ## Verification Random sample post-commit: ``` $ cd stacks/navidrome && ../../scripts/tg plan → No changes. $ cd stacks/f1-stream && ../../scripts/tg plan → No changes. $ cd stacks/frigate && ../../scripts/tg plan → No changes. $ rg -c 'KYVERNO_LIFECYCLE_V1' stacks/ --include='*.tf' --include='*.tf.example' \ | awk -F: '{s+=$2} END {print s}' 169 ``` ## Reproduce locally 1. `git pull` 2. `rg 'KYVERNO_LIFECYCLE_V1' stacks/ | wc -l` → 169+ 3. `cd stacks/navidrome && ../../scripts/tg plan` → expect 0 drift on the deployment's dns_config field. Refs: code-seq (Wave 3B dns_config class closed; kubernetes_manifest annotation class handled separately in 8d94688d for tls_secret) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 21:19:48 +00:00
spec[0].template[0].spec[0].dns_config, # KYVERNO_LIFECYCLE_V1: Kyverno admission webhook mutates dns_config with ndots=2
]
}
depends_on = [kubernetes_job.migrations]
}
resource "kubernetes_service" "trading-bot-frontend" {
metadata {
name = "trading-bot-frontend"
namespace = kubernetes_namespace.trading-bot.metadata[0].name
labels = {
app = "trading-bot-frontend"
}
}
spec {
selector = {
app = "trading-bot-frontend"
}
port {
port = 80
target_port = 80
}
}
}
module "ingress" {
source = "../../modules/kubernetes/ingress_factory"
[infra] Auto-create Cloudflare DNS records from ingress_factory ## Context Deploying new services required manually adding hostnames to cloudflare_proxied_names/cloudflare_non_proxied_names in config.tfvars — a separate file from the service stack. This was frequently forgotten, leaving services unreachable externally. ## This change: - Add `dns_type` parameter to `ingress_factory` and `reverse_proxy/factory` modules. Setting `dns_type = "proxied"` or `"non-proxied"` auto-creates the Cloudflare DNS record (CNAME to tunnel or A/AAAA to public IP). - Simplify cloudflared tunnel from 100 per-hostname rules to wildcard `*.viktorbarzin.me → Traefik`. Traefik still handles host-based routing. - Add global Cloudflare provider via terragrunt.hcl (separate cloudflare_provider.tf with Vault-sourced API key). - Migrate 118 hostnames from centralized config.tfvars to per-service dns_type. 17 hostnames remain centrally managed (Helm ingresses, special cases). - Update docs, AGENTS.md, CLAUDE.md, dns.md runbook. ``` BEFORE AFTER config.tfvars (manual list) stacks/<svc>/main.tf | module "ingress" { v dns_type = "proxied" stacks/cloudflared/ } for_each = list | cloudflare_record auto-creates tunnel per-hostname cloudflare_record + annotation ``` ## What is NOT in this change: - Uptime Kuma monitor migration (still reads from config.tfvars) - 17 remaining centrally-managed hostnames (Helm, special cases) - Removal of allow_overwrite (keep until migration confirmed stable) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 13:45:04 +00:00
dns_type = "proxied"
namespace = kubernetes_namespace.trading-bot.metadata[0].name
name = "trading"
service_name = "trading-bot-frontend"
tls_secret_name = var.tls_secret_name
protected = true
extra_annotations = {
"gethomepage.dev/enabled" = "true"
"gethomepage.dev/name" = "Trading Bot"
"gethomepage.dev/description" = "Automated trading"
"gethomepage.dev/icon" = "mdi-chart-line"
"gethomepage.dev/group" = "Finance & Personal"
"gethomepage.dev/pod-selector" = ""
}
}
*/