job "vault" {
  datacenters = ["dc1"]
  type        = "service"

  # 约束只在 warden、ch4、ash3c 节点上运行
  constraint {
    attribute = "${node.unique.name}"
    operator  = "regexp"
    value     = "^(warden|ch4|ash3c)$"
  }

  group "vault" {
    count = 3

    # 确保每个节点只运行一个实例
    constraint {
      operator  = "distinct_hosts"
      value     = "true"
    }

    # 网络配置
    network {
      port "http" {
        static = 8200
        to     = 8200
      }
    }

    # 服务发现配置 - 包含版本信息
    service {
      name = "vault"
      port = "http"
      
      # 添加版本标签以避免检查拒绝
      tags = [
        "vault",
        "secrets",
        "version:1.20.3"
      ]

      check {
        name     = "vault-health"
        type     = "http"
        path     = "/v1/sys/health"
        interval = "10s"
        timeout  = "3s"
        method   = "GET"
        
      }

      # 健康检查配置
      check {
        name     = "vault-sealed-check"
        type     = "script"
        command  = "/bin/sh"
        args     = ["-c", "vault status -format=json | jq -r '.sealed' | grep -q 'false'"]
        interval = "30s"
        timeout  = "5s"
        task     = "vault"
      }
    }

    # 任务配置
    task "vault" {
      driver = "raw_exec"

      # 资源配置
      resources {
        cpu    = 500
        memory = 1024
      }

      # 环境变量
      env {
        VAULT_ADDR = "http://127.0.0.1:8200"
      }

      # 模板配置 - Vault 配置文件
      template {
        data = <<EOF
ui = true

storage "consul" {
  address = "127.0.0.1:8500"
  path    = "vault"
}

# HTTP listener (不使用 TLS，因为 nomad 会处理负载均衡)
listener "tcp" {
  address = "0.0.0.0:8200"
  tls_disable = 1
}

# 禁用 mlock 以避免权限问题
disable_mlock = true

# 日志配置
log_level = "INFO"
log_format = "json"

# 性能优化
max_lease_ttl = "168h"
default_lease_ttl = "24h"

# HA 配置
ha_storage "consul" {
  address = "127.0.0.1:8500"
  path    = "vault"
}
EOF
        destination = "local/vault.hcl"
        perms       = "644"
        wait {
          min = "2s"
          max = "10s"
        }
      }

      # 启动命令
      config {
        command = "/usr/bin/vault"
        args = [
          "agent",
          "-config=/local/vault.hcl"
        ]
      }


      # 重启策略
      restart {
        attempts = 3
        interval = "30m"
        delay    = "15s"
        mode     = "fail"
      }
    }

    # 更新策略
    update {
      max_parallel     = 1
      health_check     = "checks"
      min_healthy_time = "10s"
      healthy_deadline = "5m"
      progress_deadline = "10m"
      auto_revert      = true
      canary           = 0
    }

    # 迁移策略
    migrate {
      max_parallel     = 1
      health_check     = "checks"
      min_healthy_time = "10s"
      healthy_deadline = "5m"
    }
  }
}
