How to Create a Secret in Secret Manager in GCP
To create a secret in Google Cloud Secret Manager, use the
gcloud secrets create command with a secret name and optional labels. Then add secret data as a version using gcloud secrets versions add. This securely stores sensitive information like passwords or API keys.Syntax
The basic syntax to create a secret and add a secret version in GCP Secret Manager is:
gcloud secrets create [SECRET_NAME] --replication-policy="automatic"creates the secret container.gcloud secrets versions add [SECRET_NAME] --data-file=[FILE_PATH]adds the secret data as a version from a file.
Explanation:
[SECRET_NAME]: The name you choose for your secret.--replication-policy="automatic": Lets Google manage secret replication for high availability.--data-file: Path to the file containing the secret data you want to store.
bash
gcloud secrets create my-secret --replication-policy="automatic"
gcloud secrets versions add my-secret --data-file=./my-secret.txtExample
This example shows how to create a secret named api-key and add a secret version with the API key stored in a file called apikey.txt.
bash
gcloud secrets create api-key --replication-policy="automatic"
gcloud secrets versions add api-key --data-file=apikey.txtOutput
Created secret [api-key].
Added secret version [1] to [api-key].
Common Pitfalls
Common mistakes when creating secrets in GCP Secret Manager include:
- Trying to add secret data before creating the secret container.
- Using an incorrect file path for the secret data file.
- Not setting a replication policy, which is required.
- Using secret names with invalid characters or spaces.
Always create the secret first, verify the file path, and use simple secret names.
bash
Wrong:
gcloud secrets versions add my-secret --data-file=./secret.txt
Right:
gcloud secrets create my-secret --replication-policy="automatic"
gcloud secrets versions add my-secret --data-file=./secret.txtQuick Reference
| Command | Description |
|---|---|
| gcloud secrets create [NAME] --replication-policy="automatic" | Create a new secret with automatic replication |
| gcloud secrets versions add [NAME] --data-file=[FILE] | Add secret data as a new version from a file |
| gcloud secrets list | List all secrets in the project |
| gcloud secrets versions access latest --secret=[NAME] | Retrieve the latest secret version data |
Key Takeaways
Always create the secret container before adding secret data versions.
Use the --replication-policy flag to set how secrets are stored and replicated.
Store secret data in a file and reference it with --data-file when adding versions.
Choose simple, valid secret names without spaces or special characters.
Verify file paths and permissions to avoid errors when adding secret versions.