Cyberworld-builders / gcp-iac

Managing Google Cloud Resources through Infrastructure as Code
0 stars 0 forks source link

Create a KMS Key for Storage Folder Encryption #5

Closed jaylong255 closed 3 weeks ago

jaylong255 commented 3 weeks ago

Creating a KMS Key for Terraform State Encryption

Understanding KMS Keys:

A KMS key is a cryptographic key that can be used to encrypt and decrypt data. In GCP, KMS keys are managed by the Key Management Service (KMS).

Steps:

  1. Create a KMS Key Ring:

    gcloud kms keyrings create my-keyring \
     --location us-central1 \
     --project your-project-id
    • This command creates a key ring named my-keyring in the us-central1 region of your project.
  2. Create a KMS Key:

    gcloud kms keys create my-key \
     --keyring my-keyring \
     --location us-central1 \
     --project your-project-id \
     --purpose encryption
    • This command creates a key named my-key within the my-keyring key ring. The key is intended for encryption purposes.
  3. Get the Key Version Name:

    gcloud kms keyrings list-versions my-keyring my-key
    • This command lists the versions of the key. You'll need the name of the latest version for your Terraform configuration.

Using the KMS Key in Terraform:

  1. Configure the Terraform Backend:
    terraform {
     backend "gcs" {
       bucket        = "your-terraform-state-bucket"
       prefix        = "terraform-state"
       key           = "terraform.tfstate"
       credentials   = file("path/to/your/service-account.json")
       region        = "us-central1" # Replace with your bucket's region
       encryption     = "kms"
       kms_key_name  = "projects/your-project-id/locations/us-central1/keyRings/my-keyring/cryptoKeys/my-key/cryptoKeyVersions/latest"
     }
    }
    • Replace the placeholders with your actual values.

Explanation:

Additional Considerations:

By following these steps, you can create a KMS key and use it to encrypt your Terraform state stored in a GCS bucket. This provides an additional layer of security for your infrastructure.

jaylong255 commented 3 weeks ago

Enable Cloud KMS API

gcloud services enable cloudkms.googleapis.com --project my-project-id
jaylong255 commented 3 weeks ago

Make sure your project is linked to a billing account

List Billing Accounts

gcloud beta billing accounts list

Enable billing on a project

gcloud beta billing projects link myname-system-root --billing-account=012345-6789AB-CDEF01