0

I have a secret key stored in the Secret manager of GCP. The idea is to use that secret key to get the budget list using cloud functions.

Right now, I can access that key from my code, but the problem that I'm facing is that I need to set an environment variable with that secret key.

This is the way in which I could add the secret key (if you have in your local directory that file), but is there another way?

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "seret_key_file.json"
Pin90
  • 91
  • 1
  • 10
  • 2
    You have a secret stored in Secrets Manager. Read the secret and set an environment variable. Edit your question with details on exactly what your goal is, what you have tried, and the error/issue that remains. – John Hanley Jul 23 '21 at 17:24
  • 1
    If you use Cloud Functions, you don't need a service account key file. Simply deploy your function with a custom service account. – guillaume blaquiere Jul 24 '21 at 11:31

2 Answers2

1

try using sa account with the roles needed to run ex

function create_sa() { #
   gcloud iam service-accounts create "$SERVICE_ACCOUNT_NAME"
   gcloud iam service-accounts list
}

function add_role2sa() { #
   gcloud projects add-iam-policy-binding "$PROJECT_ID" --member serviceAccount:"$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role 'roles/iam.serviceAccountTokenCreator'
   gcloud projects add-iam-policy-binding "$PROJECT_ID" --member serviceAccount:"$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role 'roles/cloudfunctions.invoker'
}

function save_key_sa() { #
   gcloud iam service-accounts keys create "$GOOGLE_APPLICATION_CREDENTIALS" --iam-account "$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com"
}

you can get json file and store in a folder with limited access

rio
  • 685
  • 9
  • 16
1

You should not use Secret Manager for this purpose. Instead, deploy your Cloud Function as the service account you expect. With the gcloud CLI tool, you can do this with:

gcloud functions deploy ... \
  --service-account="my-account@p.iam.gserviceaccount.com"

This will make Cloud Functions run as the provided identity, inheriting the permissions of the underlying identity.


If you really want to use a custom Service Account Key, you need to manually instantiate the client using the private key data. For example:

client = secretmanager.SecretManagerServiceClient().from_service_account_info('<json service account key contents>')
sethvargo
  • 26,739
  • 10
  • 86
  • 156