terraform-contour-mirror/live/secrets/terragrunt.hcl

207 lines
9.3 KiB
HCL

include "root" {
path = find_in_parent_folders()
}
locals {
repo_root = try(get_repo_root(), "${get_terragrunt_dir()}/../..")
infra_config = yamldecode(file("${local.repo_root}/infrastructure.yaml"))
env_override = trimspace(get_env("INFRA_ENV", ""))
env_from_file = try(trimspace(local.infra_config.current_environment), "")
available_envs = sort(keys(try(local.infra_config.environments, {})))
env_fallback = try(local.available_envs[0], "")
env_name = local.env_override != "" ? local.env_override : (
local.env_from_file != "" ? local.env_from_file : local.env_fallback
)
# Single declarative source: shape + data in one sops file. In CI it is
# decrypted ahead of time and the path is passed via INFRA_SECRET_VALUES_FILE;
# locally we fall back to direct sops decryption. Values reach the module only
# via inputs (ephemeral), never written to disk.
#
# No try(...,"")/try(...,{}) on decrypt/parse/env-lookup below on purpose:
# swallowing those failures used to collapse silently into secrets = [],
# and a terraform plan with 0 declared secrets looks like a normal, boring
# "destroy everything" diff - nothing marks it as "decrypt actually failed".
secret_values_env_file = get_env("INFRA_SECRET_VALUES_FILE", "")
secret_values_raw = local.secret_values_env_file != "" ? file(local.secret_values_env_file) : sops_decrypt_file("${local.repo_root}/infrastructure-secrets.yaml")
secret_values_config = yamldecode(local.secret_values_raw)
# file() as a poor man's error(): HCL has no native assert/error function,
# this is the standard trick - an intentionally-broken file() call surfaces
# the message text inside terraform's own "no such file" error.
_fail_on_missing_secret_env = !contains(keys(local.secret_values_config.environments), local.env_name) ? file("INFRA_ENV '${local.env_name}' not found in infrastructure-secrets.yaml environments: [${join(", ", keys(local.secret_values_config.environments))}]") : ""
secret_values_env = local.secret_values_config.environments[local.env_name]
# secrets key itself may legitimately be absent for an environment with 0
# secrets declared - that one stays a real default, not an error.
secrets = try(local.secret_values_env.secrets, [])
# Явная проверка top-level ключей каждой записи secrets: Terraform молча
# отбрасывает незнакомые ключи при приведении к типу (например custom_key
# вместо custom_keys, depends_ons вместо depends_on) - без этой проверки
# опечатка в infrastructure-secrets.yaml тихо теряется, без единой ошибки
# в плане, и нужное поле остаётся дефолтным/пустым.
allowed_secret_keys = toset([
"name", "namespace", "type", "registry_url", "data", "depends_on",
"yc_sa_key_names", "custom_keys", "constant_keys", "random_keys",
"credential_keys", "labels", "annotations", "lifecycle", "sink", "vault_path",
])
secret_key_typos = flatten([
for secret in local.secrets : [
for k in keys(secret) : "${try(secret.namespace, "?")}/${try(secret.name, "?")}: unknown key '${k}'"
if !contains(local.allowed_secret_keys, k)
]
])
_fail_on_secret_key_typos = length(local.secret_key_typos) > 0 ? file("Unknown/misspelled key(s) in infrastructure-secrets.yaml secrets: ${join(" | ", local.secret_key_typos)}") : ""
# image-pull-secret (regcred) fan-out. Single source: vault.data.common.regcred.dockerconfigjson
# (secret values live under vault.data.* - see .sops.yaml encrypted_regex).
# Rolled as a kubernetes.io/dockerconfigjson secret named `regcred` into every
# namespace flagged `image_pull_secret: true` in infrastructure.yaml. Only created
# when the source is a real docker config (guards against the CHANGE_ME placeholder).
regcred_dockerconfigjson = try(local.secret_values_env.vault.data.common.regcred.dockerconfigjson, "")
regcred_valid = can(jsondecode(local.regcred_dockerconfigjson))
regcred_namespaces = [
for ns in try(local.infra_config.environments[local.env_name].namespaces, []) :
ns.name if try(ns.image_pull_secret, false)
]
regcred_secrets = local.regcred_valid ? [
for ns in local.regcred_namespaces : {
name = "regcred"
namespace = ns
type = "dockerconfigjson"
registry_url = ""
data = { ".dockerconfigjson" = base64encode(local.regcred_dockerconfigjson) }
depends_on = {}
yc_sa_key_names = {}
custom_keys = {}
constant_keys = {}
random_keys = {}
credential_keys = {}
labels = {}
annotations = {}
ignore_changes = false
sink = "k8s"
vault_path = ""
}
] : []
secrets_input = [
for secret in local.secrets : {
name = secret.name
namespace = try(secret.namespace, "")
type = try(secret.type, "opaque")
registry_url = try(secret.registry_url, "")
data = try(secret.data, {})
depends_on = try(secret.depends_on, {})
yc_sa_key_names = try(secret.yc_sa_key_names, {})
custom_keys = try(secret.custom_keys, {})
constant_keys = try(secret.constant_keys, {})
random_keys = try(secret.random_keys, {})
credential_keys = try(secret.credential_keys, {})
labels = try(secret.labels, {})
annotations = try(secret.annotations, {})
ignore_changes = try(secret.lifecycle.ignore_changes, false)
# Sink: k8s (default) or vault. vault_path is the KV name (default <prefix>/<name>).
sink = try(secret.sink, "k8s")
vault_path = try(secret.vault_path, "")
}
]
}
dependency "namespace" {
config_path = "../namespace"
mock_outputs = { namespaces = {}, names = [] }
mock_outputs_allowed_terraform_commands = ["init", "validate", "plan"]
}
dependency "s3" {
config_path = "../s3"
mock_outputs = { bucket_name = "mock", access_key = "mock", secret_key = "mock", buckets = {}, service_accounts = {} }
mock_outputs_allowed_terraform_commands = ["init", "validate", "plan"]
}
dependency "database" {
config_path = "../database"
mock_outputs = { database_outputs_map = {} }
mock_outputs_allowed_terraform_commands = ["init", "validate", "plan"]
}
dependency "rabbitmq" {
config_path = "../rabbitmq"
mock_outputs = { rabbitmq_outputs_map = {} }
mock_outputs_allowed_terraform_commands = ["init", "validate", "plan"]
}
dependency "kafka_topics" {
config_path = "../kafka-topics"
mock_outputs = { kafka_outputs_map = {} }
mock_outputs_allowed_terraform_commands = ["init", "validate", "plan"]
}
remote_state {
backend = "s3"
generate = {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
}
config = {
endpoint = get_env("TF_STATE_S3_ENDPOINT", "")
bucket = get_env("TF_STATE_S3_BUCKET", "")
key = "${local.env_name}/secrets/terraform.tfstate"
region = get_env("TF_STATE_S3_REGION", "ru-central1")
access_key = get_env("S3_ACCESS_KEY", get_env("AWS_ACCESS_KEY_ID", ""))
secret_key = get_env("S3_SECRET_KEY", get_env("AWS_SECRET_ACCESS_KEY", ""))
skip_region_validation = true
skip_credentials_validation = true
skip_metadata_api_check = true
skip_bucket_root_access = true
force_path_style = true
}
}
terraform {
source = "${get_terragrunt_dir()}/../../modules//k8s-secret"
}
inputs = {
secrets = concat(local.secrets_input, local.regcred_secrets)
s3_outputs = {
bucket_name = dependency.s3.outputs.bucket_name
access_key = dependency.s3.outputs.access_key
secret_key = dependency.s3.outputs.secret_key
}
s3_buckets_map = try(dependency.s3.outputs.buckets, {})
yc_service_accounts_map = try(dependency.s3.outputs.service_accounts, {})
database_outputs_map = dependency.database.outputs.database_outputs_map
rabbitmq_outputs_map = try(dependency.rabbitmq.outputs.rabbitmq_outputs_map, {})
kafka_outputs_map = try(dependency.kafka_topics.outputs.kafka_outputs_map, {})
valkey_outputs_map = {}
# In-cluster constants (contour). No managed-YC CA; in-cluster pgbouncer/pg on 5432.
constants = {
s3_endpoint = try(local.infra_config.environments[local.env_name].minio.endpoint, "http://minio.minio.svc.cluster.local:9000")
postgres_port = "5432"
postgres_ca = ""
valkey_port = "6379"
valkey_ca = ""
}
# Vault sink target (KV v2). Mount/prefix match the vault-secrets platform layout.
vault_kv_mount = try(local.secret_values_env.vault.kv_mount, "secrets")
vault_path_prefix = try(local.secret_values_env.vault.path_prefix, "vault")
env_vars = {
DOCKER_REGISTRY_USERNAME = get_env("DOCKER_REGISTRY_USERNAME", "")
DOCKER_REGISTRY_PASSWORD = get_env("DOCKER_REGISTRY_PASSWORD", "")
}
kubeconfig_path = get_env("KUBECONFIG", "")
kube_context = get_env("KUBE_CONTEXT", "")
}