簡體   English   中英

用於本地開發的 Google Cloud Functions 憑據

[英]Google Cloud Functions Credentials for Local Development

我有一個谷歌雲 function。 在這個 function 中,我想將文件寫入 GCS(谷歌雲存儲),然后獲取寫入 GCS 的文件的簽名 URL 並將該 ZE6B391A8D2C4D45902A23A8B6DZ 發送給調用者。

對於本地開發,我使用 functions-framework 命令在本地運行函數: functions-framework --source=.build/ --target=http-function --port 8082

當我想寫入 GCS 或獲取已簽名的 URL 時,雲功能框架只是嘗試從已登錄的 gcloud CLI 用戶那里獲取憑據。 但是,我想指出它從服務帳戶中讀取憑據。 對於所有其他 gcloud 開發目的,我們已將服務帳戶信息放在本地 creds.json 文件中,並將 gcloud 指向從該文件中讀取。

有什么方法可以實現這個功能嗎? 這意味着當我在本地啟動函數(使用函數框架)時,我將它指向 creds.json 文件以從那里讀取憑據?

所有 Google 的 SDK,例如用於 GCS,都使用您應該使用的應用程序默認憑據,而不是顯式路徑到密鑰。 如果函數框架是這樣,那么導出變量應該可以工作。

在這種情況下,命令gcloud auth application-default login是更好的建議,特別是對於測試簽名的 URL,因為使用該本地憑據以及 Cloud Functions 憑據(通過元數據服務器),私鑰不存在,並且必須以特定方式調用已簽名的 URL(提供令牌和服務帳戶才能對 URL 進行簽名)。 使用gcloud auth application-default login創建應用程序默認憑據,該憑據具有用戶帳戶的所有權限,並作為名為{HOME}/.config/gcloud/application-default_credentials的密鑰持久保存。

雲 Function 本地開發認證

這就是我正在使用由發布/訂閱事件觸發的 Nodejs 本地開發谷歌雲 function 所做的。 這使用了函數框架 Nodejs

TL;博士;

# shell A
gcloud auth application-default login

npm start

發布/訂閱事件消息

# shell B
curl -d "@mockPubSub.json" \                                                                                
  -X POST \
  -H "Content-Type: application/json" \
  http://localhost:8080

更多細節

  1. Cloud Function 與功能框架

文檔: 函數框架 Nodejs

package.json

注意--target--signature-type

{
...
  "scripts": {
    "start": "npx functions-framework --target=helloPubSub --signatur-type=event"
  },
  "dependencies": {
    "@google-cloud/debug-agent": "^7.0.0",
    "@google-cloud/storage": "^6.0.0"
  },
  "devDependencies": {
    "@google-cloud/functions-framework": "^3.1.2"
  }
...
}
  1. 下載文件的示例nodejs cloud function
/* modified from the sample
index.js
*/

const {Storage} = require('@google-cloud/storage');

function log(message, severity = 'DEBUG', payload) {
  // Structured logging
  // https://cloud.google.com/functions/docs/monitoring/logging#writing_structured_logs

  if (!!payload) {
    // If payload is an Error, get the stack trace.
    if (payload instanceof Error && !!payload.stack) {
      if (!!message ) {
         message = message + '\n' + payload.stack;
      } else {
         message = payload.stack;
      }
    }
  }
  const logEntry = {
    message: message,
    severity: severity,
    payload : payload
  };
  console.log(JSON.stringify(logEntry));
}

function getConfigFile(payload){
  console.log("Get Config File from GCS")
  const bucketName = 'some-bucket-in-a-project';
  const fileName = 'config.json';

  // Creates a client
  const storage = new Storage();

  async function downloadIntoMemory() {
    // Downloads the file into a buffer in memory.
    const contents = await storage.bucket(bucketName).file(fileName).download();

    console.log(
      `Contents of gs://${bucketName}/${fileName} are ${contents.toString()}.`
    );
  }

  downloadIntoMemory().catch(console.error);
}


exports.helloPubSub = async (pubSubEvent, context) => {
  /*
  Read payload from the event and log the exception in App project if the payload cannot be parsed
  */
 try {
    const payload = Buffer.from(pubSubEvent.body.message.data, 'base64').toString()
    const pubSubEventObj = JSON.parse(payload) ;
    console.log("name: ", pubSubEventObj.name);

    getConfigFile(pubSubEventObj)

  } catch (err) {
    log('failed to process payload: + payload \n' , 'ERROR', err);
  }

};
  1. Pub/Sub 事件的模擬消息

博客參考,但我沒有使用模擬器

myJson.json

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}  
  1. 為 Pub/sub 消息編碼(可能有更好的方法
cat myJson.json | grep -v % | base64
  1. 取 output 並將其放入數據鍵的值中:

mockPubSub.json

{
  "message": {
    "attributes": {
      "greeting": "Hello from the Cloud Pub/Sub Emulator!"
    },
    "data": "< put the output of the base64 from above here >",
    "messageId": "136969346945"
  },
  "subscription": "projects/myproject/subscriptions/mysubscription"
}
  1. 遵循TL;DR:以上的步驟。

免責聲明

  • gcloud auth application-default login使用執行命令的用戶的權限。 所以請記住,在生產中,雲 function 使用的服務帳戶將需要從存儲桶中讀取。
  • 在擦洗這個(即重命名位)並復制它時,我可能把它搞砸了。 對不起,如果這是真的。
  • 如果您好奇,這都是人為的,我的設計是從雲調度程序中獲取消息,其中包含有關從配置中讀取內容的相關詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM