google-cloud-platformterraformgoogle-secret-managersecret-manager

How to create a secret in Google Cloud Secret Manager by Terraform?


This is official page: https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/secret_manager_secret

I created these files:

variables.tf

variable gcp_project {
  type = string
}

main.tf

resource "google_secret_manager_secret" "my_password" {
  provider = google-beta

  secret_id = "my-password"

  replication {
    automatic = true
  }
}

data "google_secret_manager_secret_version" "my_password_v1" {
  provider = google-beta
  project  = var.gcp_project
  secret   = google_secret_manager_secret.my_password.secret_id
  version  = 1
}

outputs.tf

output my_password_version {
  value = data.google_secret_manager_secret_version.my_password_v1.version
}

When apply it, got error:

Error: Error retrieving available secret manager secret versions: googleapi: Error 404: Secret Version [projects/2381824501/secrets/my-password/versions/1] not found.

So I created the secret by gcloud cli:

echo -n "my_secret_password" | gcloud secrets create "my-password" \
    --data-file - \
    --replication-policy "automatic"

Then apply terraform again, it said Error: project: required field is not set.

If use terraform to create a secret with a real value, how to do?


Solution

  • I found the following article that I consider to be useful on Managing Secret Manager with Terraform.

    You have to:

    1. Create the Setup
    2. Create a file named versions.tf that define the version constraints.
    3. Create a file named main.tf and configure the Google provider stanza:

    This is the code for creating a Secret Manager secret named "my-secret" with an automatic replication policy:

    resource "google_secret_manager_secret" "my-secret" {
      provider = google-beta
    
      secret_id = "my-secret"
    
      replication {
        automatic = true
      }
    
      depends_on = [google_project_service.secretmanager]
    }