Google Cloud Functions - How to securely store service account private key when using Google Source Repository?

后端 未结 6 1009
醉酒成梦
醉酒成梦 2020-12-29 15:35

I use Google Source Repository to store my Google Cloud Functions. (Git repo hosted by Google, basically)

One of my function needs to access a private Google Sheet f

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 16:29

    This is how I solved this problem. First create a logic in a file keys.js to determine whether you are in development or production (and create corresponding ./dev.js and ./prod.js files, where you should include ./dev.js in .ignore file to make sure it's not uploaded to your github remote):

    if (process.env.NODE_ENV === "production") {
      module.exports = require("./prod");
    } else {
      module.exports = require("./dev");
    }
    

    Second, you require your keys.js file where the logic above resides and create a credential object based on the data received from keys.js:

    const credentials = {
      type: keys.googleType,
      project_id: keys.googleProjectId,
      private_key_id: keys.googlePrivateKeyId,
      private_key: keys.googlePrivateKey,
      client_email: keys.googleClientEmail,
      client_id: keys.googleClientId,
      auth_uri: keys.googleAuthUri,
      token_uri: keys.googleTokenUri,
      auth_provider_x509_cert_url: keys.googleAuthProviderX509CertUrl,
      client_x509_cert_url: keys.googleClientX509CertUrl
    };
    

    Now, for every google cloud service you can use the following example patterns:

      const storage = new Storage({
        project_id: credentials.project_id,
        credentials
      });
      const client = new textToSpeech.TextToSpeechClient({
        project_id: credentials.project_id,
        credentials
      });
    ...
    etc.
    

提交回复
热议问题