從本端原始碼建立函數工作量

您可以透過 IBM Cloud® Code Engine CLI,直接在本地工作站上從原始碼建立您的 Code Engine 函式。 使用 function create (或 fn create) 指令,從本端來源建置程式碼組合,並部署函數以參照此建置的程式碼組合。

程式碼組合是代表函數碼的檔案集合。 這個程式碼組合會注入執行時期儲存器中。 您的程式碼組合由 Code Engine 建立,並儲存在儲存器登錄中或與函數一起列入。 程式碼組合不是 Open Container Initiative (OCI) 標準儲存器映像檔。

當您提交從本端目錄取回程式碼的建置時,您的原始碼會壓縮成保存檔。Code Engine 會自動將程式碼組合上傳至帳戶中的 IBM Cloud® Container Registry 名稱空間,然後建立並部署函數以參照此建置程式碼組合。 請注意,您只能將 IBM Cloud Container Registry 設為本端建置的目標。 在此實務範例中,您只需要提供函數的名稱,以及本端來源的路徑。 如需選項的完整清單,請參閱 ibmcloud ce fn create 指令。

如需存取映像檔登錄所需許可權的相關資訊,請參閱 設定映像檔登錄的權限

您可以選擇使用 .ceignore 檔案來忽略原始碼內的某些檔案型樣,其行為與 .gitignore 檔案類似。 例如,Node.js 函數的 .ceignore 檔項目可能包括 node_modules.npm。 如需要忽略的其他範例檔案型樣,請參閱 GitHub.gitignore 儲存庫

IBM Cloud® Container Registry 此情境下必須具備此條件。

開始之前

在使用本端來源之前,請確定您的來源位於本端工作站上可存取的位置。

使用 CLI 從本端原始碼建立函數

此範例使用下列 Node.js 程式碼,並儲存為 main.js 檔案。 您可以替換自己的程式碼。

/**
 * The `main` function is the entry-point into the function.
 * It has one optional argument, which carries all the
 * parameters the function was invoked with.
*/
async function main(params) {
  // log environment variables available to the function
  console.log(process.env);
  // log Code Engine system headers available to the function
  console.log(params.__ce_headers);
  // log all parameters for debugging purposes
  console.log("params: "+params);
  // since functions are invoked through http(s), we return an HTTP response
  return {
      statusCode: 200,
      headers: { 'Content-Type': 'application/json' },
      body: params };
}
// this step is necessary, if you gave your main function a different name
// we include it here for documentation purposes only
module.exports.main = main;
  1. 切換至包含 main.js 檔案的目錄,或記錄其路徑。

  2. 建立稱為 myfun-local 的函數,以使用 main.js 檔案作為來源。 此指令會自動建置程式碼組合,並將其推送至帳戶中的 Container Registry 名稱空間。 如果您沒有現有的 Container Registry 名稱空間,Code Engine 會自動為您建立一個名稱空間。

    ibmcloud ce fn create --name myfun-local --runtime nodejs --build-source main.js
    

    輸出範例

    Preparing function 'myfun-local' for build push...
    Creating function 'myfun-local'...
    Packaging files to upload from source path 'main.js'...
    Submitting build run 'myfun-local-run-230123-111011111'...
    Creating image 'icr.io/ce--abcde-glxo4kabcde/function-myfun-local:230123-1650-yrj86'...
    Waiting for build run to complete...
    Build run status: 'Running'
    Build run completed successfully.
    Run 'ibmcloud ce buildrun get -n myfun-local-run-230626-115011911' to check the build run status.
    Waiting for function 'myfun-local' to become ready...
    Function 'myfun-local' is ready.
    OK
    Run 'ibmcloud ce function get -n myfun-local' to see more details.
    https://myfun-local.glxo4kabcde.us-south.codeengine.test.appdomain.cloud
    

    請注意,function create 指令的輸出提供在建立函數之前建置執行的進度相關資訊。

    在此範例中,建置的程式碼組合會上傳至 Container Registry中的 ce--abcde-glxo4kabcde 名稱空間。

    下表彙總在此範例中與 fn create 指令搭配使用的選項。 如需指令及其選項的相關資訊,請參閱 ibmcloud ce function create 指令。 由於這些選項會根據原始程式碼所在的位置而有所不同,因此請確保原始程式碼所在的位置與範例相符。

    命令說明
    選項 說明
    --name 功能的名稱。 請使用專案內唯一的名稱。 此值是必要的。
    -名稱必須以小寫字母開頭。
    -名稱必須以小寫英數字元結尾。
    -名稱必須是 63 個字元或更少,且可以包含字母、數字及連字號 (-)。
    --build-source 通往本地來源的路徑。 這是必要值。
    --runtime 用於此函數的執行時期。 這是必要值。
  3. 使用 function get 指令來顯示應用程式的相關資訊,包括建置的相關資訊。

    ibmcloud ce function get --name myfun-local
    

    輸出範例

    Getting function 'myfun-local'...
    OK
    Name:          myfun-local
    Project Name:  sample
    Project ID:    abcdefgh-abcd-abcd-abcd-1a2b3c4d5e6f
    Age:           5m41s
    Created:       2023-06-26T16:50:14Z
    URL:           https://myfun-local.glxo4kabcde.us-south.codeengine.test.appdomain.cloud
    Status:        Ready
    Resources:
      CPU:                 0.25
      Memory:              500M
      Max Execution Time:  60 seconds
    Build Information:
      Build Run Name:     myfun-local-run-230123-111011111
      Build Type:         local
      Build Strategy:     codebundle-nodejs-22
      Timeout:            600
      Source:             main.js
      Build Run Summary:  Succeeded
      Build Run Status:   Succeeded
      Build Run Reason:   All Steps have completed executing
      Run 'ibmcloud ce buildrun get -n myfun-local-run-230123-111011111' for details.
    Function Code:
      Runtime:        nodejs-22 (managed)
      Bundle Secret:  ce-auto-icr-us-south
      Code Bundle:    cr://icr.io/ce--abcde-glxo4kabcde/function-myfun-local:230123-1650-yrj86
      Main:           main()
    

