# Customer-managed key for the bucket. # # Two things about Cloud KMS surprise people. Its API is off in a new project, # so it has to be switched on first. And key rings and keys can never be # deleted. terraform destroy removes them from state and destroys the key # versions, while the ring and key names stay taken in that project for good. # The random suffix is there so a second apply after a destroy does not collide. resource "google_project_service" "kms" { project = var.project_id service = "cloudkms.googleapis.com" disable_on_destroy = false } resource "random_id" "ring" { byte_length = 3 } resource "google_kms_key_ring" "audit" { name = "${var.name}-${random_id.ring.hex}" location = lower(var.location) project = var.project_id depends_on = [google_project_service.kms] } resource "google_kms_crypto_key" "audit" { name = "${var.name}-storage" key_ring = google_kms_key_ring.audit.id rotation_period = "7776000s" # 90 days # Destroying a key makes everything encrypted with it unreadable, for good. # A destroy that reaches this key stops with an error. lifecycle { prevent_destroy = true } labels = local.labels } # Cloud Storage encrypts with the key through its own service agent, one per # project. That agent needs this role on the key, or bucket creation fails. data "google_storage_project_service_account" "gcs" { project = var.project_id } resource "google_kms_crypto_key_iam_member" "gcs" { crypto_key_id = google_kms_crypto_key.audit.id role = "roles/cloudkms.cryptoKeyEncrypterDecrypter" member = "serviceAccount:${data.google_storage_project_service_account.gcs.email_address}" }