locals {
  secret_path  = "secret/data/${var.environment}/${var.short_hostname}/certificate"
  policy_name  = "${var.environment}-${var.short_hostname}-cert-policy"
  approle_name = "${var.environment}-${var.short_hostname}-approle"
}

resource "vault_policy" "cert_access" {
  name   = local.policy_name
  policy = <<EOT
path "${local.secret_path}" {
  capabilities = ["read"]
}
EOT
}

resource "vault_approle_auth_backend_role" "cert_role" {
  backend        = "approle"
  role_name      = local.approle_name
  token_policies = [vault_policy.cert_access.name]
  token_ttl      = 3600  # 1 hour in seconds
  token_max_ttl  = 14400 # 4 hours in seconds
  secret_id_ttl  = 86400 # 24 hours in seconds
}

resource "vault_approle_auth_backend_role_secret_id" "cert_role_secret" {
  backend   = "approle"
  role_name = vault_approle_auth_backend_role.cert_role.role_name
}

resource "ansible_host" "vault_agent_node" {
  name   = var.short_hostname
  groups = ["vault_agent"]

  variables = {
    ansible_user                 = "ansible"
    ansible_ssh_private_key_file = "~/.ssh/id_ed25519"
    ansible_python_interpreter   = "/usr/bin/python3"
    vault_approle_role_id        = vault_approle_auth_backend_role.cert_role.role_id
    vault_approle_secret_id      = vault_approle_auth_backend_role_secret_id.cert_role_secret.secret_id
    vault_address                = var.vault_address
    vault_secret_path            = local.secret_path
    environment                  = var.environment
    short_hostname               = var.short_hostname
    ssl_certs_dir                = "/etc/ssl/certs"
    ssl_private_dir              = "/etc/ssl/private"
  }
}
