Search code examples
google-cloud-platformgoogle-secret-manager

How to set the value of a secret in GCP through CLI?


I have script written in bash where I create a key with a certain name.

#!/bin/bash

project_id="y"
secret_id="x"
secret_value="test"
gcloud config set project "$project_id"
gcloud secrets create "$secret_id" --replication-policy="automatic"

I want to be able to also directly add the secret-value to my secret, so that I do not have to go into my GCP account and set it manually (which would defeat the purpose). I have seen that it is possible to attach files through the following command, however there does not seem to be a similar command for a secret value.

--data-file="/path/to/file.txt"

Solution

  • From https://cloud.google.com/sdk/gcloud/reference/secrets/create#--data-file:

    --data-file=PATH File path from which to read secret data. Set this to "-" to read the secret data from stdin.

    So set --data-file to - and pass the value over stdin. Note, if you use echo use -n to avoid adding a newline.

    echo -n $secret_value | gcloud secrets create ... --data-file=-