

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 中建立您的應用程式 AWS SAM
<a name="using-sam-cli-init"></a>

完成[入門](serverless-getting-started.md)和閱讀 之後[如何使用 AWS Serverless Application Model (AWS SAM)](chapter-using-sam.md)，您就可以在開發人員環境中建立 AWS SAM 專案。您的 AWS SAM 專案將做為撰寫無伺服器應用程式的起點。如需`sam init`命令選項的 AWS SAM CLI清單，請參閱 [sam init](sam-cli-command-reference-sam-init.md)。

 AWS Serverless Application Model 命令列界面 (AWS SAM CLI) `sam init`命令提供初始化新無伺服器應用程式的選項，其中包含：
+ 用來定義基礎設施程式碼的 AWS SAM 範本。
+ 組織應用程式的資料夾結構。
+  AWS Lambda 函數的組態。

若要建立 AWS SAM 專案，請參閱本節中的主題。

**注意**  
`sam init` 在支援的執行時間 (TypeScript、Python、Java) 中包含用於持久函數的專案範本。這些範本提供用於建置具狀態無伺服器應用程式的入門程式碼和組態。

**Topics**
+ [

## 初始化新的無伺服器應用程式
](#using-sam-cli-init-new)
+ [

## sam init 的選項
](#using-sam-cli-init-options)
+ [

## 疑難排解
](#using-sam-cli-init-troubleshooting)
+ [

## 範例
](#using-sam-cli-init-examples)
+ [

## 進一步了解
](#using-sam-cli-init-learn)
+ [

## 後續步驟
](#w2aac18c11c39)

## 初始化新的無伺服器應用程式
<a name="using-sam-cli-init-new"></a>

**使用 初始化新的無伺服器應用程式 AWS SAM CLI**

1. `cd` 到起始目錄。

1. 在命令列執行下列項目：

   ```
   $ sam init
   ```

1.  AWS SAM CLI 將引導您完成互動式流程，以建立新的無伺服器應用程式。
**注意**  
如 中所述[教學課程：使用 部署 Hello World 應用程式 AWS SAM](serverless-getting-started-hello-world.md)，此命令會初始化您的無伺服器應用程式，建立您的專案目錄。此目錄將包含數個檔案和資料夾。最重要的檔案是 `template.yaml`。這是您的 AWS SAM 範本。您的 python 版本必須與 **sam init**命令建立的 `template.yaml` 檔案中列出的 python 版本相符。

### 選擇開始範本
<a name="using-sam-cli-init-new-template"></a>

*範本*包含下列項目：

1. 基礎設施程式碼的 AWS SAM 範本。

1. 開始的專案目錄，可組織您的專案檔案。例如，這可能包括：

   1. Lambda 函數程式碼及其相依性的結構。

   1. 包含本機測試測試事件的`events`資料夾。

   1. 支援單元測試的`tests`資料夾。

   1. 用於設定專案設定`samconfig.toml`的檔案。

   1. `ReadMe` 檔案和其他基本啟動專案檔案。

   以下是開始專案目錄的範例：

   ```
   sam-app
   ├── README.md
   ├── __init__.py
   ├── events
   │   └── event.json
   ├── hello_world
   │   ├── __init__.py
   │   ├── app.py
   │   └── requirements.txt
   ├── samconfig.toml
   ├── template.yaml
   └── tests
       ├── __init__.py
       ├── integration
       │   ├── __init__.py
       │   └── test_api_gateway.py
       ├── requirements.txt
       └── unit
           ├── __init__.py
           └── test_handler.py
   ```

您可以從可用的 *AWS Quick Start 範本*清單中選擇，或提供您自己的*自訂範本位置*。

**選擇 AWS Quick Start 範本**

1. 出現提示時，選取 **AWS Quick Start 範本**。

1. 選取要開始的 AWS Quick Start 範本。以下是範例：

   ```
   Which template source would you like to use?
       1 - AWS Quick Start Templates
       2 - Custom Template Location
   Choice: 1
   
   Choose an AWS Quick Start application template
       1 - Hello World Example
       2 - Multi-step workflow
       3 - Serverless API
       4 - Scheduled task
       5 - Standalone function
       6 - Data processing
       7 - Hello World Example With Powertools
       8 - Infrastructure event management
       9 - Serverless Connector Hello World Example
       10 - Multi-step workflow with Connectors
       11 - Lambda EFS example
       12 - DynamoDB Example
       13 - Machine Learning
   Template: 4
   ```

**選擇您自己的自訂範本位置**

1. 出現提示時，選取**自訂範本位置**。

   ```
   Which template source would you like to use?
       1 - AWS Quick Start Templates
       2 - Custom Template Location
   Choice: 2
   ```

1.  AWS SAM CLI 將提示您提供範本位置。

   ```
   Template location (git, mercurial, http(s), zip, path):
   ```

   將下列任何位置提供給範本 .zip 檔案封存：
   + **GitHub 儲存庫** – 儲存GitHub庫中 .zip 檔案的路徑。檔案必須位於儲存庫的根目錄中。
   + **Mercurial 儲存庫** – 儲存Mercurial庫中 .zip 檔案的路徑。檔案必須位於儲存庫的根目錄中。
   + **.zip 路徑** – 您 .zip 檔案的 HTTPS 或本機路徑。

1.  AWS SAM CLI 將使用自訂範本初始化無伺服器應用程式。

### 選擇執行時間
<a name="using-sam-cli-init-new-runtime"></a>

當您選擇 *AWS Quick Start 範本*時， AWS SAM CLI會提示您選取 Lambda 函數的執行時間。顯示 AWS SAM CLI的選項清單是 Lambda 原生支援的執行時間。
+ [執行時間](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html#gettingstarted-concepts-runtime)會提供在執行環境中執行的特定語言環境。
+ 部署到 時 AWS 雲端，Lambda 服務會在[執行環境中](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html)叫用您的 函數。

您可以使用任何其他程式設計語言搭配自訂執行時間。若要這樣做，您需要手動建立您的啟動應用程式結構。然後，您可以使用 設定自訂範本位置`sam init`，快速初始化應用程式。

從您的選擇中， AWS SAM CLI會為您的 Lambda 函數程式碼和相依性建立起始目錄。

如果 Lambda 支援執行時間的多個相依性管理員，系統會提示您選擇偏好的相依性管理員。

### 選擇套件類型
<a name="using-sam-cli-init-new-package"></a>

當您選擇 *AWS Quick Start 範本*和*執行時間*時， 會 AWS SAM CLI提示您選取*套件類型*。套件類型會決定如何部署 Lambda 函數以搭配 Lambda 服務使用。支援的兩種套件類型為：

1. **容器映像** – 包含基本作業系統、執行時間、Lambda 延伸模組、您的應用程式程式碼及其相依性。

1. **.zip 檔案封存** – 包含您的應用程式程式碼及其相依性。

若要進一步了解部署套件類型，請參閱《 *AWS Lambda 開發人員指南*》中的 [Lambda 部署套件](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html)。

以下是 Lambda 函數封裝為容器映像之應用程式的範例目錄結構。會 AWS SAM CLI下載映像，並在`Dockerfile`函數的 目錄中建立 以指定映像。

```
sam-app
├── README.md
├── __init__.py
├── events
│   └── event.json
├── hello_world
│   ├── Dockerfile
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
├── samconfig.toml
├── template.yaml
└── tests
    ├── __init__.py
    └── unit
        ├── __init__.py
        └── test_handler.py
```

以下是應用程式的範例目錄結構，其中包含封裝為 .zip 檔案封存的 函數。

```
sam-app
├── README.md
├── __init__.py
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
├── samconfig.toml
├── template.yaml
└── tests
    ├── __init__.py
    ├── integration
    │   ├── __init__.py
    │   └── test_api_gateway.py
    ├── requirements.txt
    └── unit
        ├── __init__.py
        └── test_handler.py
```

### 設定 AWS X-Ray 追蹤
<a name="using-sam-cli-init-new-tracing"></a>

您可以選擇啟用 AWS X-Ray 追蹤。若要進一步了解，請參閱《 *AWS X-Ray 開發人員指南*》中的[什麼是 AWS X-Ray？](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html)。

如果您啟用 ， AWS SAM CLI會設定您的 AWS SAM 範本。以下是範例：

```
Globals:
  Function:
    ...
    Tracing: Active
  Api:
    TracingEnabled: True
```

### 使用 Amazon CloudWatch Application Insights 設定監控
<a name="using-sam-cli-init-new-insights"></a>

您可以選擇使用 Amazon CloudWatch Application Insights 啟用監控。若要進一步了解，請參閱《[Amazon CloudWatch 使用者指南》中的 Amazon CloudWatch Application Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html)。 *Amazon CloudWatch *

如果您啟用 ， AWS SAM CLI會設定您的 AWS SAM 範本。以下是範例：

```
Resources:
  ApplicationResourceGroup:
    Type: AWS::ResourceGroups::Group
    Properties:
      Name:
        Fn::Join:
        - ''
        - - ApplicationInsights-SAM-
          - Ref: AWS::StackName
      ResourceQuery:
        Type: CLOUDFORMATION_STACK_1_0
  ApplicationInsightsMonitoring:
    Type: AWS::ApplicationInsights::Application
    Properties:
      ResourceGroupName:
        Fn::Join:
        - ''
        - - ApplicationInsights-SAM-
          - Ref: AWS::StackName
      AutoConfigurationEnabled: 'true'
    DependsOn: ApplicationResourceGroup
```

### 為您的應用程式命名
<a name="using-sam-cli-init-new-name"></a>

為您的應用程式提供名稱。使用此名稱為您的應用程式 AWS SAM CLI建立頂層資料夾。

## sam init 的選項
<a name="using-sam-cli-init-options"></a>

以下是您可以搭配 `sam init`命令使用的一些主要選項。如需所有選項的清單，請參閱 [sam init](sam-cli-command-reference-sam-init.md)。

### 使用自訂範本位置初始化應用程式
<a name="using-sam-cli-init-options-location"></a>

使用 `--location`選項並提供支援的自訂範本位置。以下是範例：

```
$ sam init --location https://github.com/aws-samples/sessions-with-aws-sam/raw/master/starter-templates/web-app.zip
```

### 在沒有互動式流程的情況下初始化應用程式
<a name="using-sam-cli-init-options-no-interactive"></a>

使用 `--no-interactive`選項，並在命令列提供您的組態選擇，以略過互動式流程。以下是範例：

```
$ sam init --no-interactive --runtime go1.x --name go-demo --dependency-manager mod --app-template hello-world
```

## 疑難排解
<a name="using-sam-cli-init-troubleshooting"></a>

若要對 進行故障診斷 AWS SAM CLI，請參閱 [AWS SAM CLI 故障診斷](sam-cli-troubleshooting.md)。

## 範例
<a name="using-sam-cli-init-examples"></a>

### 使用 Hello World AWS Starter 範本初始化新的無伺服器應用程式
<a name="using-sam-cli-init-examples-helloworld"></a>

在此範例中，請參閱*教學課程：部署 Hello World 應用程式*[步驟 1：初始化範例 Hello World 應用程式](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-init)中的 。

### 使用自訂範本位置初始化新的無伺服器應用程式
<a name="using-sam-cli-init-examples-custom"></a>

以下是為您的自訂範本提供GitHub位置的範例：

```
$ sam init --location gh:aws-samples/cookiecutter-aws-sam-python
$ sam init --location git+sh://git@github.com/aws-samples/cookiecutter-aws-sam-python.git
$ sam init --location hg+ssh://hg@bitbucket.org/repo/template-name
```

以下是本機檔案路徑的範例：

```
$ sam init --location /path/to/template.zip
```

以下是 HTTPS 可連線的路徑範例：

```
$ sam init --location https://github.com/aws-samples/sessions-with-aws-sam/raw/master/starter-templates/web-app.zip
```

## 進一步了解
<a name="using-sam-cli-init-learn"></a>

若要進一步了解如何使用 `sam init`命令，請參閱以下內容：
+ **[學習 AWS SAM：sam init](https://www.youtube.com/watch?v=9m3R-leD5Xo) ** – 上的Serverless Land「學習 AWS SAM」系列YouTube。
+ **[建構無伺服器應用程式以搭配 AWS SAM CLI（使用 SAM S2E7 的工作階段）](https://www.youtube.com/watch?v=k9IRdgze9fQ)** – 在 上使用序列的 AWS SAM 工作階段YouTube。

## 後續步驟
<a name="w2aac18c11c39"></a>

現在您已建立 AWS SAM 專案，即可開始撰寫應用程式。[使用 定義您的基礎設施 AWS SAM](serverless-authoring.md) 如需您需要完成之任務的詳細說明，請參閱 。