最近要準備寫一些Secret的部分才發現base64 encoding其實是可以被解密的,因此就找了一下怎麼讓GKE結合KMS來做加解密的動作。下面就來看code,我們一樣使用terraform來做。
大家記得要先enable kms api
或者在用terraform
api.tf
module "enabled_google_apis" {
source = "terraform-google-modules/project-factory/google//modules/project_services"
version = "~> 11.3"
project_id = var.project_id
disable_services_on_destroy = false
activate_apis = [
"cloudkms.googleapis.com",
]
}
首先我們新增一個kms.tf
resource "google_kms_crypto_key" "violet_crypto_key" {
name = "violet_crypto_key"
key_ring = google_kms_key_ring.violet_key_ring.id
}
resource "google_kms_key_ring" "violet_key_ring" {
name = "violet_key_ring"
location = var.location
}
resource "google_kms_key_ring_iam_member" "key_ring" {
key_ring_id = google_kms_key_ring.violet_key_ring.id
role = "roles/cloudkms.cryptoKeyEncrypterDecrypter"
member = "serviceAccount:service-${你的project number}@container-engine-robot.iam.gserviceaccount.com"
}
resource "google_project_iam_custom_role" "gke_cluster_defualt_to_access_kms" {
role_id = "GKEClusterDefaulttoAccessKMS"
title = "GKE Cluster Default to AccessKMS"
permissions = [
"cloudkms.cryptoKeyVersions.useToDecrypt",
"cloudkms.cryptoKeyVersions.useToEncrypt"
]
}
記得 resource google_kms_key_ring_iam_member.key_ring的部分要綁gke用的service account這樣才能讓GKE access到kms 。
接下來到gke module或是使用cluster container registry的地方加入
database_encryption = [
{
state = "ENCRYPTED"
key_name = google_kms_crypto_key.violet_crypto_key.id
}
]
depends_on = [
google_kms_key_ring.violet_key_ring
]
接下來terraform apply後就可以啦