包括函數的相依關係

您可以使用許多不同的程式設計語言來建立函數。 當您的函數碼變得複雜時,您可以新增程式碼模組作為函數的相依關係。 每一種語言都有自己的模組,可與您的函數碼搭配使用。 例如,Node.js 相依關係通常是現有的 npm 模組,而 Python 使用 Python 套件。 必須在具有原始碼的檔案中宣告並建立這些相依關係

包括 Node.js 函數的模組

透過建立 package.json 檔案,建立包含特定 Node.js 模組的相依關係的函數。 在此情況下,原始碼和套件檔都位於相同的資料夾中。

  1. 透過將程式碼寫入 main.js 檔案來建立原始碼。 例如,將下列程式碼範例複製到稱為 main.js 的檔案。

    /**
    * The `main` function is the entry-point into the function.
    * It has one optional argument, which carries all the
    * parameters the function was invoked with.
    */
    function main(params /* optional */) {
      // use third-party 'lorem-ipsum' package to generate random words
      const LoremIpsum = require("lorem-ipsum").LoremIpsum;
      const lorem = new LoremIpsum();
      // since functions are invoked through http(s), we return an HTTP response
      return {
        headers: { "Content-Type": "text/plain;charset=utf-8" },
        body: lorem.generateWords(10),
      };
    }
    // this step is necessary, if you gave your main function a different name
    // we include it here for documentation purposes only
    module.exports.main = main;
    
  2. 建立 package.json 檔案,其中包含函數的必要相依關係。 對於前一個程式碼範例,請使用 package.json 檔案的下列內容。

    {
      "name": "function",
      "version": "1.0.0",
      "main": "main.js",
      "dependencies" : {
    		    "lorem-ipsum" : "2.0.8"
     	}
    }
    
  3. 在 Code Engine中建立檔案作為函數。 在此情況下,您位於本端檔案所在的目錄中,因此您可以使用 . 作為建置來源。

    ibmcloud ce fn create --name nodelorem --runtime nodejs --build-source .
    
  4. 執行提供的 fn get 指令,以尋找函數的詳細資料。

  5. 將 URL 貼入網頁瀏覽器,即可啟動您的函式。 您的瀏覽器會顯示 lorem ipsum 的段落。

如需 fn create 指令及其選項的相關資訊,請參閱 建立函數

包括 Python 函數的模組

透過建立 requirements.txt 檔案,建立包含特定 Python 模組之相依關係的函數。 在此情況下,原始碼和需求檔案都位於相同的資料夾中。

  1. 透過將程式碼儲存至 __main__.py 檔案來建立函數

    # use third-party 'lorem-ipsum' package to generate random words
    from lorem_text import lorem
    # The `main` function is the entry-point into the function.
    # It has one optional argument, which carries all the
    # parameters the function was invoked with.
    def main(params):
        words = 10
        # since functions are invoked through http(s), we return an HTTP response
        return {
          "headers": {
            "Content-Type": "text/plain;charset=utf-8",
        },
        "body": lorem.words(words),
    }
    def main(params):
         words = 10
         return {
              "headers": {
                  "Content-Type": "text/plain;charset=utf-8",
              },
              "body": lorem.words(words),
          }
    
  2. 建立包含函數所需相依關係的 requirements.txt

    lorem-text
    
  3. 在 Code Engine中建立檔案作為函數。 在此情況下,您位於本端檔案所在的目錄中,因此您可以使用 . 作為建置來源。

    ibmcloud ce fn create --name pylorem --runtime python --build-source .
    
  4. 執行提供的 fn get 指令,以尋找函數的詳細資料。

  5. 將 URL 貼入網頁瀏覽器,即可啟動您的函式。 您的瀏覽器會顯示 lorem ipsum 的段落。

如需 fn create 指令及其選項的相關資訊,請參閱 建立函數

下一步

既然已從本端原始碼建立及部署您的函數,您可以使用 ibmcloud ce function update 指令來更新函數,以符合您的需求。 如果您要更新來源以與函數搭配使用,則必須在 function update 指令上提供 --build-source 選項。

從本端來源或從 CLI 儲存庫原始碼 部署函數時,產生的建置執行不會以建置配置為基礎。 最終會自動刪除完成的建置執行。 如果建置執行成功,則會在 1 小時之後刪除非基於建置配置的建置執行。 如果建置執行不成功,則會在 24 小時之後刪除此建置執行。 您只能使用 CLI 來顯示這項建置執行的相關資訊。 您無法在控制台中查看此建置運行。

尋找更多程式碼範例? 請參閱 IBM Cloud Code Engine GitHub 儲存庫中的範例