

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

# 如何使用 的教學課程 AWS ParallelCluster
<a name="tutorials-v3"></a>

下列教學課程說明如何開始使用第 3 AWS ParallelCluster 版，並提供一些常見任務的最佳實務指引。

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**Topics**
+ [在 上執行您的第一個任務 AWS ParallelCluster](tutorials-running-your-first-job-on-version-3.md)
+ [建置自訂 AWS ParallelCluster AMI](building-custom-ami-v3.md)
+ [整合 Active Directory](tutorials_05_multi-user-ad.md)
+ [使用 AWS KMS 金鑰設定共用儲存加密](tutorials_04_encrypted_kms_fs-v3.md)
+ [在多個佇列模式叢集中執行任務](multi-queue-tutorial-v3.md)
+ [使用 AWS ParallelCluster API](tutorials_06_API_use.md)
+ [使用Slurm會計建立叢集](tutorials_07_slurm-accounting-v3.md)
+ [使用外部Slurmdbd會計建立叢集](external-slurmdb-accounting.md)
+ [還原至先前的 AWS Systems Manager 文件版本](tutorials_08_ssm-document-version-rev-v3.md)
+ [使用 建立叢集 CloudFormation](tutorials_09_cfn-custom-resource-v3.md)
+ [使用 Terraform 部署 ParallelCluster API](tutorial-deploy-terraform.md)
+ [使用 Terraform 建立叢集](tutorial-create-cluster-terraform.md)
+ [使用 Terraform 建立自訂 AMI](tutorial-create-ami-terraform.md)
+ [AWS ParallelCluster UI 與 Identity Center 整合](tutorials_10_pcui-aws-ic-integration-v3.md)
+ [使用 Pyxis 執行容器化任務](tutorials_11_running-containerized-jobs-with-pyxis.md)
+ [使用啟用 EFA 的 FSx Lustre 建立叢集](tutorial-efa-enabled-fsx-lustre.md)
+ [使用 p6e-gb200 執行個體支援 NVIDIA-Imex](support-nvidia-imex-p6e-gb200-instance.md)
+ [使用啟動範本覆寫自訂運算節點網路介面](tutorial-network-customization-v3.md)

# 在 上執行您的第一個任務 AWS ParallelCluster
<a name="tutorials-running-your-first-job-on-version-3"></a>

本教學課程會逐步引導您在 上執行第一個 Hello World 任務 AWS ParallelCluster

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**先決條件**
+ AWS ParallelCluster [已安裝 ](install-v3-parallelcluster.md)。
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ 您有 [Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 您有一個 IAM 角色，具有執行 CLI [`pcluster`](pcluster-v3.md) 所需的[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)。

## 確認安裝
<a name="tutorial-1stjob-verify-install"></a>

 首先，我們會驗證 AWS ParallelCluster 是否正確安裝和設定，包括 Node.js 相依性。

```
$ node --version
v16.8.0
$ pcluster version
{
  "version": "3.15.0"
}
```

這會傳回 的執行版本 AWS ParallelCluster。

## 建立您的第一個叢集
<a name="tutorial-1stjob-first-cluster"></a>

現在要建立您的第一個叢集。由於本教學課程的工作負載不是效能密集的工作負載，我們可以使用 `t2.micro` 的預設執行個體大小。(對於生產工作負載，您可以選擇最適合您需求的執行個體大小。) 讓我們呼叫您的叢集 `hello-world`。

```
$ pcluster create-cluster \
    --cluster-name hello-world \
    --cluster-configuration hello-world.yaml
```

**注意**  
大多數`pcluster`命令都必須指定 AWS 區域 要使用的 。如果未在`AWS_DEFAULT_REGION`環境變數中指定，或 `~/.aws/config` 檔案 `[default]`區段中的 `region`設定，則必須在`pcluster`命令列中提供 `--region` 參數。

如果輸出提供您有關組態的訊息，您需要執行下列動作來設定 AWS ParallelCluster：

```
$ pcluster configure --config hello-world.yaml
```

 如果[`pcluster create-cluster`](pcluster.create-cluster-v3.md)命令成功，您會看到類似以下的輸出：

```
{
  "cluster": {
    "clusterName": "hello-world",
    "cloudformationStackStatus": "CREATE_IN_PROGRESS",
    "cloudformationStackArn": "arn:aws:cloudformation:xxx:stack/xxx",
    "region": "...",
    "version": "...",
    "clusterStatus": "CREATE_IN_PROGRESS"
  }
}
```

 您可以使用下列方式監控叢集的建立：

```
$ pcluster describe-cluster --cluster-name hello-world
```

 在建立叢集時`clusterStatus`報告「`CREATE_IN_PROGRESS`」。成功建立叢集時， 會`clusterStatus`轉換為「`CREATE_COMPLETE`」。輸出也提供我們前端節點`privateIpAddress`的 `publicIpAddress`和 。

## 登入您的頭部節點
<a name="tutorial-1stjob-logging-in-head-node"></a>

 使用您的 OpenSSH pem 檔案登入您的頭部節點。

```
$ pcluster ssh --cluster-name hello-world -i /path/to/keyfile.pem
```

 登入之後，執行命令 `sinfo` 來驗證您的運算節點是否已設置和設定。

```
$ sinfo
PARTITION AVAIL  TIMELIMIT  NODES  STATE NODELIST
queue1*      up   infinite     10  idle~ queue1-dy-queue1t2micro-[1-10]
```

 輸出顯示我們的叢集中有一個佇列，最多十個節點。

## 使用 Slurm 執行您的第一個任務
<a name="tutorial-1stjob-first-slurm-job"></a>

接著，我們建立一個任務，它會休眠一會兒，然後輸出其自己的主機名稱。建立稱為 `hellojob.sh` 的檔案，其中具有以下內容。

```
#!/bin/bash
sleep 30
echo "Hello World from $(hostname)"
```

 接著，使用 `sbatch` 來提交任務，並驗證它是否執行。

```
$ sbatch hellojob.sh
Submitted batch job 2
```

 現在，您可以檢視佇列並檢查此任務的狀態。新 Amazon EC2 執行個體的佈建會在背景中啟動。您可以使用 `sinfo`命令監控叢集執行個體的狀態。

```
$ squeue
             JOBID PARTITION     NAME     USER ST       TIME  NODES NODELIST(REASON)
                 2    queue1 hellojob ec2-user CF       3:30      1 queue1-dy-queue1t2micro-1
```

 輸出顯示任務已提交至 `queue1`。等待 30 秒讓任務完成，然後再次執行 `squeue`。

```
$ squeue
             JOBID PARTITION     NAME     USER ST       TIME  NODES NODELIST(REASON)
```

 現在佇列中沒有任何任務，我們可以在目前的目錄中檢查輸出。

```
$ ls -l
total 8
-rw-rw-r-- 1 ec2-user ec2-user 57 Sep  1 14:25 hellojob.sh
-rw-rw-r-- 1 ec2-user ec2-user 43 Sep  1 14:30 slurm-2.out
```

 在輸出中，我們看到「`out`」檔案。我們可以看到任務的輸出：

```
$ cat slurm-2.out
Hello World from queue1-dy-queue1t2micro-1
```

輸出也會顯示我們的任務已在執行個體 `queue1-dy-queue1t2micro-1` 上成功執行。

在您剛建立的叢集中，叢集的所有節點之間只會共用主目錄。

若要進一步了解如何建立和使用叢集，請參閱 [最佳實務](best-practices-v3.md)。

如果您的應用程式需要共用軟體、程式庫或資料，請考慮下列選項：
+ 建置 AWS ParallelCluster 已啟用的自訂 AMI，其中包含您的軟體，如中所述[建置自訂 AWS ParallelCluster AMI](building-custom-ami-v3.md)。
+ 使用 AWS ParallelCluster 組態檔案中的 [StorageSettings](SharedStorage-v3.md) 選項來指定共用檔案系統，並將已安裝的軟體存放在指定的掛載位置。
+ 使用 [自訂引導操作](custom-bootstrap-actions-v3.md)來自動化叢集中每個節點的引導程序。

# 建置自訂 AWS ParallelCluster AMI
<a name="building-custom-ami-v3"></a>

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**重要**  
如果您建置自訂 AMI，則必須在每個新 AWS ParallelCluster 版本中重複用來建立自訂 AMI 的步驟。

在進一步閱讀之前，我們建議您先檢閱 [自訂引導操作](custom-bootstrap-actions-v3.md)區段。判斷您要進行的修改是否可以編寫指令碼，並支援未來的 AWS ParallelCluster 版本。

雖然通常建立自訂 AMI 並不理想，但在某些情況下 AWS ParallelCluster ，需要為 建置自訂 AMI。本教學課程說明如何為這些案例建置自訂 AMI。

**先決條件**
+ AWS ParallelCluster [已安裝 ](install-v3-parallelcluster.md)。
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ 您有 [Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 您有一個 IAM 角色，具有執行 CLI [`pcluster`](pcluster-v3.md) 和建置映像所需的[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)。

## 如何自訂 AWS ParallelCluster AMI
<a name="how-to-customize-the-aws-parallelcluster-ami-v3"></a>

有兩種方式可建置自訂 AWS ParallelCluster AMI。這兩種方法之一是使用 CLI AWS ParallelCluster 建立新的 AMI。另一種方法需要您手動修改，以建置可在 下使用的新 AMI AWS 帳戶。

## 建置自訂 AWS ParallelCluster AMI
<a name="build-a-custom-aws-parallelcluster-ami-v3"></a>

如果您有自訂 AMI 和軟體，您可以在其 AWS ParallelCluster 上套用 所需的變更。 AWS ParallelCluster 依賴 EC2 Image Builder 服務來建置自訂 AMIs。如需詳細資訊，請參閱[映像建置器使用者指南](https://docs.aws.amazon.com/imagebuilder/latest/userguide/what-is-image-builder.html)。

重點：
+ 程序大約需要 1 小時。如果在建置時要安裝其他 [`Build`](Build-v3.md) /[`Components`](Build-v3.md#Build-v3-Components)，則此時間可能會有所不同。
+ AMI 會標記主要元件的版本。這些包括核心、排程器和 [EFA](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) 驅動程式。元件版本的子集也會在 AMI 描述中報告。
+ 從 AWS ParallelCluster 3.0.0 開始，一組新的 CLI 命令可用來管理映像的生命週期。其中包括 [`build-image`](pcluster.build-image-v3.md)、[`list-images`](pcluster.list-images-v3.md)、[`describe-image`](pcluster.describe-image-v3.md) 和 [`delete-image`](pcluster.delete-image-v3.md)。
+ 此方法可重複。您可以重新執行它來保持 AMIs更新 （例如作業系統更新），然後在更新現有叢集時使用它們。

**注意**  
如果您在 AWS 中國分割區中使用此方法，您可能會遇到網路錯誤。例如，當您從 GitHub 或作業系統儲存庫下載套件時，您可能會從 `pcluster build-image`命令看到這些錯誤。如果發生這種情況，我們建議您使用下列其中一種替代方法：  
遵循繞過此命令[修改 AWS ParallelCluster AMI](#modify-an-aws-parallelcluster-ami-v3)的方法。
在另一個分割區和區域中建置映像，例如 `us-east-1`，然後存放/還原它以將其移至中國區域。如需詳細資訊，請參閱《*Amazon EC2 使用者指南*》中的[使用 S3 存放和還原 AMI ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-store-restore.html)。

步驟：

1. 設定您的 AWS 帳戶 登入資料，讓 AWS ParallelCluster 用戶端可以代表您呼叫 AWS API 操作。如需必要許可的清單，請參閱[AWS Identity and Access Management 中的 許可 AWS ParallelCluster](iam-roles-in-parallelcluster-v3.md)。

1. 建立基本*建置映像*組態檔案。若要這樣做，請指定[`InstanceType`](Build-v3.md#yaml-build-image-Build-InstanceType)要用來建置映像的 和 [`ParentImage`](Build-v3.md#yaml-build-image-Build-ParentImage)。這些是用來建立 AMI 的起點。如需選用建置參數的詳細資訊，請參閱[映像組態](image-builder-configuration-file-v3.md)。

   ```
   Build:
    InstanceType: <BUILD_INSTANCE_TYPE>
    ParentImage: <BASE_AMI_ID>
   ```

1. 使用 CLI 命令[`pcluster build-image`](pcluster.build-image-v3.md)從您提供做為基礎的 AWS ParallelCluster AMI 開始建置 AMI。

   ```
   $ pcluster build-image --image-id IMAGE_ID --image-configuration IMAGE_CONFIG.yaml --region REGION
       {
    "image": {
      "imageId": "IMAGE_ID",
      "imageBuildStatus": "BUILD_IN_PROGRESS",
      "cloudformationStackStatus": "CREATE_IN_PROGRESS",
      "cloudformationStackArn": "arn:aws:cloudformation:us-east-1:123456789012:stack/IMAGE_ID/abcd1234-ef56-gh78-ij90-1234abcd5678",
      "region": "us-east-1",
      "version": "3.15.0"
    }
   }
   ```
**警告**  
`pcluster build-image` 使用預設 VPC。如果您使用 AWS Control Tower 或 AWS 登陸區域刪除預設 VPC，則必須在映像組態檔案中指定子網路 ID。如需詳細資訊，請參閱[`SubnetId`](HeadNode-v3.md#yaml-HeadNode-Networking-SubnetId)。

   如需其他參數的清單，請參閱[`pcluster build-image`](pcluster.build-image-v3.md)命令參考頁面。上述命令的結果如下：
   + 根據映像組態建立 CloudFormation 堆疊。堆疊包含建置所需的所有 EC2 Image Builder 資源。
   + 建立的資源包括自訂映像建置器 AWS ParallelCluster 元件可新增至的官方映像建置器元件。如需詳細資訊，請參閱 *EC2 * [ Image Builder 使用者指南中的使用映像建置器建立自訂元件](https://docs.aws.amazon.com/imagebuilder/latest/userguide/create-component.html)。
   + EC2 Image Builder 會啟動建置執行個體、套用 AWS ParallelCluster 技術指南、安裝 AWS ParallelCluster 軟體堆疊，以及執行必要的組態任務。 AWS ParallelCluster 技術指南用於建置和引導 AWS ParallelCluster。
   + 執行個體會停止，並從中建立新的 AMI。
   + 另一個執行個體會從新建立的 AMI 啟動。在測試階段，EC2 Image Builder 會執行 Image Builder 元件中定義的測試。
   + 如果建置成功，則會刪除堆疊。如果建置失敗，堆疊會保留並可供檢查。

1. 您可以執行下列命令來監控建置程序的狀態。建置完成後，您可以執行它來擷取回應中提供的 AMI ID。

   ```
   $ pcluster describe-image --image-id IMAGE_ID --region REGION
       
   # BEFORE COMPLETE
   {
    "imageConfiguration": {
      "url": "https://parallelcluster-1234abcd5678efgh-v1-do-not-delete.s3.amazonaws.com/parallelcluster/3.15.0/images/IMAGE_ID-abcd1234efgh5678/configs/image-config.yaml?...",
    },
    "imageId": "IMAGE_ID",
    "imagebuilderImageStatus": "BUILDING",
    "imageBuildStatus": "BUILD_IN_PROGRESS",
    "cloudformationStackStatus": "CREATE_IN_PROGRESS",
    "cloudformationStackArn": "arn:aws:cloudformation:us-east-1:123456789012:stack/IMAGE_ID/abcd1234-ef56-gh78-ij90-1234abcd5678",
    "region": "us-east-1",
    "version": "3.15.0",
    "cloudformationStackTags": [
      {
        "value": "3.15.0",
        "key": "parallelcluster:version"
      },
      {
        "value": "IMAGE_ID",
        "key": "parallelcluster:image_name"
      },
      ...
    ],
    "imageBuildLogsArn": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/imagebuilder/ParallelClusterImage-IMAGE_ID",
    "cloudformationStackCreationTime": "2022-04-05T21:36:26.176Z"
   }
   
   # AFTER COMPLETE
   {
    "imageConfiguration": {
      "url": "https://parallelcluster-1234abcd5678efgh-v1-do-not-delete.s3.us-east-1.amazonaws.com/parallelcluster/3.15.0/images/IMAGE_ID-abcd1234efgh5678/configs/image-config.yaml?Signature=..."
    },
    "imageId": "IMAGE_ID",
    "imageBuildStatus": "BUILD_COMPLETE",
    "region": "us-east-1",
    "ec2AmiInfo": {
        "amiName": "IMAGE_ID 2022-04-05T21-39-24.020Z",
        "amiId": "ami-1234stuv5678wxyz",
        "description": "AWS ParallelCluster AMI for alinux2, kernel-4.14.238-182.422.amzn2.x86_64, lustre-2.10.8-5.amzn2.x86_64, efa-1.13.0-1.amzn2.x86_64, dcv-2021.1.10598-1.el7.x86_64, slurm-20-11-8-1",
        "state": "AVAILABLE",
        "tags": [
         {
           "value": "2021.3.11591-1.el7.x86_64",
           "key": "parallelcluster:dcv_version"
         },
         ...
        ],
      "architecture": "x86_64"
    },
    "version": "3.15.0"      
   }
   ```

1. 若要建立叢集，請在叢集組態的 [`CustomAmi`](Scheduling-v3.md#yaml-Scheduling-SlurmQueues-Image-CustomAmi) 欄位中輸入 AMI ID。

**故障診斷和監控 AMI 建立程序**

影像建立會在大約一小時的時間內完成。您可以執行 [`pcluster describe-image`](pcluster.describe-image-v3.md)命令或日誌擷取命令來監控程序。

```
$ pcluster describe-image --image-id IMAGE_ID --region REGION
```

此[`build-image`](pcluster.build-image-v3.md)命令會使用建置映像所需的所有 Amazon EC2 資源建立 CloudFormation 堆疊，並啟動 EC2 Image Builder 程序。

執行 [`build-image`](pcluster.build-image-v3.md)命令後，您可以使用 擷取 CloudFormation 堆疊事件[`pcluster get-image-stack-events`](pcluster.get-image-stack-events-v3.md)。您可以使用 `--query` 參數篩選結果，以查看最新的事件。如需詳細資訊，請參閱*AWS Command Line Interface 《 使用者指南*》中的[篩選 AWS CLI 輸出](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html)。

```
$ pcluster get-image-stack-events --image-id IMAGE_ID --region REGION --query "events[0]"
{
 "eventId": "ParallelClusterImage-CREATE_IN_PROGRESS-2022-04-05T21:39:24.725Z",
 "physicalResourceId": "arn:aws:imagebuilder:us-east-1:123456789012:image/parallelclusterimage-IMAGE_ID/3.15.0/1",
 "resourceStatus": "CREATE_IN_PROGRESS",
 "resourceStatusReason": "Resource creation Initiated",
 "resourceProperties": "{\"InfrastructureConfigurationArn\":\"arn:aws:imagebuilder:us-east-1:123456789012:infrastructure-configuration/parallelclusterimage-abcd1234-ef56-gh78-ij90-1234abcd5678\",\"ImageRecipeArn\":\"arn:aws:imagebuilder:us-east-1:123456789012:image-recipe/parallelclusterimage-IMAGE_ID/3.15.0\",\"DistributionConfigurationArn\":\"arn:aws:imagebuilder:us-east-1:123456789012:distribution-configuration/parallelclusterimage-abcd1234-ef56-gh78-ij90-1234abcd5678\",\"Tags\":{\"parallelcluster:image_name\":\"IMAGE_ID\",\"parallelcluster:image_id\":\"IMAGE_ID\"}}",
 "stackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/IMAGE_ID/abcd1234-ef56-gh78-ij90-1234abcd5678",
 "stackName": "IMAGE_ID",
 "logicalResourceId": "ParallelClusterImage",
 "resourceType": "AWS::ImageBuilder::Image",
 "timestamp": "2022-04-05T21:39:24.725Z"
}
```

約 15 分鐘後，堆疊事件會出現在與映像建置器建立相關的日誌事件項目中。您現在可以使用 和 [`pcluster get-image-log-events`](pcluster.get-image-log-events-v3.md)命令列出映像日誌串流[`pcluster list-image-log-streams`](pcluster.list-image-log-streams-v3.md)並監控映像建置器步驟。

```
$ pcluster list-image-log-streams --image-id IMAGE_ID --region REGION \
    --query 'logStreams[*].logStreamName'

 "3.15.0/1"
]

$ pcluster get-image-log-events --image-id IMAGE_ID --region REGION \
--log-stream-name 3.15.0/1 --limit 3
{
 "nextToken": "f/36295977202298886557255241372854078762600452615936671762",
 "prevToken": "b/36295977196879805474012299949460899222346900769983430672",
 "events": [
   {
     "message": "ExecuteBash: FINISHED EXECUTION",
     "timestamp": "2022-04-05T22:13:26.633Z"
   },
   {
     "message": "Document arn:aws:imagebuilder:us-east-1:123456789012:component/parallelclusterimage-test-abcd1234-ef56-gh78-ij90-1234abcd5678/3.15.0/1",
     "timestamp": "2022-04-05T22:13:26.741Z"
   },
   {
     "message": "TOE has completed execution successfully",
     "timestamp": "2022-04-05T22:13:26.819Z"
   }
 ]
}
```

繼續檢查 [`describe-image`](pcluster.describe-image-v3.md)命令，直到您看到 `BUILD_COMPLETE` 狀態為止。

```
$ pcluster describe-image --image-id IMAGE_ID --region REGION
{
 "imageConfiguration": {
   "url": "https://parallelcluster-1234abcd5678efgh-v1-do-not-delete.s3.us-east-1.amazonaws.com/parallelcluster/3.15.0/images/IMAGE_ID-abcd1234efgh5678/configs/image-config.yaml?Signature=..."
 },
 "imageId": "IMAGE_ID",
 "imageBuildStatus": "BUILD_COMPLETE",
 "region": "us-east-1",
 "ec2AmiInfo": {
     "amiName": "IMAGE_ID 2022-04-05T21-39-24.020Z",
     "amiId": "ami-1234stuv5678wxyz",
     "description": "AWS ParallelCluster AMI for alinux2, kernel-4.14.238-182.422.amzn2.x86_64, lustre-2.10.8-5.amzn2.x86_64, efa-1.13.0-1.amzn2.x86_64, dcv-2021.1.10598-1.el7.x86_64, slurm-20-11-8-1",
     "state": "AVAILABLE",
     "tags": [
      {
        "value": "2021.3.11591-1.el7.x86_64",
        "key": "parallelcluster:dcv_version"
      },
      ...
     ],
   "architecture": "x86_64"
 },
 "version": "3.15.0"      
}
```

如果您需要對自訂 AMI 建立問題進行疑難排解，請建立映像日誌的封存，如下列步驟所述。

視 `--output` 參數而定，可以將日誌存檔在 Amazon S3 儲存貯體或本機檔案中。

```
$ pcluster export-image-logs --image-id IMAGE_ID --region REGION \
--bucket BUCKET_NAME --bucket-prefix BUCKET_FOLDER
{
 "url": "https://BUCKET_NAME.s3.us-east-1.amazonaws.com/BUCKET-FOLDER/IMAGE_ID-logs-202209071136.tar.gz?AWSAccessKeyId=..."
}

$ pcluster export-image-logs --image-id IMAGE_ID \
--region REGION --bucket BUCKET_NAME --bucket-prefix BUCKET_FOLDER --output-file /tmp/archive.tar.gz
{
 "path": "/tmp/archive.tar.gz"
}
```

封存包含與映像建置器程序和 CloudFormation 堆疊事件相關的 CloudWatch Logs 串流。命令可能需要幾分鐘的時間才能執行。

 **管理自訂 AMIs** 

從 AWS ParallelCluster 3.0.0 開始，在 CLI 中新增一組新的命令，以建置、監控和管理映像生命週期。如需 命令的詳細資訊，請參閱 [pcluster 命令](pcluster-v3.md)。

## 修改 AWS ParallelCluster AMI
<a name="modify-an-aws-parallelcluster-ami-v3"></a>

此方法包含透過在官方 AWS ParallelCluster AMI 上新增自訂來修改官方 AMI。 AWS ParallelCluster AMIs 會以新版本更新。這些 AMIs 具有安裝和設定時， AWS ParallelCluster 運作所需的所有元件。您可以從其中一個開始，做為您的基礎。

重點：
+ 此方法比 [`build-image`](pcluster.build-image-v3.md)命令更快。不過，這是手動程序，無法自動重複。
+ 透過此方法，您無法存取可透過 CLI 取得的日誌擷取和映像生命週期管理命令。

步驟：

------
#### [ New Amazon EC2 console ]

1. 尋找對應至您使用之特定 AWS 區域 的 AMI。若要尋找，請使用 [`pcluster list-official-images`](pcluster.list-official-images-v3.md)命令搭配 `--region` 參數，以選取特定 AWS 區域 和 `--os`和 `--architecture` 參數，以您想要使用的作業系統和架構來篩選所需的 AMI。從輸出擷取 Amazon EC2 映像 ID。

1. 登入 AWS 管理主控台 ，並在 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/)：// 開啟 Amazon EC2 主控台。

1. 在導覽窗格中，選擇**影像**，然後選擇 **AMIs**。搜尋擷取的 EC2 映像 ID，選取 AMI，然後從 **AMI 選擇啟動執行個體**。

1. 向下捲動並選擇您的**執行個體類型**。

1. 選擇您的**金鑰對**和**啟動執行個體**。

1. 使用作業系統使用者和 SSH金鑰登入您的執行個體。

1. 手動自訂執行個體以符合您的需求。

1. 執行下列命令來準備您的執行個體以建立 AMI。

   ```
   sudo /usr/local/sbin/ami_cleanup.sh
   ```

1. 從主控台中，選擇**執行個體狀態**和**停止執行個體**。

   導覽至**執行個體**、選擇新執行個體、選取**執行個體狀態**和**停止執行個體**。

1. 使用 Amazon EC2 主控台或 AWS CLI [create-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-image.html) 從執行個體建立新的 AMI。

**從 Amazon EC2 主控台**

   1. 在導覽窗格中，選擇 **Instances (執行個體)**。

   1. 選擇您建立和修改的執行個體。

   1. 在**動作**中，選擇**映像**，然後選擇**建立映像**。

   1. 選擇 **Create Image (建立映像)**。

1. 在叢集組態的 [`CustomAmi`](Scheduling-v3.md#yaml-Scheduling-SlurmQueues-Image-CustomAmi) 欄位中輸入新的 AMI ID，然後建立叢集。

------
#### [ Old Amazon EC2 console ]

1. 尋找對應至您使用之特定 AWS 區域 的 AWS ParallelCluster AMI。若要尋找它，您可以使用 [`pcluster list-official-images`](pcluster.list-official-images-v3.md)命令搭配 `--region` 參數，選取特定 AWS 區域 和 `--os`和 `--architecture` 參數，以您想要使用的作業系統和架構來篩選所需的 AMI。您可以從輸出擷取 Amazon EC2 Image ID。

1. 登入 AWS 管理主控台 ，並在 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/)：// 開啟 Amazon EC2 主控台。

1. 在導覽窗格中，選擇**影像**，然後選擇 **AMIs**。設定**公用映像**的篩選條件，並搜尋擷取的 EC2 映像 ID，選取 AMI，然後選擇**啟動**。

1. 選擇您的執行個體類型，然後選取**下一步：設定執行個體詳細資訊**或**檢閱並啟動**以啟動您的執行個體。

1. 選擇**啟動**、選取您的**金鑰對**和**啟動執行個體**。

1. 使用作業系統使用者和 SSH 金鑰來登入執行個體。如需詳細資訊，請導覽至**執行個體**，選取新的執行個體並**連線**。

1. 手動自訂執行個體以符合您的需求。

1. 執行下列命令，以備妥執行個體來建立 AMI：

   ```
   sudo /usr/local/sbin/ami_cleanup.sh
   ```

1. 從 Amazon EC2 主控台，在導覽窗格中選擇**執行個體**，選擇您的新執行個體，然後選擇**動作**、**執行個體狀態**和**停止**。

1. 使用 Amazon EC2 主控台或 AWS CLI [create-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-image.html) 從執行個體建立新的 AMI。

**從 Amazon EC2 主控台**

   1. 在導覽窗格中，選擇 **Instances (執行個體)**。

   1. 選擇您建立和修改的執行個體。

   1. 在**動作**中，選擇**映像**，然後選擇**建立映像**。

   1. 選擇 **Create Image (建立映像)**。

1. 在叢集組態的 [`CustomAmi`](Scheduling-v3.md#yaml-Scheduling-SlurmQueues-Image-CustomAmi) 欄位中輸入新的 AMI ID，然後建立叢集。

------

# 整合 Active Directory
<a name="tutorials_05_multi-user-ad"></a>

在本教學課程中，您會建立多個使用者環境。此環境包含與 (Active Directory) 整合 AWS ParallelCluster AWS Managed Microsoft AD 的 `corp.example.com`。您可以設定 `Admin`使用者來管理 目錄、`ReadOnly`使用者來讀取目錄，以及`user000`使用者來登入叢集。您可以使用自動化路徑或手動路徑來建立聯網資源、Active Directory (AD)，以及您用來設定 AD 的 Amazon EC2 執行個體。無論您的路徑為何，您建立的基礎設施都會預先設定為 AWS ParallelCluster 使用下列其中一種方法進行整合：
+ 具有憑證驗證的 LDAPS （建議為最安全的選項）
+ 沒有憑證驗證的 LDAPS
+ LDAP

LDAP 本身*不提供*加密。為了確保安全傳輸潛在敏感資訊，強烈建議您將 LDAPS (LDAP over TLS/SSL) 用於與 ADs 整合的叢集。如需詳細資訊，請參閱《 Directory Service *管理指南*》中的[使用 啟用伺服器端 LDAPS AWS Managed Microsoft AD](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_ldap_server_side.html)。

建立這些資源之後，請繼續設定和建立與 Active Directory (AD) 整合的叢集。建立叢集之後，請以您建立的使用者身分登入。如需您在本教學課程中建立組態的詳細資訊，請參閱 [多個使用者存取叢集](multi-user-v3.md)和 [`DirectoryService`](DirectoryService-v3.md)組態區段。

本教學課程說明如何建立支援多個使用者存取叢集的環境。本教學課程不涵蓋您建立和使用 Directory Service AD 的方式。您在本教學 AWS Managed Microsoft AD 課程中設定 所採取的步驟僅供測試之用。*它們不會*用來取代官方文件和最佳實務，請參閱《 *Directory Service 管理指南*》中的 [AWS Managed Microsoft AD](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_microsoft_ad.html)和 [Simple AD](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_simple_ad.html)。

**注意**  
目錄使用者密碼會根據目錄密碼政策屬性定義過期。若要使用 重設目錄密碼 AWS ParallelCluster，請參閱 [如何重設使用者密碼和過期的密碼](troubleshooting-v3-multi-user.md#troubleshooting-v3-multi-user-reset-passwd)。

**注意**  
由於網域控制站變更和目錄維護，目錄網域控制站 IP 地址可能會變更。如果您選擇自動快速建立方法來建立目錄基礎設施，則必須在目錄 IP 地址變更時，手動對齊目錄控制器前面的負載平衡器。如果您使用快速建立方法，目錄 IP 地址不會自動與負載平衡器對齊。

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**先決條件**
+ AWS ParallelCluster [已安裝 ](install-v3-parallelcluster.md)。
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ 您有 [Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 您有一個 IAM 角色，具有執行 CLI [`pcluster`](pcluster-v3.md) 所需的[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)。

當您完成教學課程時，請以您自己的名稱`region-id`和 ID 取代 `d-abcdef01234567890`，`inputs highlighted in red`例如 和 。 IDs 將 取代`0123456789012`為您的 AWS 帳戶 數字。

# 建立 AD 基礎設施
<a name="tutorials_05_multi-user-ad-step1"></a>

選擇*自動化*索引標籤，使用 CloudFormation 快速建立範本建立 Active Directory (AD) 基礎設施。

選擇*手動*索引標籤以手動建立 AD 基礎設施。

## 自動化
<a name="tutorials_05_multi-user-ad-step1-automated"></a>

1. 登入 AWS 管理主控台。

1. 開啟 [CloudFormation Quick Create (region us-east-1)](https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/create/review?stackName=pcluster-ad&templateURL=https://us-east-1-aws-parallelcluster.s3.amazonaws.com/templates/1-click/ad-integration.yaml)，以在 CloudFormation 主控台中建立下列資源：
   + 如果未指定 VPC，則具有兩個子網路和路由以進行公開存取的 VPC。
   +  AWS Managed Microsoft AD。
   + 加入 AD 的 Amazon EC2 執行個體，可用來管理目錄。

1. 在**快速建立堆疊**頁面**參數**區段中，輸入下列參數的密碼：
   + **AdminPassword**
   + **ReadOnlyPassword**
   + **UserPassword**

   請記下密碼。您稍後在本教學課程中使用它們。

1. 針對 **DomainName**，輸入 **corp.example.com**

1. 針對 **Keypair**，輸入 Amazon EC2 金鑰對的名稱。

1. 勾選方塊以確認頁面底部的每個存取功能。

1. 選擇**建立堆疊**。

1. 在 CloudFormation 堆疊達到 `CREATE_COMPLETE` 狀態後，選擇堆疊的**輸出**索引標籤。請記下輸出資源名稱和 IDs，因為您需要在後續步驟中使用它們。輸出提供建立叢集所需的資訊。  
![\[圖表顯示 中建立的堆疊輸出 AWS 管理主控台。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/ad-cfn.png)

1. 若要完成練習 [（選用） 管理 AD 使用者和群組](tutorials_05_multi-user-ad-step2.md)，您需要目錄 ID。選擇**資源**並向下捲動以記下目錄 ID。

1. 在 [（選用） 管理 AD 使用者和群組](tutorials_05_multi-user-ad-step2.md)或 繼續[建立叢集](tutorials_05_multi-user-ad-step3.md)。

## 手動
<a name="tutorials_05_multi-user-ad-step1-manual"></a>

為目錄服務建立 VPC，其中兩個子網路位於不同的可用區域和 AWS Managed Microsoft AD。

### 建立 AD
<a name="tutorials_05_multi-user-ad-step1-manual-ad"></a>

**注意**  
目錄和網域名稱為 `corp.example.com`。簡短名稱為 `CORP`。
變更指令碼中的`Admin`密碼。
Active Directory (AD) 至少需要 15 分鐘才能建立。

使用下列 Python 指令碼在本機建立 VPC、子網路和 AD 資源 AWS 區域。將此檔案儲存為 `ad.py` 並執行。

```
import boto3
import time
from pprint import pprint

vpc_name = "PclusterVPC"
ad_domain = "corp.example.com"
admin_password = "asdfASDF1234"

ec2 = boto3.client("ec2")
ds = boto3.client("ds")
region = boto3.Session().region_name

# Create the VPC, Subnets, IGW, Routes
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")["Vpc"]
vpc_id = vpc["VpcId"]
time.sleep(30)
ec2.create_tags(Resources=[vpc_id], Tags=[{"Key": "Name", "Value": vpc_name}])
subnet1 = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.0.0.0/17", AvailabilityZone=f"{region}a")["Subnet"]
subnet1_id = subnet1["SubnetId"]
time.sleep(30)
ec2.create_tags(Resources=[subnet1_id], Tags=[{"Key": "Name", "Value": f"{vpc_name}/subnet1"}])
ec2.modify_subnet_attribute(SubnetId=subnet1_id, MapPublicIpOnLaunch={"Value": True})
subnet2 = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.0.128.0/17", AvailabilityZone=f"{region}b")["Subnet"]
subnet2_id = subnet2["SubnetId"]
time.sleep(30)
ec2.create_tags(Resources=[subnet2_id], Tags=[{"Key": "Name", "Value": f"{vpc_name}/subnet2"}])
ec2.modify_subnet_attribute(SubnetId=subnet2_id, MapPublicIpOnLaunch={"Value": True})
igw = ec2.create_internet_gateway()["InternetGateway"]
ec2.attach_internet_gateway(InternetGatewayId=igw["InternetGatewayId"], VpcId=vpc_id)
route_table = ec2.describe_route_tables(Filters=[{"Name": "vpc-id", "Values": [vpc_id]}])["RouteTables"][0]
ec2.create_route(RouteTableId=route_table["RouteTableId"], DestinationCidrBlock="0.0.0.0/0", GatewayId=igw["InternetGatewayId"])
ec2.modify_vpc_attribute(VpcId=vpc_id, EnableDnsSupport={"Value": True})
ec2.modify_vpc_attribute(VpcId=vpc_id, EnableDnsHostnames={"Value": True})

# Create the Active Directory
ad = ds.create_microsoft_ad(
    Name=ad_domain,
    Password=admin_password,
    Description="ParallelCluster AD",
    VpcSettings={"VpcId": vpc_id, "SubnetIds": [subnet1_id, subnet2_id]},
    Edition="Standard",
)
directory_id = ad["DirectoryId"]

# Wait for completion
print("Waiting for the directory to be created...")
directories = ds.describe_directories(DirectoryIds=[directory_id])["DirectoryDescriptions"]
directory = directories[0]
while directory["Stage"] in {"Requested", "Creating"}:
    time.sleep(3)
    directories = ds.describe_directories(DirectoryIds=[directory_id])["DirectoryDescriptions"]
    directory = directories[0]
    
dns_ip_addrs = directory["DnsIpAddrs"]

pprint({"directory_id": directory_id,
        "vpc_id": vpc_id,
        "subnet1_id": subnet1_id,
        "subnet2_id": subnet2_id,
        "dns_ip_addrs": dns_ip_addrs})
```

以下是 Python 指令碼的範例輸出。

```
{
  "directory_id": "d-abcdef01234567890",
  "dns_ip_addrs": ["192.0.2.254", "203.0.113.237"],
  "subnet1_id": "subnet-021345abcdef6789",
  "subnet2_id": "subnet-1234567890abcdef0",
  "vpc_id": "vpc-021345abcdef6789"
}
```

記下輸出資源名稱和 IDs。您可以在後續步驟中使用它們。

指令碼完成後，請繼續下一個步驟。

### 建立 Amazon EC2 執行個體
<a name="tutorials_05_multi-user-ad-step1-manual-instance"></a>

------
#### [ New Amazon EC2 console ]

1. 登入 AWS 管理主控台。

1. 如果您沒有連接步驟 4 中所列政策的角色，請開啟位於 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 的 IAM 主控台。否則，請跳至步驟 5。

1. 建立`ResetUserPassword`政策，將紅色反白顯示的內容取代為您執行以建立 AD 之指令碼輸出的 AWS 區域 ID、帳戶 ID 和目錄 ID。

   ResetUserPassword

   ```
   {
          "Statement": [
           {
               "Action": [
                   "ds:ResetUserPassword"
               ],
               "Resource": "arn:aws:ds:region-id:123456789012:directory/d-abcdef01234567890",
               "Effect": "Allow"
           }
       ]
   }
   ```

1. 建立已連接下列政策的 IAM 角色。
   + AWS 受管政策 [AmazonSSMManagedInstanceCore](https://console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore)
   + AWS 受管政策 [AmazonSSMDirectoryServiceAccess](https://console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AmazonSSMDirectoryServiceAccess)
   + ResetUserPassword 政策

1. 前往 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/) 開啟 Amazon EC2 主控台。

1. 在 **Amazon EC2 儀表板**中，選擇**啟動執行個體**。

1. 在**應用程式和作業系統映像**中，選取最近的 Amazon Linux 2 AMI。

1. 針對**執行個體類型**，選擇 t2.micro。

1. 針對**金鑰對**，選擇金鑰對。

1. 針對**網路設定**，選擇**編輯**。

1. 針對 **VPC**，選取目錄 VPC。

1. 向下捲動並選取**進階詳細資訊**。

1. 在**進階詳細資訊**的**網域聯結目錄中**，選擇 **corp.example.com**。

1. 針對 **IAM 執行個體描述檔**，選擇您在步驟 1 中建立的角色，或連接步驟 4 中列出政策的角色。

1. 在**摘要**中，選擇**啟動執行個體**。

1. 請記下執行個體 ID （例如 i-1234567890abcdef0)，並等待執行個體完成啟動。

1. 執行個體啟動後，請繼續下一個步驟。

------
#### [ Old Amazon EC2 console ]

1. 登入 AWS 管理主控台。

1. 如果您沒有連接步驟 4 中所列政策的角色，請開啟位於 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 的 IAM 主控台。否則，請跳至步驟 5。

1. 建立 `ResetUserPassword` 政策。將紅色反白內容取代為您執行的指令碼輸出中的 AWS 區域 ID、 AWS 帳戶 ID 和目錄 ID，以建立 Active Directory (AD)。

   ResetUserPassword

   ```
   {
           "Statement": [
               {
                   "Action": [
                       "ds:ResetUserPassword"
                   ],
                   "Resource": "arn:aws:ds:region-id:123456789012:directory/d-abcdef01234567890",
                   "Effect": "Allow"
               }
           ]
        }
   ```

1. 建立已連接下列政策的 IAM 角色。
   + AWS 受管政策 [AmazonSSMManagedInstanceCore](https://console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore)
   + AWS 受管政策 [AmazonSSMDirectoryServiceAccess](https://console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AmazonSSMDirectoryServiceAccess)
   + ResetUserPassword 政策

1. 前往 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/) 開啟 Amazon EC2 主控台。

1. 在 **Amazon EC2 儀表板**中，選擇**啟動執行個體**。

1. 在**應用程式和作業系統映像**中，選取最近的 Amazon Linux 2 AMI。

1. 對於 **Instance type (執行個體類型)**，選擇 t2.micro。

1. 針對**金鑰對**，選擇金鑰對。

1. 在**網路設定**中，選擇**編輯**。

1. 在**網路設定** **VPC** 中，選取目錄 VPC。

1. 向下捲動並選取**進階詳細資訊**。

1. 在**進階詳細資訊**的**網域聯結目錄中**，選擇 **corp.example.com**。

1. 在**進階詳細資訊**、**執行個體描述**檔中，選擇您在步驟 1 中建立的角色，或使用連接步驟 4 中所列政策的角色。

1. 在**摘要**中，選擇**啟動執行個體**。

1. 請記下執行個體 ID （例如 i-1234567890abcdef0)，並等待執行個體完成啟動。

1. 執行個體啟動後，請繼續下一個步驟。

------

### 將執行個體加入 AD
<a name="tutorials_05_multi-user-ad-step1-manual-join"></a>

1. 

**連線至您的執行個體，並以 身分加入 AD 領域`admin`。**

   執行下列命令以連線至執行個體。

   ```
   $ INSTANCE_ID="i-1234567890abcdef0"
   ```

   ```
   $ PUBLIC_IP=$(aws ec2 describe-instances \
   --instance-ids $INSTANCE_ID \
   --query "Reservations[0].Instances[0].PublicIpAddress" \
   --output text)
   ```

   ```
   $ ssh -i ~/.ssh/keys/keypair.pem ec2-user@$PUBLIC_IP
   ```

1. 

**安裝必要的軟體並加入領域。**

   ```
   $ sudo yum -y install sssd realmd oddjob oddjob-mkhomedir adcli samba-common samba-common-tools krb5-workstation openldap-clients policycoreutils-python
   ```

1. 

**將管理員密碼取代為`admin`您的密碼。**

   ```
   $ ADMIN_PW="asdfASDF1234"
   ```

   ```
   $ echo $ADMIN_PW | sudo realm join -U Admin corp.example.com
   Password for Admin:
   ```

   如果上述 成功，您就會加入領域，並且可以繼續進行下一個步驟。

### 將使用者新增至 AD
<a name="tutorials_05_multi-user-ad-step1-manual-join-add-users"></a>

1. 

**建立 ReadOnlyUser 和其他使用者。**

   在此步驟中，您會使用您在上一個步驟中安裝的 [adcli](https://www.mankier.com/package/adcli) 和 [openldap-clients](https://www.mankier.com/package/openldap-clients) 工具。

   ```
   $ echo $ADMIN_PW | adcli create-user -x -U Admin --domain=corp.example.com --display-name=ReadOnlyUser ReadOnlyUser
   ```

   ```
   $ echo $ADMIN_PW | adcli create-user -x -U Admin --domain=corp.example.com --display-name=user000 user000
   ```

1. **確認已建立使用者：**

   目錄 DNS IP 地址是 Python 指令碼的輸出。

   ```
   $ DIRECTORY_IP="192.0.2.254"
   ```

   ```
   $ ldapsearch -x -h $DIRECTORY_IP -D Admin -w $ADMIN_PW -b "cn=ReadOnlyUser,ou=Users,ou=CORP,dc=corp,dc=example,dc=com"
   ```

   ```
   $ ldapsearch -x -h $DIRECTORY_IP -D Admin -w $ADMIN_PW -b "cn=user000,ou=Users,ou=CORP,dc=corp,dc=example,dc=com"
   ```

   根據預設，當您使用 建立使用者時`ad-cli`，使用者會停用。

1. 

****從本機電腦重設和啟用使用者密碼：****

   登出 Amazon EC2 執行個體。
**注意**  
`ro-p@ssw0rd` 是從 `ReadOnlyUser`擷取的密碼 AWS Secrets Manager。
`user-p@ssw0rd` 是在您將 (`ssh`) 連線到叢集時提供的叢集使用者密碼。

   `directory-id` 是 Python 指令碼的輸出。

   ```
   $ DIRECTORY_ID="d-abcdef01234567890"
   ```

   ```
   $ aws ds reset-user-password \
   --directory-id $DIRECTORY_ID \
   --user-name "ReadOnlyUser" \
   --new-password "ro-p@ssw0rd" \
   --region "region-id"
   ```

   ```
   $ aws ds reset-user-password \
   --directory-id $DIRECTORY_ID \
   --user-name "user000" \
   --new-password "user-p@ssw0rd" \
   --region "region-id"
   ```

1. **將密碼新增至 Secrets Manager 秘密。**

   現在您已建立 `ReadOnlyUser`並設定密碼，請將它存放在 AWS ParallelCluster 用於驗證登入的秘密中。

   使用 Secrets Manager 建立新的秘密，將 的密碼保留`ReadOnlyUser`為 值。秘密值格式必須是純文字 （而非 JSON 格式）。記下秘密 ARN 以供未來步驟使用。

   ```
   $ aws secretsmanager create-secret --name "ADSecretPassword" \
   --region region_id \
   --secret-string "ro-p@ssw0rd" \
   --query ARN \
   --output text
   arn:aws:secretsmanager:region-id:123456789012:secret:ADSecretPassword-1234
   ```

### 具有憑證驗證 （建議） 設定的 LDAPS
<a name="tutorials_05_multi-user-ad-step1-manual-ldaps"></a>

記下資源 IDs。您稍後會在步驟中使用它們。

1. 

**在本機產生網域憑證。**

   ```
   $ PRIVATE_KEY="corp-example-com.key"
   CERTIFICATE="corp-example-com.crt"
   printf ".\n.\n.\n.\n.\ncorp.example.com\n.\n" | openssl req -x509 -sha256 -nodes -newkey rsa:2048 -keyout $PRIVATE_KEY -days 365 -out $CERTIFICATE
   ```

1. 

**將憑證儲存到 Secrets Manager，以便稍後可從叢集內擷取。**

   ```
   $ aws secretsmanager create-secret --name example-cert \
     --secret-string file://$CERTIFICATE \
     --region region-id
   {
     "ARN": "arn:aws:secretsmanager:region-id:123456789012:secret:example-cert-123abc",
     "Name": "example-cert",
     "VersionId": "14866070-092a-4d5a-bcdd-9219d0566b9c"
   }
   ```

1. 將下列政策新增至您建立的 IAM 角色，以將 Amazon EC2 執行個體加入 AD 網域。

   `PutDomainCertificateSecrets`

   ```
   {
       "Statement": [
           {
               "Action": [
                   "secretsmanager:PutSecretValue"
               ],
               "Resource": [
                   "arn:aws:secretsmanager:region-id:123456789012:secret:example-cert-123abc"
               ],
               "Effect": "Allow"
           }
       ]
   }
   ```

1. 

**將憑證匯入至 AWS Certificate Manager (ACM)。**

   ```
   $ aws acm import-certificate --certificate fileb://$CERTIFICATE \
     --private-key fileb://$PRIVATE_KEY \
     --region region-id
   {
     "CertificateArn": "arn:aws:acm:region-id:123456789012:certificate/343db133-490f-4077-b8d4-3da5bfd89e72"
   }
   ```

1. 

**建立 和放在 Active Directory 端點前面的負載平衡器。**

   ```
   $ aws elbv2 create-load-balancer --name CorpExampleCom-NLB \
     --type network \
     --scheme internal \
     --subnets subnet-1234567890abcdef0 subnet-021345abcdef6789 \
     --region region-id
   {
     "LoadBalancers": [
       {
         "LoadBalancerArn": "arn:aws:elasticloadbalancing:region-id:123456789012:loadbalancer/net/CorpExampleCom-NLB/3afe296bf4ba80d4",
         "DNSName": "CorpExampleCom-NLB-3afe296bf4ba80d4.elb.region-id.amazonaws.com",
         "CanonicalHostedZoneId": "Z2IFOLAFXWLO4F",
         "CreatedTime": "2022-05-05T12:56:55.988000+00:00",
         "LoadBalancerName": "CorpExampleCom-NLB",
         "Scheme": "internal",
         "VpcId": "vpc-021345abcdef6789",
         "State": {
           "Code": "provisioning"
          },
          "Type": "network",
          "AvailabilityZones": [
            {
              "ZoneName": "region-idb",
              "SubnetId": "subnet-021345abcdef6789",
              "LoadBalancerAddresses": []
            },
            {
              "ZoneName": "region-ida",
              "SubnetId": "subnet-1234567890abcdef0",
              "LoadBalancerAddresses": []
            }
          ],
          "IpAddressType": "ipv4"
       }   
     ]
   }
   ```

1. 

**建立目標為 Active Directory 端點的目標群組。**

   ```
   $ aws elbv2 create-target-group --name CorpExampleCom-Targets --protocol TCP \
     --port 389 \
     --target-type ip \
     --vpc-id vpc-021345abcdef6789 \
     --region region-id
   {
     "TargetGroups": [
       {
         "TargetGroupArn": "arn:aws:elasticloadbalancing:region-id:123456789012:targetgroup/CorpExampleCom-Targets/44577c583b695e81",
         "TargetGroupName": "CorpExampleCom-Targets",
         "Protocol": "TCP",
         "Port": 389,
         "VpcId": "vpc-021345abcdef6789",
         "HealthCheckProtocol": "TCP",
         "HealthCheckPort": "traffic-port",
         "HealthCheckEnabled": true,
         "HealthCheckIntervalSeconds": 30,
         "HealthCheckTimeoutSeconds": 10,
         "HealthyThresholdCount": 3,
         "UnhealthyThresholdCount": 3,
         "TargetType": "ip",
         "IpAddressType": "ipv4"
       }
     ]
   }
   ```

1. 

**將 Active Directory (AD) 端點註冊到目標群組。**

   ```
   $ aws elbv2 register-targets --target-group-arn arn:aws:elasticloadbalancing:region-id:123456789012:targetgroup/CorpExampleCom-Targets/44577c583b695e81 \
     --targets Id=192.0.2.254,Port=389 Id=203.0.113.237,Port=389 \
     --region region-id
   ```

1. 

**使用憑證建立 LB 接聽程式。**

   ```
   $ aws elbv2 create-listener --load-balancer-arn arn:aws:elasticloadbalancing:region-id:123456789012:loadbalancer/net/CorpExampleCom-NLB/3afe296bf4ba80d4 \
     --protocol TLS \
     --port 636 \
     --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:region-id:123456789012:targetgroup/CorpExampleCom-Targets/44577c583b695e81 \
     --ssl-policy ELBSecurityPolicy-TLS-1-2-2017-01 \
     --certificates CertificateArn=arn:aws:acm:region-id:123456789012:certificate/343db133-490f-4077-b8d4-3da5bfd89e72 \
     --region region-id
     "Listeners": [
     {
       "ListenerArn": "arn:aws:elasticloadbalancing:region-id:123456789012:listener/net/CorpExampleCom-NLB/3afe296bf4ba80d4/a8f9d97318743d4b",
       "LoadBalancerArn": "arn:aws:elasticloadbalancing:region-id:123456789012:loadbalancer/net/CorpExampleCom-NLB/3afe296bf4ba80d4",
       "Port": 636,
       "Protocol": "TLS",
       "Certificates": [
         {
           "CertificateArn": "arn:aws:acm:region-id:123456789012:certificate/343db133-490f-4077-b8d4-3da5bfd89e72"
          }
        ],
        "SslPolicy": "ELBSecurityPolicy-TLS-1-2-2017-01",
        "DefaultActions": [
          {
            "Type": "forward",
            "TargetGroupArn": "arn:aws:elasticloadbalancing:region-id:123456789012:targetgroup/CorpExampleCom-Targets/44577c583b695e81",
            "ForwardConfig": {
              "TargetGroups": [
                {
                   "TargetGroupArn": "arn:aws:elasticloadbalancing:region-id:123456789012:targetgroup/CorpExampleCom-Targets/44577c583b695e81"
                 }
               ]
             }
           }
         ]
       }
     ]
   }
   ```

1. 

**建立託管區域，以在叢集 VPC 中探索網域。**

   ```
   $ aws route53 create-hosted-zone --name corp.example.com \
     --vpc VPCRegion=region-id,VPCId=vpc-021345abcdef6789 \
     --caller-reference "ParallelCluster AD Tutorial"
   {
     "Location": "https://route53.amazonaws.com/2013-04-01/hostedzone/Z09020002B5MZQNXMSJUB",
     "HostedZone": {
       "Id": "/hostedzone/Z09020002B5MZQNXMSJUB",
       "Name": "corp.example.com.",
       "CallerReference": "ParallelCluster AD Tutorial",
       "Config": {
            "PrivateZone": true
       },
       "ResourceRecordSetCount": 2
     },
     "ChangeInfo": {
       "Id": "/change/C05533343BF3IKSORW1TQ",
       "Status": "PENDING",
       "SubmittedAt": "2022-05-05T13:21:53.863000+00:00"
     },
     "VPC": {
       "VPCRegion": "region-id",
       "VPCId": "vpc-021345abcdef6789"
     }
   }
   ```

1. 

**使用`recordset-change.json`下列內容建立名為 的檔案。 `HostedZoneId`是負載平衡器的正式託管區域 ID。**

   ```
   {
     "Changes": [
       {
         "Action": "CREATE",
         "ResourceRecordSet": {
           "Name": "corp.example.com",
           "Type": "A",
           "Region": "region-id",
           "SetIdentifier": "example-active-directory",
           "AliasTarget": {
             "HostedZoneId": "Z2IFOLAFXWLO4F",
             "DNSName": "CorpExampleCom-NLB-3afe296bf4ba80d4.elb.region-id.amazonaws.com",
             "EvaluateTargetHealth": true
           }
         }
       }
     ]
   }
   ```

1. 

**將記錄集變更提交至託管區域，這次使用託管區域 ID。**

   ```
   $ aws route53 change-resource-record-sets --hosted-zone-id Z09020002B5MZQNXMSJUB \
     --change-batch file://recordset-change.json
   {
     "ChangeInfo": {
       "Id": "/change/C0137926I56R3GC7XW2Y",
       "Status": "PENDING",
       "SubmittedAt": "2022-05-05T13:40:36.553000+00:00"
     }
   }
   ```

1. 

**使用`policy.json`下列內容建立政策文件。**

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Action": [
                   "secretsmanager:GetSecretValue"
               ],
               "Resource": [
                   "arn:aws:secretsmanager:us-east-1:123456789012:secret:example-cert-abc123"
               ],
               "Effect": "Allow"
           }
       ]
   }
   ```

------

1. 

**使用`policy.json`下列內容建立名為 的政策文件。**

   ```
   $ aws iam create-policy --policy-name ReadCertExample \
     --policy-document file://policy.json
   {
     "Policy": {
       "PolicyName": "ReadCertExample",
       "PolicyId": "ANPAUUXUVBC42VZSI4LDY",
       "Arn": "arn:aws:iam::123456789012:policy/ReadCertExample-efg456",
       "Path": "/",
       "DefaultVersionId": "v1",
       "AttachmentCount": 0,
       "PermissionsBoundaryUsageCount": 0,
       "IsAttachable": true,
       "CreateDate": "2022-05-05T13:42:18+00:00",
       "UpdateDate": "2022-05-05T13:42:18+00:00"
     }
   }
   ```

1. 繼續遵循 [（選用） 管理 AD 使用者和群組](tutorials_05_multi-user-ad-step2.md)或 中的步驟[建立叢集](tutorials_05_multi-user-ad-step3.md)。

# （選用） 管理 AD 使用者和群組
<a name="tutorials_05_multi-user-ad-step2"></a>

在此步驟中，您可以從加入 Active Delivery (AD) 網域的 Amazon EC2 Amazon Linux 2 執行個體管理使用者和群組。

如果您遵循*自動化*路徑，請重新啟動並登入在自動化過程中建立的 AD 聯結執行個體。

如果您遵循*手動*路徑，請重新啟動並登入您在先前步驟中建立並加入 AD 的執行個體。

在這些步驟中，您會使用在上述步驟中安裝在執行個體中的 [adcli](https://www.mankier.com/package/adcli) 和 [openldap-clients](https://www.mankier.com/package/openldap-clients) 工具。

**登入已加入 AD 網域的 Amazon EC2 執行個體**

1. 從 Amazon EC2 主控台中選取在先前步驟中建立的無標題 Amazon EC2 執行個體。執行個體狀態可能**已停止**。

1. 如果執行個體狀態為**停止**，請選擇**執行個體狀態**，然後選擇**啟動執行個體**。

1. 狀態檢查通過後，選取執行個體，然後選擇**將** 和 SSH 連接至執行個體。

**在登入加入 AD 的 Amazon EC2 Amazon Linux 2 執行個體時管理使用者和群組**

當您使用 ` -U "Admin"`選項執行`adcli`命令時，系統會提示您輸入 AD `Admin`密碼。您可以在`ldapsearch`命令中包含 AD `Admin`密碼。

1. 

**建立使用者。**

   ```
   $ adcli create-user "clusteruser" --domain "corp.example.com" -U "Admin"
   ```

1. 

**設定使用者密碼。**

   ```
   $ aws --region "region-id" ds reset-user-password --directory-id "d-abcdef01234567890" --user-name "clusteruser" --new-password "new-p@ssw0rd"
   ```

1. 

**建立 群組。**

   ```
   $ adcli create-group "clusterteam" --domain "corp.example.com" -U "Admin"
   ```

1. 

**將使用者新增至群組。**

   ```
   $ adcli add-member "clusterteam" "clusteruser" --domain "corp.example.com" -U "Admin"
   ```

1. 

**描述使用者和群組。**

   描述所有使用者。

   ```
   $ ldapsearch "(&(objectClass=user))" -x -h "192.0.2.254" -b "DC=corp,DC=example,DC=com" -D "CN=Admin,OU=Users,OU=CORP,DC=corp,DC=example,DC=com" -w "p@ssw0rd"
   ```

   描述特定使用者。

   ```
   $ ldapsearch "(&(objectClass=user)(cn=clusteruser))" -x -h "192.0.2.254" -b "DC=corp,DC=example,DC=com" -D "CN=Admin,OU=Users,OU=CORP,DC=corp,DC=example,DC=com" -w "p@ssw0rd"
   ```

   描述具有名稱模式的所有使用者。

   ```
   $ ldapsearch "(&(objectClass=user)(cn=user*))" -x -h "192.0.2.254" -b "DC=corp,DC=example,DC=com" -D "CN=Admin,OU=Users,OU=CORP,DC=corp,DC=example,DC=com" -w "p@ssw0rd"
   ```

   描述屬於特定群組的所有使用者。

   ```
   $ ldapsearch "(&(objectClass=user)(memberOf=CN=clusterteam,OU=Users,OU=CORP,DC=corp,DC=example,DC=com))" -x -h "192.0.2.254" -b "DC=corp,DC=example,DC=com" -D "CN=Admin,OU=Users,OU=CORP,DC=corp,DC=example,DC=com" -w "p@ssw0rd"
   ```

   描述所有群組

   ```
   $ ldapsearch "objectClass=group" -x -h "192.0.2.254" -b "DC=corp,DC=example,DC=com" -D "CN=Admin,OU=Users,OU=CORP,DC=corp,DC=example,DC=com" -w "p@ssw0rd"
   ```

   描述特定群組

   ```
   $ ldapsearch "(&(objectClass=group)(cn=clusterteam))" -x -h "192.0.2.254" -b "DC=corp,DC=example,DC=com" -D "CN=Admin,OU=Users,OU=CORP,DC=corp,DC=example,DC=com" -w "p@ssw0rd"
   ```

1. 

**從群組中移除使用者。**

   ```
   $ adcli remove-member "clusterteam" "clusteruser" --domain "corp.example.com" -U "Admin"
   ```

1. 

**刪除使用者。**

   ```
   $ adcli delete-user "clusteruser" --domain "corp.example.com" -U "Admin"
   ```

1. 

**刪除群組。**

   ```
   $ adcli delete-group "clusterteam" --domain "corp.example.com" -U "Admin"
   ```

# 建立叢集
<a name="tutorials_05_multi-user-ad-step3"></a>

如果您尚未結束 Amazon EC2 執行個體，請現在執行此操作。

環境設定為建立叢集，可根據 Active Directory (AD) 驗證使用者。

建立簡單的叢集組態，並提供與連接到 AD 相關的設定。如需詳細資訊，請參閱 [`DirectoryService`](DirectoryService-v3.md) 一節。

選擇下列其中一個叢集組態，並將其複製到名為 `ldaps_config.yaml`、 `ldaps_nocert_config.yaml`或 的檔案`ldap_config.yaml`。

我們建議您使用憑證驗證選擇 LDAPS 組態。如果您選擇此組態，您還必須將引導指令碼複製到名為 的檔案`active-directory.head.post.sh`。此外，您必須將其存放在 Amazon S3 儲存貯體中，如組態檔案中所示。

## 具有憑證驗證組態的 LDAPS （建議）
<a name="tutorials_05_multi-user-ad-step3-ldaps"></a>

**注意**  
`KeyName`：其中一個 Amazon EC2 金鑰對。
`SubnetId / SubnetIds`：CloudFormation 快速建立堆疊 （自動化教學課程） 或 python 指令碼 （手動教學課程） 輸出中提供的其中一個子網路 IDs。
`Region`：您建立 AD 基礎設施的區域。
`DomainAddr`：此 IP 地址是 AD 服務的其中一個 DNS 地址。
`PasswordSecretArn`：包含 密碼之秘密的 Amazon Resource Name (ARN)`DomainReadOnlyUser`。
`BucketName`：存放引導指令碼的儲存貯體名稱。
`AdditionalPolicies` / `Policy`：讀取網域認證政策 ReadCertExample 的 Amazon Resource Name (ARN)。
`CustomActions` / `OnNodeConfigured` / `Args`：持有網域認證政策之秘密的 Amazon Resource Name (ARN)。
為了提高安全狀態，建議您使用 `HeadNode` / `Ssh` / `AllowedIps`組態來限制 SSH 對前端節點的存取。  
請注意， 中指定的憑證`LdapTlsCaCert`必須可供所有叢集節點存取。

**硬性要求**  
中指定的憑證`LdapTlsCaCert`必須可供所有叢集節點存取。  
無法存取憑證的節點將無法從 目錄解析使用者。

```
Region: region-id
Image:
  Os: alinux2
HeadNode: 
  InstanceType: t2.micro
  Networking:
    SubnetId: subnet-abcdef01234567890
  Ssh:
    KeyName: keypair
  Iam:
    AdditionalIamPolicies:
      - Policy: arn:aws:iam::123456789012:policy/ReadCertExample
    S3Access:
      - BucketName: amzn-s3-demo-bucket
        EnableWriteAccess: false
        KeyName: bootstrap/active-directory/active-directory.head.post.sh
  CustomActions:
    OnNodeConfigured:
      Script: s3://amzn-s3-demo-bucket/bootstrap/active-directory/active-directory.head.post.sh
      Args:
        - arn:aws:secretsmanager:region-id:123456789012:secret:example-cert-123abc
        - /opt/parallelcluster/shared/directory_service/domain-certificate.crt
Scheduling:
  Scheduler: slurm
  SlurmQueues:
    - Name: queue0
      ComputeResources:
        - Name: queue0-t2-micro
          InstanceType: t2.micro
          MinCount: 1
          MaxCount: 10         
      Networking:
        SubnetIds:
          - subnet-abcdef01234567890
DirectoryService:
  DomainName: corp.example.com
  DomainAddr: ldaps://corp.example.com
  PasswordSecretArn: arn:aws:secretsmanager:region-id:123456789012:secret:ADSecretPassword-1234
  DomainReadOnlyUser: cn=ReadOnlyUser,ou=Users,ou=CORP,dc=corp,dc=example,dc=com
  LdapTlsCaCert: /opt/parallelcluster/shared/directory_service/domain-certificate.crt
  LdapTlsReqCert: hard
```

**引導指令碼**

建立引導檔案之後，在將其上傳至 S3 儲存貯體之前，請執行 `chmod +x active-directory.head.post.sh` 以授予 AWS ParallelCluster 執行許可。

```
#!/bin/bash
set -e

CERTIFICATE_SECRET_ARN="$1"
CERTIFICATE_PATH="$2"

[[ -z $CERTIFICATE_SECRET_ARN ]] && echo "[ERROR] Missing CERTIFICATE_SECRET_ARN" && exit 1
[[ -z $CERTIFICATE_PATH ]] && echo "[ERROR] Missing CERTIFICATE_PATH" && exit 1

source /etc/parallelcluster/cfnconfig
REGION="${cfn_region:?}"

mkdir -p $(dirname $CERTIFICATE_PATH)
aws secretsmanager get-secret-value --region $REGION --secret-id $CERTIFICATE_SECRET_ARN --query SecretString --output text > $CERTIFICATE_PATH
```

## 沒有憑證驗證組態的 LDAPS
<a name="tutorials_05_multi-user-ad-step3-ldaps-no-cert"></a>

**注意**  
`KeyName`：其中一個 Amazon EC2 金鑰對。
`SubnetId / SubnetIds`：CloudFormation 快速建立堆疊 （自動化教學課程） 或 python 指令碼 （手動教學課程） 輸出中的其中一個子網路 IDs。
`Region`：您建立 AD 基礎設施的區域。
`DomainAddr`：此 IP 地址是 AD 服務的其中一個 DNS 地址。
`PasswordSecretArn`：包含 密碼之秘密的 Amazon Resource Name (ARN)`DomainReadOnlyUser`。
為了提高安全性狀態，建議您使用 HeadNode/Ssh/AllowedIps 組態來限制 SSH 對前端節點的存取。

```
Region: region-id
Image:
  Os: alinux2
HeadNode: 
  InstanceType: t2.micro
  Networking:
    SubnetId: subnet-abcdef01234567890
  Ssh:
    KeyName: keypair
Scheduling:
  Scheduler: slurm
  SlurmQueues:
    - Name: queue0
      ComputeResources:
        - Name: queue0-t2-micro
          InstanceType: t2.micro
          MinCount: 1
          MaxCount: 10         
      Networking:
        SubnetIds:
          - subnet-abcdef01234567890
DirectoryService:
  DomainName: corp.example.com
  DomainAddr: ldaps://corp.example.com
  PasswordSecretArn: arn:aws:secretsmanager:region-id:123456789012:secret:ADSecretPassword-1234
  DomainReadOnlyUser: cn=ReadOnlyUser,ou=Users,ou=CORP,dc=corp,dc=example,dc=com
  LdapTlsReqCert: never
```

## LDAP 組態
<a name="tutorials_05_multi-user-ad-step3-ldap"></a>

**注意**  
`KeyName`：其中一個 Amazon EC2 金鑰對。
`SubnetId / SubnetIds`：CloudFormation 快速建立堆疊 （自動教學課程） 或 python 指令碼 （手動教學課程） 輸出中提供的其中一個子網路 IDs。
`Region`：您建立 AD 基礎設施的區域。
`DomainAddr`：此 IP 地址是您 AD 服務的其中一個 DNS 地址。
`PasswordSecretArn`：包含 密碼之秘密的 Amazon Resource Name (ARN)`DomainReadOnlyUser`。
為了提高安全性狀態，建議您使用 HeadNode/Ssh/AllowedIps 組態來限制 SSH 對前端節點的存取。

```
Region: region-id
Image:
  Os: alinux2
HeadNode: 
  InstanceType: t2.micro
  Networking:
    SubnetId: subnet-abcdef01234567890
  Ssh:
    KeyName: keypair
Scheduling:
  Scheduler: slurm
  SlurmQueues:
    - Name: queue0
      ComputeResources:
        - Name: queue0-t2-micro
          InstanceType: t2.micro
          MinCount: 1
          MaxCount: 10         
      Networking:
        SubnetIds:
          - subnet-abcdef01234567890
DirectoryService:
  DomainName: dc=corp,dc=example,dc=com
  DomainAddr: ldap://192.0.2.254,ldap://203.0.113.237
  PasswordSecretArn: arn:aws:secretsmanager:region-id:123456789012:secret:ADSecretPassword-1234
  DomainReadOnlyUser: cn=ReadOnlyUser,ou=Users,ou=CORP,dc=corp,dc=example,dc=com
  AdditionalSssdConfigs:
    ldap_auth_disable_tls_never_use_in_production: True
```

使用下列命令建立您的叢集。

```
$ pcluster create-cluster --cluster-name "ad-cluster" --cluster-configuration "./ldaps_config.yaml"
{
  "cluster": {
    "clusterName": "pcluster",
    "cloudformationStackStatus": "CREATE_IN_PROGRESS",
    "cloudformationStackArn": "arn:aws:cloudformation:region-id:123456789012:stack/ad-cluster/1234567-abcd-0123-def0-abcdef0123456",
    "region": "region-id",
    "version": 3.15.0,
    "clusterStatus": "CREATE_IN_PROGRESS"
  }
}
```

# 以使用者身分連線至叢集
<a name="tutorials_05_multi-user-ad-step4"></a>

您可以使用下列命令來判斷叢集的狀態。

```
$ pcluster describe-cluster -n ad-cluster --region "region-id" --query "clusterStatus"
```

輸出如下。

```
"CREATE_IN_PROGRESS" / "CREATE_COMPLETE"
```

當狀態達到 時`"CREATE_COMPLETE"`，請使用建立的使用者名稱和密碼登入。

```
$ HEAD_NODE_IP=$(pcluster describe-cluster -n "ad-cluster" --region "region-id" --query headNode.publicIpAddress | xargs echo)
```

```
$ ssh user000@$HEAD_NODE_IP
```

您可以提供在 為新使用者建立的SSH金鑰，不使用密碼登入`/home/user000@HEAD_NODE_IP/.ssh/id_rsa`。

如果`ssh`命令成功，您已成功以已驗證使用 Active Directory (AD) 的使用者身分連線至叢集。

# 清除
<a name="tutorials_05_multi-user-ad-step5"></a>

1. 

**從本機電腦刪除叢集。**

   ```
   $ pcluster delete-cluster --cluster-name "ad-cluster" --region "region-id"
   {
     "cluster": {
       "clusterName": "ad-cluster",
       "cloudformationStackStatus": "DELETE_IN_PROGRESS",
       "cloudformationStackArn": "arn:aws:cloudformation:region-id:123456789012:stack/ad-cluster/1234567-abcd-0123-def0-abcdef0123456",
       "region": "region-id",
       "version": "3.15.0",
       "clusterStatus": "DELETE_IN_PROGRESS"
     }
   }
   ```

1. 

**檢查要刪除的叢集進度。**

   ```
   $ pcluster describe-cluster --cluster-name "ad-cluster" --region "region-id" --query "clusterStatus"
   "DELETE_IN_PROGRESS"
   ```

   成功刪除叢集後，請繼續下一個步驟。

## 自動化
<a name="tutorials_05_multi-user-ad-step5-automated"></a>

**刪除 Active Directory 資源**

1. 從 https：//[https://console.aws.amazon.com/cloudformation/](https://console.aws.amazon.com/cloudformation/)。

1. 在導覽窗格中，選擇 **Stacks (堆疊)**。

1. 從堆疊清單中，選擇 AD 堆疊 （例如 `pcluster-ad`)。

1. 選擇 **刪除**。

## 手動
<a name="tutorials_05_multi-user-ad-step5-manual"></a>

1. 

**刪除 Amazon EC2 執行個體。**

   1. 在 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/) 的導覽窗格中，選擇**執行個體**。

   1. 從執行個體清單中，選擇您建立以將使用者新增至目錄的執行個體。

   1. 選擇**執行個體狀態**，然後選擇**終止執行個體**。

1. 

**刪除託管區域。**

   1. `recordset-delete.json` 使用下列內容建立 。在此範例中，HostedZoneId 是負載平衡器的正式託管區域 ID。

      ```
      {
        "Changes": [
          {
            "Action": "DELETE",
            "ResourceRecordSet": {
              "Name": "corp.example.com",
              "Type": "A",
              "Region": "region-id",
              "SetIdentifier": "pcluster-active-directory",
              "AliasTarget": {
                "HostedZoneId": "Z2IFOLAFXWLO4F",
                "DNSName": "CorpExampleCom-NLB-3afe296bf4ba80d4.elb.region-id.amazonaws.com",
                "EvaluateTargetHealth": true
              }
            }
          }
        ]
      }
      ```

   1. 使用託管區域 ID 將記錄集變更提交至託管區域。

      ```
      $ aws route53 change-resource-record-sets --hosted-zone-id Z09020002B5MZQNXMSJUB \
        --change-batch file://recordset-delete.json
      {
       "ChangeInfo": {
           "Id": "/change/C04853642A0TH2TJ5NLNI",
           "Status": "PENDING",
           "SubmittedAt": "2022-05-05T14:25:51.046000+00:00"
       }
      }
      ```

   1. 刪除託管區域。

      ```
      $ aws route53 delete-hosted-zone --id Z09020002B5MZQNXMSJUB
      {
       "ChangeInfo": {
           "Id": "/change/C0468051QFABTVHMDEG9",
           "Status": "PENDING",
           "SubmittedAt": "2022-05-05T14:26:13.814000+00:00"
       }
      }
      ```

1. 

**刪除 LB 接聽程式。**

   ```
   $ aws elbv2 delete-listener \
     --listener-arn arn:aws:elasticloadbalancing:region-id:123456789012:listener/net/CorpExampleCom-NLB/3afe296bf4ba80d4/a8f9d97318743d4b --region region-id
   ```

1. 

**刪除目標群組。**

   ```
   $ aws elbv2 delete-target-group \
     --target-group-arn arn:aws:elasticloadbalancing:region-id:123456789012:targetgroup/CorpExampleCom-Targets/44577c583b695e81 --region region-id
   ```

1. 

**刪除負載平衡器。**

   ```
   $ aws elbv2 delete-load-balancer \
     --load-balancer-arn arn:aws:elasticloadbalancing:region-id:123456789012:loadbalancer/net/CorpExampleCom-NLB/3afe296bf4ba80d4 --region region-id
   ```

1. 

**刪除叢集用來從 Secrets Manager 讀取憑證的政策。**

   ```
   $ aws iam delete-policy --policy-arn arn:aws:iam::123456789012:policy/ReadCertExample
   ```

1. 

**刪除包含網域憑證的秘密。**

   ```
   $ aws secretsmanager delete-secret \
     --secret-id arn:aws:secretsmanager:region-id:123456789012:secret:example-cert-123abc \
     --region region-id
   {
    "ARN": "arn:aws:secretsmanager:region-id:123456789012:secret:example-cert-123abc",
    "Name": "example-cert",
    "DeletionDate": "2022-06-04T16:27:36.183000+02:00"
   }
   ```

1. 

**從 ACM 刪除憑證。**

   ```
   $ aws acm delete-certificate \
     --certificate-arn arn:aws:acm:region-id:123456789012:certificate/343db133-490f-4077-b8d4-3da5bfd89e72 --region region-id
   ```

1. 

**刪除 Active Directory (AD) 資源。**

   1. 從 python 指令碼 的輸出取得下列資源 IDs`ad.py`：
      + AD ID
      + AD IDs
      + AD VPC ID

   1. 執行下列命令來刪除目錄。

      ```
      $ aws ds delete-directory --directory-id d-abcdef0123456789 --region region-id
      {
         "DirectoryId": "d-abcdef0123456789"
      }
      ```

   1. 列出 VPC 中的安全群組。

      ```
      $ aws ec2 describe-security-groups --filters '[{"Name":"vpc-id","Values":["vpc-07614ade95ebad1bc"]}]' --region region-id
      ```

   1. 刪除自訂安全群組。

      ```
      $ aws ec2 delete-security-group --group-id sg-021345abcdef6789 --region region-id
      ```

   1. 刪除子網路。

      ```
      $ aws ec2 delete-subnet --subnet-id subnet-1234567890abcdef --region region-id
      ```

      ```
      $ aws ec2 delete-subnet --subnet-id subnet-021345abcdef6789 --region region-id
      ```

   1. 描述網際網路閘道。

      ```
      $ aws ec2 describe-internet-gateways \
        --filters Name=attachment.vpc-id,Values=vpc-021345abcdef6789 \
        --region region-id
      {
        "InternetGateways": [
          {
            "Attachments": [
              {
                "State": "available",
                "VpcId": "vpc-021345abcdef6789"
              }
            ],
            "InternetGatewayId": "igw-1234567890abcdef",
            "OwnerId": "123456789012",
            "Tags": []
          }
        ]  
      }
      ```

   1. 分離網際網路閘道。

      ```
      $ aws ec2 detach-internet-gateway \
        --internet-gateway-id igw-1234567890abcdef \
        --vpc-id vpc-021345abcdef6789 \
        --region region-id
      ```

   1. 刪除網際網路閘道。

      ```
      $ aws ec2 delete-internet-gateway \
        --internet-gateway-id igw-1234567890abcdef \
        --region region-id
      ```

   1. 刪除 VPC。

      ```
      $ aws ec2 delete-vpc \
        --vpc-id vpc-021345abcdef6789 \
        --region region-id
      ```

   1. 刪除包含`ReadOnlyUser`密碼的秘密。

      ```
      $ aws secretsmanager delete-secret \
        --secret-id arn:aws:secretsmanager:region-id:123456789012:secret:ADSecretPassword-1234" \
        --region region-id
      ```

# 使用 AWS KMS 金鑰設定共用儲存加密
<a name="tutorials_04_encrypted_kms_fs-v3"></a>

了解如何設定客戶受管 AWS KMS 金鑰，以加密和保護針對 設定的叢集檔案儲存系統中的資料 AWS ParallelCluster。

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

AWS ParallelCluster 支援下列共用儲存組態選項：
+ [`SharedStorage`](SharedStorage-v3.md) / [`EbsSettings`](SharedStorage-v3.md#SharedStorage-v3-EbsSettings) / [`KmsKeyId`](SharedStorage-v3.md#yaml-SharedStorage-EbsSettings-KmsKeyId)
+ [`SharedStorage`](SharedStorage-v3.md) / [`EfsSettings`](SharedStorage-v3.md#SharedStorage-v3-EfsSettings) / [`KmsKeyId`](SharedStorage-v3.md#yaml-SharedStorage-EfsSettings-KmsKeyId)
+ [`SharedStorage`](SharedStorage-v3.md) / [`FsxLustreSettings`](SharedStorage-v3.md#SharedStorage-v3-FsxLustreSettings) / [`KmsKeyId`](SharedStorage-v3.md#yaml-SharedStorage-FsxLustreSettings-KmsKeyId)

您可以使用這些選項，為 Amazon EBS、Amazon EFS 和 FSx for Lustre 共用儲存系統加密提供客戶受管 AWS KMS 金鑰。若要使用這些政策，您必須為下列項目建立和設定 IAM 政策：
+ [`HeadNode`](HeadNode-v3.md) / [`Iam`](HeadNode-v3.md#HeadNode-v3-Iam) / [`AdditionalIamPolicies`](HeadNode-v3.md#yaml-HeadNode-Iam-AdditionalIamPolicies) / [`Policy`](HeadNode-v3.md#yaml-HeadNode-Iam-AdditionalIamPolicies-Policy)
+ [`Scheduler`](Scheduling-v3.md#yaml-Scheduling-Scheduler) / [`SlurmQueues`](Scheduling-v3.md#Scheduling-v3-SlurmQueues) / [`Iam`](Scheduling-v3.md#Scheduling-v3-SlurmQueues-Iam) / [`AdditionalIamPolicies`](Scheduling-v3.md#yaml-Scheduling-SlurmQueues-Iam-AdditionalIamPolicies) / [`Policy`](Scheduling-v3.md#yaml-Scheduling-SlurmQueues-Iam-AdditionalIamPolicies-Policy) 

**先決條件**
+ AWS ParallelCluster [已安裝 ](install-v3-parallelcluster.md)。
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ 您有 [Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 您有一個 IAM 角色，具有執行 CLI [`pcluster`](pcluster-v3.md) 所需的[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)。

**Topics**
+ [建立政策](creating-the-role-v3.md)
+ [設定和建立叢集](creating-the-cluster-v3.md)

# 建立政策
<a name="creating-the-role-v3"></a>

在本教學課程中，您將建立使用 AWS KMS 金鑰設定共用儲存加密的政策。

**建立政策**

1. 前往 IAM 主控台：https：//[https://console.aws.amazon.com/iam/home](https://console.aws.amazon.com/iam/home)。

1. 選擇**政策**。

1. 選擇**建立政策**。

1. 選擇 **JSON** 索引標籤並貼上下列政策。請務必`123456789012`以您的 AWS 帳戶 ID 和金鑰 Amazon Resource Name (ARN) 取代所有出現的 ，並以您自己的 AWS 區域 取代。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "kms:DescribeKey",
                   "kms:ReEncrypt*",
                   "kms:CreateGrant",
                   "kms:Decrypt"
               ],
               "Resource": [
                   "arn:aws:kms:us-east-1:123456789012:key/abcd1234-ef56-gh78-ij90-abcd1234efgh5678"
               ]
           }
       ]
   }
   ```

------

1. 在本教學課程中，將政策命名為 `ParallelClusterKmsPolicy`，然後選擇**建立政策**。

1. 記下政策 ARN。您需要它來設定叢集。

# 設定和建立叢集
<a name="creating-the-cluster-v3"></a>

以下是範例叢集組態，其中包含具有加密功能的 Amazon Elastic Block Store 共用檔案系統。

```
Region: eu-west-1
Image:
  Os: alinux2
HeadNode:
  InstanceType: t2.micro
  Networking:
    SubnetId: subnet-abcdef01234567890
  Ssh:
    KeyName: my-ssh-key
  Iam:
    AdditionalIamPolicies:
      - Policy: arn:aws:iam::123456789012:policy/ParallelClusterKmsPolicy
Scheduling:
  Scheduler: slurm
  SlurmQueues:
    - Name: q1
      ComputeResources:
        - Name: t2micro
          InstanceType: t2.micro
          MinCount: 0
          MaxCount: 10
      Networking:
        SubnetIds:
          - subnet-abcdef01234567890
      Iam:
        AdditionalIamPolicies:
          - Policy: arn:aws:iam::123456789012:policy/ParallelClusterKmsPolicy
SharedStorage:
  - MountDir: /shared/ebs1
    Name: shared-ebs1
    StorageType: Ebs
    EbsSettings:
      Encrypted: True
      KmsKeyId: abcd1234-ef56-gh78-ij90-abcd1234efgh5678
```

將紅色文字中的項目取代為您自己的值。然後，建立使用 AWS KMS 金鑰在 Amazon EBS 中加密資料的叢集。

Amazon EFS 和 FSx for Lustre 檔案系統的組態類似。

Amazon EFS `SharedStorage`組態如下所示。

```
...
SharedStorage:
  - MountDir: /shared/efs1
    Name: shared-efs1
    StorageType: Efs
    EfsSettings:
      Encrypted: True
      KmsKeyId: abcd1234-ef56-gh78-ij90-abcd1234efgh5678
```

FSx for Lustre `SharedStorage`組態如下所示。

```
...
SharedStorage:
  - MountDir: /shared/fsx1
    Name: shared-fsx1
    StorageType: FsxLustre
    FsxLustreSettings:
      StorageCapacity: 1200
      DeploymentType: PERSISTENT_1
      PerUnitStorageThroughput: 200
      KmsKeyId: abcd1234-ef56-gh78-ij90-abcd1234efgh5678
```

# 在多個佇列模式叢集中執行任務
<a name="multi-queue-tutorial-v3"></a>

本教學課程說明如何 AWS ParallelCluster 在具有[多個佇列模式](configuration-of-multiple-queues-v3.md)的 上執行您的第一個「Hello World」任務。

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**先決條件**
+ AWS ParallelCluster [已安裝 ](install-v3-parallelcluster.md)。
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ 您有 [Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 您有一個 IAM 角色，具有執行 CLI [`pcluster`](pcluster-v3.md) 所需的[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)。

## 設定您的叢集
<a name="multi-queue-tutorial-v3-configure-cluster"></a>

首先，執行下列命令，確認 AWS ParallelCluster 已正確安裝。

```
$ pcluster version
```

如需 `pcluster version` 的相關資訊，請參閱 [`pcluster version`](pcluster.version-v3.md)。

此命令會傳回 的執行版本 AWS ParallelCluster。

接著，執行 `pcluster configure` 以產生基本組態檔案。遵循遵循此命令的所有提示。

```
$ pcluster configure --config multi-queue-mode.yaml
```

如需 `pcluster configure` 命令的詳細資訊，請參閱[`pcluster configure`](pcluster.configure-v3.md)。

完成此步驟後，`multi-queue-mode.yaml`會顯示名為 的基本組態檔案。此檔案包含基本叢集組態。

在下一個步驟中，您會修改新的組態檔案，並啟動具有多個佇列的叢集。

**注意**  
此教學課程使用的某些執行個體不符合免費方案資格。

在本教學課程中，請修改您的組態檔案以符合下列組態。以紅色反白顯示的項目代表您的組態檔案值。保留您自己的值。

```
Region: region-id
Image:
 Os: alinux2
HeadNode:
 InstanceType: c5.xlarge
 Networking:
   SubnetId: subnet-abcdef01234567890
 Ssh:
   KeyName: yourkeypair
Scheduling:
 Scheduler: slurm
 SlurmQueues:
 - Name: spot
   ComputeResources:
   - Name: c5xlarge
     InstanceType: c5.xlarge
     MinCount: 1
     MaxCount: 10
   - Name: t2micro
     InstanceType: t2.micro
     MinCount: 1
     MaxCount: 10
   Networking:
     SubnetIds:
     - subnet-abcdef01234567890
 - Name: ondemand
   ComputeResources:
   - Name: c52xlarge
     InstanceType: c5.2xlarge
     MinCount: 0
     MaxCount: 10
   Networking:
     SubnetIds:
     - subnet-021345abcdef6789
```

## 建立 叢集
<a name="multi-queue-tutorial-v3-create-cluster"></a>

`multi-queue-cluster` 根據您的組態檔案建立名為 的叢集。

```
$ pcluster create-cluster --cluster-name multi-queue-cluster --cluster-configuration multi-queue-mode.yaml
{
 "cluster": {
   "clusterName": "multi-queue-cluster",
   "cloudformationStackStatus": "CREATE_IN_PROGRESS",
   "cloudformationStackArn": "arn:aws:cloudformation:eu-west-1:123456789012:stack/multi-queue-cluster/1234567-abcd-0123-def0-abcdef0123456",
   "region": "eu-west-1",
   "version": "3.15.0",
   "clusterStatus": "CREATE_IN_PROGRESS"
 }
}
```

如需 `pcluster create-cluster` 命令的詳細資訊，請參閱[`pcluster create-cluster`](pcluster.create-cluster-v3.md)。

若要檢查叢集的狀態，請執行下列命令。

```
$ pcluster list-clusters
{
 "cluster": {
   "clusterName": "multi-queue-cluster",
   "cloudformationStackStatus": "CREATE_IN_PROGRESS",
   "cloudformationStackArn": "arn:aws:cloudformation:eu-west-1:123456789012:stack/multi-queue-cluster/1234567-abcd-0123-def0-abcdef0123456",
   "region": "eu-west-1",
   "version": "3.15.0",
   "clusterStatus": "CREATE_IN_PROGRESS"
 }
}
```

建立叢集時， `clusterStatus` 欄位會顯示 `CREATE_COMPLETE`。

## 登入前端節點
<a name="multi-queue-tutorial-v3-log-into-head-node"></a>

使用您的私有 SSH 金鑰檔案登入前端節點。

```
$ pcluster ssh --cluster-name multi-queue-cluster -i ~/path/to/yourkeyfile.pem
```

如需 `pcluster ssh` 的相關資訊，請參閱 [`pcluster ssh`](pcluster.ssh-v3.md)。

登入後，請執行 `sinfo`命令來驗證您的排程器佇列是否已設定。

如需 的詳細資訊`sinfo`，請參閱 *Slurm 文件*中的 [sinfo](https://slurm.schedmd.com/sinfo.html)。

```
$ sinfo
PARTITION AVAIL  TIMELIMIT  NODES  STATE NODELIST
spot*        up   infinite     18  idle~ spot-dy-c5xlarge-[1-9],spot-dy-t2micro-[1-9]
spot*        up   infinite      2  idle  spot-st-c5xlarge-1,spot-st-t2micro-1
ondemand     up   infinite     10  idle~ ondemand-dy-c52xlarge-[1-10]
```

輸出顯示您的叢集中有一個和`t2.micro`一個處於可用`idle`狀態的`c5.xlarge`運算節點。

其他節點都處於省電狀態，以節點狀態的`~`尾碼表示，沒有支援它們的 Amazon EC2 執行個體。預設佇列會以佇列名稱後面的尾碼表示。 `*` `spot`是您的預設任務佇列。

## 在多個佇列模式中執行任務
<a name="multi-queue-tutorial-v3-running-job-mqm"></a>

接下來，嘗試執行任務以睡眠一段時間。任務稍後會輸出自己的主機名稱。請確定目前使用者可執行此指令碼。

```
$ tee <<EOF hellojob.sh
#!/bin/bash
sleep 30
echo "Hello World from \$(hostname)"
EOF

$ chmod +x hellojob.sh
$ ls -l hellojob.sh
-rwxrwxr-x 1 ec2-user ec2-user 57 Sep 23 21:57 hellojob.sh
```

使用 `sbatch`命令提交任務。使用 `-N 2`選項為此任務請求兩個節點，並確認任務已成功提交。如需 的詳細資訊`sbatch`，請參閱 *Slurm 文件*[https://slurm.schedmd.com/sbatch.html](https://slurm.schedmd.com/sbatch.html)中的 。

```
$ sbatch -N 2 --wrap "srun hellojob.sh"
Submitted batch job 1
```

您可以使用 `squeue`命令檢視佇列並檢查任務的狀態。由於您未指定特定佇列，因此會使用預設佇列 (`spot`)。如需 的詳細資訊`squeue`，請參閱 *Slurm 文件*[https://slurm.schedmd.com/squeue.html](https://slurm.schedmd.com/squeue.html)中的 。

```
$ squeue
JOBID PARTITION     NAME     USER  ST      TIME  NODES NODELIST(REASON)
   1      spot     wrap ec2-user  R       0:10      2 spot-st-c5xlarge-1,spot-st-t2micro-1
```

輸出顯示任務目前處於執行中狀態。等待任務完成。這大約需要 30 秒。然後，`squeue`再次執行。

```
$ squeue
JOBID PARTITION     NAME     USER          ST       TIME  NODES NODELIST(REASON)
```

現在佇列中的任務都已完成，請尋找`slurm-1.out`目前目錄中名為 的輸出檔案。

```
$ cat slurm-1.out
Hello World from spot-st-t2micro-1
Hello World from spot-st-c5xlarge-1
```

輸出顯示任務在 `spot-st-t2micro-1`和 `spot-st-c5xlarge-1`節點上成功執行。

現在使用以下命令為特定執行個體指定限制條件，以提交相同的任務。

```
$ sbatch -N 3 -p spot -C "[c5.xlarge*1&t2.micro*2]" --wrap "srun hellojob.sh"
Submitted batch job 2
```

您針對 使用這些參數`sbatch`：
+ `-N 3`– 請求三個節點。
+ `-p spot`– 將任務提交至`spot`佇列。您也可以指定 ，將任務提交至`ondemand`佇列`-p ondemand`。
+ `-C "[c5.xlarge*1&t2.micro*2]"`– 指定此任務的特定節點限制條件。這會請求一個`c5.xlarge`節點和兩個`t2.micro`節點用於此任務。

執行 `sinfo`命令以檢視節點和佇列。中的佇列 AWS ParallelCluster 在 中稱為分割區Slurm。

```
$ sinfo
PARTITION AVAIL  TIMELIMIT  NODES  STATE NODELIST
spot*        up   infinite      1  alloc# spot-dy-t2micro-1
spot*        up   infinite     17  idle~ spot-dy-c5xlarge-[2-10],spot-dy-t2micro-[2-9]
spot*        up   infinite      1  mix   spot-st-c5xlarge-1
spot*        up   infinite      1  alloc spot-st-t2micro-1
ondemand     up   infinite     10  idle~ ondemand-dy-c52xlarge-[1-10]
```

節點正在啟動。這由節點狀態的`#`尾碼表示。執行 squeue命令以檢視叢集中任務的相關資訊。

```
$ squeue
JOBID PARTITION     NAME     USER ST       TIME  NODES NODELIST(REASON)
   2      spot     wrap ec2-user CF       0:04      3 spot-dy-c5xlarge-1,spot-dy-t2micro-1,spot-st-t2micro-1
```

您的任務處於 `CF`(CONFIGURING) 狀態，正在等待執行個體擴展並加入叢集。

大約三分鐘後，節點可用，任務進入 `R`(RUNNING) 狀態。

```
$ squeue
JOBID PARTITION     NAME     USER ST       TIME  NODES NODELIST(REASON)
   2      spot     wrap ec2-user  R       0:07      3 spot-dy-t2micro-1,spot-st-c5xlarge-1,spot-st-t2micro-1
```

任務完成，且所有三個節點都處於 `idle` 狀態。

```
$ squeue
JOBID PARTITION     NAME     USER ST       TIME  NODES NODELIST(REASON)
$ sinfo
PARTITION AVAIL  TIMELIMIT  NODES  STATE NODELIST
spot*        up   infinite     17  idle~ spot-dy-c5xlarge-[1-9],spot-dy-t2micro-[2-9]
spot*        up   infinite      3  idle  spot-dy-t2micro-1,spot-st-c5xlarge-1,spot-st-t2micro-1
ondemand     up   infinite     10  idle~ ondemand-dy-c52xlarge-[1-10]
```

然後，在佇列中沒有任何任務後，請檢查`slurm-2.out`本機目錄中的 。

```
$ cat slurm-2.out 
Hello World from spot-st-t2micro-1
Hello World from spot-dy-t2micro-1
Hello World from spot-st-c5xlarge-1
```

這是叢集的最終狀態。

```
$ sinfo
PARTITION AVAIL  TIMELIMIT  NODES  STATE NODELIST
spot*        up   infinite     17  idle~ spot-dy-c5xlarge-[1-9],spot-dy-t2micro-[2-9]
spot*        up   infinite      3  idle  spot-dy-t2micro-1,spot-st-c5xlarge-1,spot-st-t2micro-1
ondemand     up   infinite     10  idle~ ondemand-dy-c52xlarge-[1-10]
```

登出叢集後，您可以執行 來清除 `pcluster delete-cluster`。如需詳細資訊，請參閱[`pcluster list-clusters`](pcluster.list-clusters-v3.md)及[`pcluster delete-cluster`](pcluster.delete-cluster-v3.md)。

```
$ pcluster list-clusters
{
 "clusters": [
   {
     "clusterName": "multi-queue-cluster",
     "cloudformationStackStatus": "CREATE_COMPLETE",
     "cloudformationStackArn": "arn:aws:cloudformation:eu-west-1:123456789012:stack/multi-queue-cluster/1234567-abcd-0123-def0-abcdef0123456",
     "region": "eu-west-1",
     "version": "3.1.4",
     "clusterStatus": "CREATE_COMPLETE"
   }
 ]
}
$ pcluster delete-cluster -n multi-queue-cluster
{
 "cluster": {
   "clusterName": "multi-queue-cluster",
   "cloudformationStackStatus": "DELETE_IN_PROGRESS",
   "cloudformationStackArn": "arn:aws:cloudformation:eu-west-1:123456789012:stack/multi-queue-cluster/1234567-abcd-0123-def0-abcdef0123456",
   "region": "eu-west-1",
   "version": "3.1.4",
   "clusterStatus": "DELETE_IN_PROGRESS"
 }
}
```

# 使用 AWS ParallelCluster API
<a name="tutorials_06_API_use"></a>

在本教學課程中，您會使用 [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 和 anCloudFormation 範本建置和測試 API。 AWS ParallelCluster CloudFormation 然後，您可以使用 GitHub 上可用的範例用戶端來使用 API。如需如何使用 API 的詳細資訊，請參閱 [AWS ParallelCluster API](api-reference-v3.md)。

如需詳細資訊，請參閱 *EC2 * [ Image Builder 使用者指南中的使用映像建置器建立自訂元件](https://docs.aws.amazon.com/imagebuilder/latest/userguide/create-component.html)。

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**先決條件**
+  AWS CLI 會在您的運算環境中[安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)和設定 。
+ AWS ParallelCluster 安裝在虛擬環境中。如需詳細資訊，請參閱[AWS ParallelCluster 在虛擬環境中安裝 （建議）](install-v3-virtual-environment.md)。
+ 您有 [Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 您有一個 IAM 角色，具有執行 CLI [`pcluster`](pcluster-v3.md) 所需的[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)。



## 步驟 1：使用 Amazon API Gateway 建置 API
<a name="tutorials_06_multi-API-use-step1"></a>

**保留在您的主要使用者目錄中並啟用您的虛擬環境：**

1. 安裝實用的 JSON 命令列處理器。

   ```
   $ sudo yum groupinstall -y "Development Tools"
    sudo yum install -y jq python3-devel
   ```

1. 執行下列命令以取得您的 AWS ParallelCluster 版本，並將其指派給 環境變數。

   ```
   $ PCLUSTER_VERSION=$(pcluster version | jq -r '.version')
    echo "export PCLUSTER_VERSION=${PCLUSTER_VERSION}" |tee -a ~/.bashrc
   ```

1. 建立環境變數，並將您的區域 ID 指派給該變數。

   ```
   $ export AWS_DEFAULT_REGION="us-east-1"
    echo "export AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION}" |tee -a ~/.bashrc
   ```

1. 執行下列命令來部署 API。

   ```
   API_STACK_NAME="pc-api-stack"
    echo "export API_STACK_NAME=${API_STACK_NAME}" |tee -a ~/.bashrc
   ```

   ```
   aws cloudformation create-stack \
      --region ${AWS_DEFAULT_REGION} \
      --stack-name ${API_STACK_NAME} \
      --template-url https://${AWS_DEFAULT_REGION}-aws-parallelcluster.s3.${AWS_DEFAULT_REGION}.amazonaws.com/parallelcluster/${PCLUSTER_VERSION}/api/parallelcluster-api.yaml \
      --capabilities CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND \
      --parameters ParameterKey=EnableIamAdminAccess,ParameterValue=true
        
       {
          "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/my-api-stack/abcd1234-ef56-gh78-ei90-1234abcd5678"
       }
   ```

   程序完成後，請繼續下一個步驟。

## 步驟 2：在 Amazon API Gateway 主控台中測試 API
<a name="tutorials_06_multi-API-use-step2"></a>

1. 登入 AWS 管理主控台。

1. 導覽至 [Amazon API Gateway 主控台](https://console.aws.amazon.com/apigateway/home)。

1. 選擇您的 API 部署。  
![\[Amazon API Gateway 主控台，其中包含您可以選擇的閘道清單。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/gateway_choose.png)

1. 選擇**階段**並選取階段。  
![\[您可以從中選擇的階段的主控台檢視。您也可以檢視 API Gateway 為您的 API 提供的 URL。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/gateway_address.png)

1. 請注意 API Gateway 提供用來存取或叫用 API 的 URL。它以藍色反白顯示。

1. 選擇**資源**，然後選取 **`GET`**下的 **`/clusters`**。

1. 選擇**測試**圖示，然後向下捲動並選擇**測試**圖示。  
![\[API 資源和測試機制的主控台檢視。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/gateway_test.png)

   您的 回應`/clusters GET`隨即出現。  
![\[API 資源、測試機制和測試請求回應的主控台檢視。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/gateway.png)

## 步驟 3：準備並測試範例用戶端以叫用 API
<a name="tutorials_06_multi-API-use-step3"></a>



將 AWS ParallelCluster 原始程式碼複製到 `cd` `api`目錄，然後安裝 Python 用戶端程式庫。

1. 

   ```
   $ git clone -b v${PCLUSTER_VERSION} https://github.com/aws/aws-parallelcluster aws-parallelcluster-v${PCLUSTER_VERSION}
    cd aws-parallelcluster-v${PCLUSTER_VERSION}/api
   ```

   ```
   $ pip3 install client/src
   ```

1. 導覽回您的主要使用者目錄。

1. 匯出用戶端在執行時所使用的 API Gateway 基本 URL。

   ```
   $ export PCLUSTER_API_URL=$( aws cloudformation describe-stacks --stack-name ${API_STACK_NAME} --query 'Stacks[0].Outputs[?OutputKey==`ParallelClusterApiInvokeUrl`].OutputValue' --output text )
    echo "export PCLUSTER_API_URL=${PCLUSTER_API_URL}" |tee -a ~/.bashrc
   ```

1. 匯出用戶端用來建立叢集的叢集名稱。

   ```
   $ export CLUSTER_NAME="test-api-cluster"
    echo "export CLUSTER_NAME=${CLUSTER_NAME}" |tee -a ~/.bashrc
   ```

1. 執行下列命令來存放範例用戶端用來存取 API 的登入資料。

   ```
   $ export PCLUSTER_API_USER_ROLE=$( aws cloudformation describe-stacks --stack-name ${API_STACK_NAME} --query 'Stacks[0].Outputs[?OutputKey==`ParallelClusterApiUserRole`].OutputValue' --output text )
    echo "export PCLUSTER_API_USER_ROLE=${PCLUSTER_API_USER_ROLE}" |tee -a ~/.bashrc
   ```

## 步驟 4：複製用戶端程式碼指令碼並執行叢集測試
<a name="tutorials_06_multi-API-use-step4"></a>

1. 將下列範例用戶端程式碼複製到主使用者目錄中`test_pcluster_client.py`的 。用戶端程式碼會發出執行下列動作的請求：
   + 建立 叢集
   + 描述叢集。
   + 列出叢集。
   + 描述運算機群。
   + 描述叢集執行個體。

   ```
   # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: MIT-0
   #
   # Permission is hereby granted, free of charge, to any person obtaining a copy of this
   # software and associated documentation files (the "Software"), to deal in the Software
   # without restriction, including without limitation the rights to use, copy, modify,
   # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
   # permit persons to whom the Software is furnished to do so.
   #
   # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
   # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
   # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
   # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
   # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
   # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   #
   #  Author: Evan F. Bollig (Github: bollig)
   
   import time, datetime
   import os
   import pcluster_client
   from pprint import pprint
   from pcluster_client.api import (
       cluster_compute_fleet_api,
       cluster_instances_api,
       cluster_operations_api
   )
   from pcluster_client.model.create_cluster_request_content import CreateClusterRequestContent
   from pcluster_client.model.cluster_status import ClusterStatus
   region=os.environ.get("AWS_DEFAULT_REGION")
   
   # Defining the host is optional and defaults to http://localhost
   # See configuration.py for a list of all supported configuration parameters.
   configuration = pcluster_client.Configuration(
       host = os.environ.get("PCLUSTER_API_URL")
   )
   cluster_name=os.environ.get("CLUSTER_NAME")
   
   # Enter a context with an instance of the API client
   with pcluster_client.ApiClient(configuration) as api_client:
       cluster_ops = cluster_operations_api.ClusterOperationsApi(api_client)
       fleet_ops = cluster_compute_fleet_api.ClusterComputeFleetApi(api_client)
       instance_ops = cluster_instances_api.ClusterInstancesApi(api_client)
       
       # Create cluster
       build_done = False
       try:
           with open('cluster-config.yaml', encoding="utf-8") as f:
               body = CreateClusterRequestContent(cluster_name=cluster_name, cluster_configuration=f.read())
               api_response = cluster_ops.create_cluster(body, region=region)
       except pcluster_client.ApiException as e:
           print("Exception when calling create_cluster: %s\n" % e)
           build_done = True
       time.sleep(60)
       
       # Confirm cluster status with describe_cluster
       while not build_done:
           try:
               api_response = cluster_ops.describe_cluster(cluster_name, region=region)
               pprint(api_response)
               if api_response.cluster_status == ClusterStatus('CREATE_IN_PROGRESS'):
                   print('. . . working . . .', end='', flush=True)
                   time.sleep(60)
               elif api_response.cluster_status == ClusterStatus('CREATE_COMPLETE'):
                   print('READY!')
                   build_done = True
               else:
                   print('ERROR!!!!')
                   build_done = True    
           except pcluster_client.ApiException as e:
               print("Exception when calling describe_cluster: %s\n" % e)  
    
       # List clusters
       try:
           api_response = cluster_ops.list_clusters(region=region)
           pprint(api_response)
       except pcluster_client.ApiException as e:
           print("Exception when calling list_clusters: %s\n" % e)
                   
       # DescribeComputeFleet
       try:
           api_response = fleet_ops.describe_compute_fleet(cluster_name, region=region)
           pprint(api_response)
       except pcluster_client.ApiException as e:
           print("Exception when calling compute fleet: %s\n" % e)
   
       # DescribeClusterInstances
       try:
           api_response = instance_ops.describe_cluster_instances(cluster_name, region=region)
           pprint(api_response)
       except pcluster_client.ApiException as e:
           print("Exception when calling describe_cluster_instances: %s\n" % e)
   ```

1. 建立叢集組態。

   ```
   $ pcluster configure --config cluster-config.yaml
   ```

1. API 用戶端程式庫會自動偵測來自您環境變數 （例如 `AWS_ACCESS_KEY_ID`、 `AWS_SECRET_ACCESS_KEY`或 `AWS_SESSION_TOKEN`) 或 的組態詳細資訊`$HOME/.aws`。下列命令會將您目前的 IAM 角色切換為指定的 ParallelClusterApiUserRole。

   ```
   $  eval $(aws sts assume-role --role-arn ${PCLUSTER_API_USER_ROLE} --role-session-name ApiTestSession | jq -r '.Credentials | "export AWS_ACCESS_KEY_ID=\(.AccessKeyId)\nexport AWS_SECRET_ACCESS_KEY=\(.SecretAccessKey)\nexport AWS_SESSION_TOKEN=\(.SessionToken)\n"')
   ```

   **要監看的錯誤：**

   如果您看到類似以下的錯誤，表示您已假設 ParallelClusterApiUserRole且您的 `AWS_SESSION_TOKEN` 已過期。

   ```
   An error occurred (AccessDenied) when calling the AssumeRole operation: 
   User: arn:aws:sts::XXXXXXXXXXXX:assumed-role/ParallelClusterApiUserRole-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/ApiTestSession 
   is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::XXXXXXXXXXXX:role/ParallelClusterApiUserRole-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
   ```

   捨棄角色，然後重新執行 `aws sts assume-role`命令以使用 ParallelClusterApiUserRole。

   ```
   $ unset AWS_SESSION_TOKEN
   unset AWS_SECRET_ACCESS_KEY
   unset AWS_ACCESS_KEY_ID
   ```

   若要為 API 存取提供目前的使用者許可，您必須[展開資源政策](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-resource-policies.html)。

1. 執行下列命令來測試範例用戶端。

   ```
   $ python3 test_pcluster_client.py
   {'cluster_configuration': 'Region: us-east-1\n'
                             'Image:\n'
                             '  Os: alinux2\n'
                             'HeadNode:\n'
                             '  InstanceType: t2.micro\n'
                             '  Networking . . . :\n'
                             '    SubnetId: subnet-1234567890abcdef0\n'
                             '  Ssh:\n'
                             '    KeyName: adpc\n'
                             'Scheduling:\n'
                             '  Scheduler: slurm\n'
                             '  SlurmQueues:\n'
                             '  - Name: queue1\n'
                             '    ComputeResources:\n'
                             '    - Name: t2micro\n'
                             '      InstanceType: t2.micro\n'
                             '      MinCount: 0\n'
                             '      MaxCount: 10\n'
                             '    Networking . . . :\n'
                             '      SubnetIds:\n'
                             '      - subnet-1234567890abcdef0\n',
    'cluster_name': 'test-api-cluster'}
   {'cloud_formation_stack_status': 'CREATE_IN_PROGRESS',
    'cloudformation_stack_arn': 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-api-cluster/abcd1234-ef56-gh78-ij90-1234abcd5678',
    'cluster_configuration': {'url': 'https://parallelcluster-021345abcdef6789-v1-do-not-delete...},
    'cluster_name': 'test-api-cluster',
    'cluster_status': 'CREATE_IN_PROGRESS',
    'compute_fleet_status': 'UNKNOWN',
    'creation_time': datetime.datetime(2022, 4, 28, 16, 18, 47, 972000, tzinfo=tzlocal()),
    'last_updated_time': datetime.datetime(2022, 4, 28, 16, 18, 47, 972000, tzinfo=tzlocal()),
    'region': 'us-east-1',
    'tags': [{'key': 'parallelcluster:version', 'value': '3.1.3'}],
    'version': '3.1.3'}
           .
           . 
           .
   . . . working . . . {'cloud_formation_stack_status': 'CREATE_COMPLETE',
    'cloudformation_stack_arn': 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-api-cluster/abcd1234-ef56-gh78-ij90-1234abcd5678',
    'cluster_configuration': {'url': 'https://parallelcluster-021345abcdef6789-v1-do-not-delete...},
    'cluster_name': 'test-api-cluster',
    'cluster_status': 'CREATE_COMPLETE',
    'compute_fleet_status': 'RUNNING',
    'creation_time': datetime.datetime(2022, 4, 28, 16, 18, 47, 972000, tzinfo=tzlocal()),
    'head_node': {'instance_id': 'i-abcdef01234567890',
                  'instance_type': 't2.micro',
                  'launch_time': datetime.datetime(2022, 4, 28, 16, 21, 46, tzinfo=tzlocal()),
                  'private_ip_address': '172.31.27.153',
                  'public_ip_address': '52.90.156.51',
                  'state': 'running'},
    'last_updated_time': datetime.datetime(2022, 4, 28, 16, 18, 47, 972000, tzinfo=tzlocal()),
    'region': 'us-east-1',
    'tags': [{'key': 'parallelcluster:version', 'value': '3.1.3'}],
    'version': '3.1.3'}
   READY!
   ```

## 步驟 5：複製用戶端程式碼指令碼並刪除叢集
<a name="tutorials_06_multi-API-use-step5"></a>

1. 將下列範例用戶端程式碼複製到 `delete_cluster_client.py`。用戶端程式碼會發出刪除叢集的請求。

   ```
   # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: MIT-0
   #
   # Permission is hereby granted, free of charge, to any person obtaining a copy of this
   # software and associated documentation files (the "Software"), to deal in the Software
   # without restriction, including without limitation the rights to use, copy, modify,
   # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
   # permit persons to whom the Software is furnished to do so.
   #
   # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
   # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
   # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
   # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
   # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
   # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   #
   #  Author: Evan F. Bollig (Github: bollig)
   
   import time, datetime
   import os
   import pcluster_client
   from pprint import pprint
   from pcluster_client.api import (
       cluster_compute_fleet_api,
       cluster_instances_api,
       cluster_operations_api
   )
   from pcluster_client.model.create_cluster_request_content import CreateClusterRequestContent
   from pcluster_client.model.cluster_status import ClusterStatus
   region=os.environ.get("AWS_DEFAULT_REGION")
   
   # Defining the host is optional and defaults to http://localhost
   # See configuration.py for a list of all supported configuration parameters.
   configuration = pcluster_client.Configuration(
       host = os.environ.get("PCLUSTER_API_URL")
   )
   cluster_name=os.environ.get("CLUSTER_NAME")
   
   # Enter a context with an instance of the API client
   with pcluster_client.ApiClient(configuration) as api_client:
       cluster_ops = cluster_operations_api.ClusterOperationsApi(api_client)
       
       # Delete the cluster
       gone = False
       try:
           api_response = cluster_ops.delete_cluster(cluster_name, region=region)
       except pcluster_client.ApiException as e:
           print("Exception when calling delete_cluster: %s\n" % e)
       time.sleep(60)
       
       # Confirm cluster status with describe_cluster
       while not gone:
           try:
               api_response = cluster_ops.describe_cluster(cluster_name, region=region)
               pprint(api_response)
               if api_response.cluster_status == ClusterStatus('DELETE_IN_PROGRESS'):
                   print('. . . working . . .', end='', flush=True)
                   time.sleep(60)    
           except pcluster_client.ApiException as e:
               gone = True
               print("DELETE COMPLETE or Exception when calling describe_cluster: %s\n" % e)
   ```

1. 執行下列命令來刪除叢集。

   ```
   $ python3 delete_cluster_client.py
   {'cloud_formation_stack_status': 'DELETE_IN_PROGRESS',
   'cloudformation_stack_arn': 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-api-cluster/abcd1234-ef56-gh78-ij90-1234abcd5678',
   'cluster_configuration': {'url': 'https://parallelcluster-021345abcdef6789-v1-do-not-delete...},
   'cluster_name': 'test-api-cluster',
   'cluster_status': 'DELETE_IN_PROGRESS',
   'compute_fleet_status': 'UNKNOWN',
   'creation_time': datetime.datetime(2022, 4, 28, 16, 50, 47, 943000, tzinfo=tzlocal()),
   'head_node': {'instance_id': 'i-abcdef01234567890',
                 'instance_type': 't2.micro',
                 'launch_time': datetime.datetime(2022, 4, 28, 16, 53, 48, tzinfo=tzlocal()),
                 'private_ip_address': '172.31.17.132',
                 'public_ip_address': '34.201.100.37',
                 'state': 'running'},
   'last_updated_time': datetime.datetime(2022, 4, 28, 16, 50, 47, 943000, tzinfo=tzlocal()),
   'region': 'us-east-1',
   'tags': [{'key': 'parallelcluster:version', 'value': '3.1.3'}],
   'version': '3.1.3'}
          .
          . 
          .
   . . . working . . . {'cloud_formation_stack_status': 'DELETE_IN_PROGRESS',
   'cloudformation_stack_arn': 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-api-cluster/abcd1234-ef56-gh78-ij90-1234abcd5678',
   'cluster_configuration': {'url': 'https://parallelcluster-021345abcdef6789-v1-do-not-delete...},
   'cluster_name': 'test-api-cluster',
   'cluster_status': 'DELETE_IN_PROGRESS',
   'compute_fleet_status': 'UNKNOWN',
   'creation_time': datetime.datetime(2022, 4, 28, 16, 50, 47, 943000, tzinfo=tzlocal()),
   'last_updated_time': datetime.datetime(2022, 4, 28, 16, 50, 47, 943000, tzinfo=tzlocal()),
   'region': 'us-east-1',
   'tags': [{'key': 'parallelcluster:version', 'value': '3.1.3'}],
   'version': '3.1.3'}
   . . . working . . . DELETE COMPLETE or Exception when calling describe_cluster: (404)
   Reason: Not Found
    	      .
    	      .
    	      .
   HTTP response body: {"message":"Cluster 'test-api-cluster' does not exist or belongs to an incompatible ParallelCluster major version."}
   ```

1. 測試完成後，請取消設定環境變數。

   ```
   $ unset AWS_SESSION_TOKEN
   unset AWS_SECRET_ACCESS_KEY
   unset AWS_ACCESS_KEY_ID
   ```

## 步驟 6：清除
<a name="tutorials_06_multi-API-use-step6"></a>

您可以使用 AWS 管理主控台 或 AWS CLI 來刪除您的 API。

1. 從 CloudFormation 主控台選擇 API 堆疊，然後選擇**刪除**。

1. 如果使用 ，請執行下列命令 AWS CLI。

   使用 CloudFormation。

   ```
   $ aws cloudformation delete-stack --stack-name ${API_STACK_NAME}
   ```

# 使用Slurm會計建立叢集
<a name="tutorials_07_slurm-accounting-v3"></a>

了解如何使用Slurm會計設定和建立叢集。如需詳細資訊，請參閱[Slurm 使用 會計 AWS ParallelCluster](slurm-accounting-v3.md)。

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

在本教學課程中，您會使用 [CloudFormation 快速建立範本 (us-east-1)](https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/create/review?stackName=pcluster-slurm-db&templateURL=https://us-east-1-aws-parallelcluster.s3.amazonaws.com/templates/1-click/serverless-database.yaml) 來建立 [Amazon Aurora](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_AuroraOverview.html) for MySQL 無伺服器資料庫。範本會指示 CloudFormation 建立所有必要元件，以在與叢集相同的 VPC 上部署無 Amazon Aurora 伺服器資料庫。範本也會為叢集與資料庫之間的連線建立基本聯網和安全性組態。

**注意**  
從 3.3.0 版開始， AWS ParallelCluster 支援使用叢集組態參數 [SlurmSettings](Scheduling-v3.md#Scheduling-v3-SlurmSettings) / [Database](Scheduling-v3.md#Scheduling-v3-SlurmSettings-Database) 進行Slurm會計。

**注意**  
快速建立範本做為範例。此範本未涵蓋Slurm會計資料庫伺服器的所有可能使用案例。您有責任建立具有適合您生產工作負載之組態和容量的資料庫伺服器。

**事前準備：**
+ AWS ParallelCluster [已安裝 ](install-v3-parallelcluster.md)。
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ 您有 [Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 您有一個 IAM 角色，具有執行 CLI [`pcluster`](pcluster-v3.md) 所需的[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)。
+ 您在 中部署快速建立範本的區域支援 Amazon Aurora MySQL 無伺服器 v2。如需詳細資訊，請參閱 [Aurora MySQL 的 Aurora Serverless v2](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Concepts.Aurora_Fea_Regions_DB-eng.Feature.ServerlessV2.html#Concepts.Aurora_Fea_Regions_DB-eng.Feature.ServerlessV2.amy)。

## 步驟 1：建立 的 VPC 和子網路 AWS ParallelCluster
<a name="slurm-accounting-vpc-v3"></a>

若要將提供的 CloudFormation 範本用於Slurm會計資料庫，您必須備妥叢集的 VPC。您可以手動或作為[使用 AWS ParallelCluster 命令列界面設定和建立叢集](install-v3-configuring.md)程序的一部分來執行此操作。如果您已使用 AWS ParallelCluster，則可能已準備好部署叢集和資料庫伺服器的 VPC。

## 步驟 2：建立資料庫堆疊
<a name="slurm-accounting-db-stack-v3"></a>

使用 [CloudFormation 快速建立範本 (us-east-1)](https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/create/review?stackName=pcluster-slurm-db&templateURL=https://us-east-1-aws-parallelcluster.s3.amazonaws.com/templates/1-click/serverless-database.yaml) 建立用於Slurm會計的資料庫堆疊。範本需要以下輸入：
+ 資料庫伺服器登入資料，特別是管理員使用者名稱和密碼。
+ 無 Amazon Aurora 伺服器叢集的大小。這取決於預期的叢集載入。
+ 網路參數，特別是用於建立子網路的目標 VPC 和子網路或 CIDR 區塊。

為您的資料庫伺服器選取適當的登入資料和大小。對於聯網選項，您必須使用 AWS ParallelCluster 部署叢集的相同 VPC。您可以建立資料庫的子網路，並將其做為輸入傳遞至範本。或者，為兩個子網路提供兩個取消連接 CIDR 區塊，並讓 CloudFormation 範本為 CIDR 區塊建立兩個子網路。請確定 CIDR 區塊不會與現有的子網路重疊。如果 CIDR 區塊與現有子網路重疊，則無法建立堆疊。

建立資料庫伺服器需要幾分鐘的時間。

## 步驟 3：建立已啟用Slurm會計的叢集
<a name="slurm-accounting-create-cluster-v3"></a>

提供的 CloudFormation 範本會產生具有一些已定義輸出的 CloudFormation 堆疊。從 AWS 管理主控台，您可以在 CloudFormation 堆疊檢視的輸出索引標籤中檢視**輸出**。若要啟用 Slurm會計， AWS ParallelCluster 叢集組態檔案中必須使用其中一些輸出：
+ `DatabaseHost`：用於 [`SlurmSettings`](Scheduling-v3.md#Scheduling-v3-SlurmSettings) / [`Database`](Scheduling-v3.md#Scheduling-v3-SlurmSettings-Database) / [`Uri`](Scheduling-v3.md#yaml-Scheduling-SlurmSettings-Database-Uri)叢集組態參數。
+ `DatabaseAdminUser`：用於 [`SlurmSettings`](Scheduling-v3.md#Scheduling-v3-SlurmSettings) / / [`Database`](Scheduling-v3.md#Scheduling-v3-SlurmSettings-Database) [`UserName`](Scheduling-v3.md#yaml-Scheduling-SlurmSettings-Database-UserName)叢集組態參數值。
+ `DatabaseSecretArn`：用於 [`SlurmSettings`](Scheduling-v3.md#Scheduling-v3-SlurmSettings) / [`Database`](Scheduling-v3.md#Scheduling-v3-SlurmSettings-Database) / [`PasswordSecretArn`](Scheduling-v3.md#yaml-Scheduling-SlurmSettings-Database-PasswordSecretArn)叢集組態參數。
+ `DatabaseClientSecurityGroup`：這是連接到叢集前端節點的安全群組，其定義在 / [`Networking`](HeadNode-v3.md#HeadNode-v3-Networking) / [`HeadNode`](HeadNode-v3.md) [`SecurityGroups`](HeadNode-v3.md#yaml-HeadNode-Networking-SecurityGroups)組態參數中。

使用輸出值更新您的叢集組態檔案`Database`參數。使用 [`pcluster`](pcluster-v3.md) CLI 建立叢集。

```
$ pcluster create-cluster -n cluster-3.x -c path/to/cluster-config.yaml
```

建立叢集之後，您可以開始使用Slurm會計命令，例如 `sacctmgr`或 `sacct`。

# 使用外部Slurmdbd會計建立叢集
<a name="external-slurmdb-accounting"></a>

了解如何設定和建立具有外部Slurmdbd會計的叢集。如需詳細資訊，請參閱[Slurm使用 進行會計 AWS ParallelCluster](slurm-accounting-v3.md)。

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為 AWS 建立或更新 AWS ParallelCluster 映像和叢集時建立的資源付費。如需詳細資訊，請參閱 [AWS 所使用的服務 AWS ParallelCluster](aws-services-v3.md)。

UI AWS ParallelCluster 是以無伺服器架構為基礎，在大多數情況下，您可以在 AWS Free Tier類別中使用它。如需詳細資訊，請參閱 [AWS ParallelCluster UI 成本](install-pcui-costs-v3.md)。

在本教學課程中，您會使用 AWS CloudFormation 快速建立範本來建立必要的元件，以在與叢集相同的 VPC 上部署 Slurmdbd 執行個體。範本會為叢集與資料庫之間的連線建立基本聯網和安全性組態。

**注意**  
從 開始`version 3.10.0`， 使用叢集組態參數 AWS ParallelCluster 支援外部 Slurmdbd`SlurmSettings / ExternelSlurmdbd`。

**注意**  
快速建立範本做為範例。此範本未涵蓋所有可能的使用案例。您有責任使用適合您生產工作負載的組態和容量建立外部 Slurmdbd。

**事前準備：**
+ AWS ParallelCluster [已安裝 ](install-v3-parallelcluster.md)。
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ 您有 [Amazon Elastic Compute Cloud 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 您的 AWS Identity and Access Management 角色具有執行 CLI [`pcluster`](pcluster-v3.md) 所需的[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)。
+ 您有Slurm會計資料庫。若要逐步完成建立Slurm會計資料庫的教學課程，請遵循[建立 Slurm 會計資料庫堆疊](tutorials_07_slurm-accounting-v3.md)中的步驟 1 和 2。

## 步驟 1：建立 Slurmdbd 堆疊
<a name="external-slurmdb-accounting-step1"></a>

在本教學課程中，使用 [CloudFormation 快速建立範本 (`us-east-1`)](https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/create/review?stackName=pcluster-slurm-dbd&templateURL=https://us-east-1-aws-parallelcluster.s3.amazonaws.com/templates/1-click/external-slurmdbd.json) 來建立 Slurmdbd 堆疊。範本需要以下輸入：

**聯網**
+ **VPCId**：啟動 Slurmdbd 執行個體的 VPC ID。
+ **SubnetId**：啟動 Slurmdbd 執行個體的子網路 ID。
+ **PrivatePrefix**：VPC 的 CIDR 字首。
+ **PrivateIp**：指派給 Slurmdbd 執行個體的次要私有 IP。

**資料庫連線**
+ **DBMSClientSG**：要連接到 Slurmdbd 執行個體的安全群組。此安全群組應允許資料庫伺服器與 Slurmdbd 執行個體之間的連線。
+ **DBMSDatabaseName**：資料庫的名稱。
+ **DBMSUsername**：資料庫的使用者名稱。
+ **DBMSPasswordSecretArn**：包含資料庫密碼的秘密。
+ **DBMSUri**：資料庫伺服器的 URI。

**執行個體設定**
+ **InstanceType**：用於 slurmdbd 執行個體的執行個體類型。
+ **KeyName**：用於 slurmdbd 執行個體的 Amazon EC2 金鑰對。

**Slurmdbd 設定**
+ **AMIID**：Slurmdbd 執行個體的 AMI。AMI 應為 ParallelCluster AMI。ParallelCluster AMI 的版本會決定 Slurmdbd 的版本。
+ **MungeKeySecretArn**：包含 munge 金鑰的秘密，用於驗證 Slurmdbd 和叢集之間的通訊。
+ **SlurmdbdPort**：slurmdbd 使用的連接埠號碼。
+ **EnableSlurmdbdSystemService**：啟用 slurmdbd 做為系統服務，並在執行個體啟動時執行。

**警告**  
如果資料庫是由不同版本的 所建立SlurmDB，請勿使用 Slurmdbd做為系統服務。  
如果資料庫包含大量項目， Slurm Database Daemon (SlurmDBD)可能需要數十分鐘才能更新資料庫，而且在此時間間隔內不會回應。  
升級 之前SlurmDB，請先備份資料庫。如需詳細資訊，請參閱 [Slurm 文件](https://slurm.schedmd.com/quickstart_admin.html#upgrade)。

## 步驟 2：建立Slurmdbd已啟用外部的叢集
<a name="external-slurmdb-accounting-step2"></a>

提供的 CloudFormation 範本會產生具有一些已定義輸出的 CloudFormation 堆疊。

從 AWS 管理主控台檢視 CloudFormation 堆疊中的**輸出**索引標籤，以檢閱建立的實體。若要啟用 Slurm會計，必須在 AWS ParallelCluster 組態檔案中使用其中一些輸出：
+ **SlurmdbdPrivateIp**：用於 [SlurmSettings](Scheduling-v3.md#Scheduling-v3-SlurmSettings)/[ExternalSlurmdbd](Scheduling-v3.md#Scheduling-v3-SlurmSettings-ExternalSlurmdbd)/[主機叢集組態](Scheduling-v3.md#yaml-Scheduling-SlurmSettings-ExternalSlurmdbd-Host)參數。
+ **SlurmdbdPort**：用於 [ SlurmSettings](Scheduling-v3.md#Scheduling-v3-SlurmSettings)/[ExternalSlurmdbd](Scheduling-v3.md#Scheduling-v3-SlurmSettings-ExternalSlurmdbd)/[連接埠](Scheduling-v3.md#yaml-Scheduling-SlurmSettings-ExternalSlurmdbd-Port)叢集組態參數值。
+ **AccountingClientSecurityGroup**：這是連接到叢集前端節點的安全群組，其定義在 [HeadNode](HeadNode-v3.md) / [Networking](HeadNode-v3.md#HeadNode-v3-Networking) / [AdditionalSecurityGroups](HeadNode-v3.md#yaml-HeadNode-Networking-AdditionalSecurityGroups) 組態參數中。

此外，從 CloudFormation 堆疊檢視中的**參數**索引標籤：
+ **MungeKeySecretArn**：用於 [SlurmSettings](Scheduling-v3.md#Scheduling-v3-SlurmSettings) / [MungeKeySecretArn](Scheduling-v3.md#yaml-Scheduling-SlurmSettings-MungeKeySecretArn) 叢集組態參數值。

使用輸出值更新您的叢集組態檔案資料庫參數。使用叢集 AWS CLI 來建立叢集。

```
$  pcluster create-cluster -n cluster-3.x-c path/to/cluster-config.yaml
```

建立叢集之後，您可以開始使用Slurm會計命令，例如 `sacctmgr`或 `sacct`。

**警告**  
`ParallelCluster` 與外部 之間的流量SlurmDB不會加密。建議在信任的網路SlurmDB中執行叢集和外部 。





# 還原至先前的 AWS Systems Manager 文件版本
<a name="tutorials_08_ssm-document-version-rev-v3"></a>

了解如何還原至先前的 AWS Systems Manager 文件版本。如需 SSM 文件的詳細資訊，請參閱 [AWS Systems Manager 使用者指南](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html)*AWS 中的 Systems Manager* 文件。

使用 AWS ParallelCluster 命令列界面 (CLI) 或 API 時，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**事前準備：**
+  AWS 帳戶 具有管理 SSM 文件許可的 。
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)

## 還原至先前的 SSM 文件版本
<a name="tutorials_08_ssm-document-version-rev-steps"></a>

1. 在終端機中，執行下列命令以取得您擁有的現有 SSM 文件清單。

   ```
   $ aws ssm list-documents --document-filter "key=Owner,value=Self"
   ```

1. 將 SSM 文件還原至先前的版本。在此範例中，我們會還原至`SessionManagerRunShell`文件的先前版本。您可以使用 SSM `SessionManagerRunShell` 文件來自訂您啟動的每個 SSM shell 工作階段。

   1. `SessionManagerRunShell` 執行下列命令來尋找 的 `DocumentVersion` 參數：

      ```
      $ aws ssm describe-document --name "SSM-SessionManagerRunShell"
      {
          "Document": {
              "Hash": "...",
              "HashType": "Sha256",
              "Name": "SSM-SessionManagerRunShell",
              "Owner": "123456789012",
              "CreatedDate": "2023-02-20T19:04:32.390000+00:00",
              "Status": "Active",
              "DocumentVersion": "1",
              "Parameters": [
                  {
                      "Name": "linuxcmd",
                      "Type": "String",
                      "Description": "The command to run on connection...",
                      "DefaultValue": "if [ -d '/opt/parallelcluster' ]; then source /opt/parallelcluster/cfnconfig; sudo su - $cfn_cluster_user; fi; /bin/bash"
                  }
              ],
              "PlatformTypes": [
                  "Windows",
                  "Linux",
                  "MacOS"
              ],
              "DocumentType": "Session",
              "SchemaVersion": "1.0",
              "LatestVersion": "2",
              "DefaultVersion": "1",
              "DocumentFormat": "JSON",
              "Tags": []
          }
      }
      ```

      最新版本為 `2`。

   1. 執行下列命令以還原至先前的版本：

      ```
      $ aws ssm delete-document --name "SSM-SessionManagerRunShell" --document-version 2
      ```

1. 再次執行 `describe-document`命令，確認文件版本已還原：

   ```
   $ aws ssm describe-document --name "SSM-SessionManagerRunShell"
   {
       "Document": {
           "Hash": "...",
           "HashType": "Sha256",
           "Name": "SSM-SessionManagerRunShell",
           "Owner": "123456789012",
           "CreatedDate": "2023-02-20T19:04:32.390000+00:00",
           "Status": "Active",
           "DocumentVersion": "1",
           "Parameters": [
               {
                   "Name": "linuxcmd",
                   "Type": "String",
                   "Description": "The command to run on connection...",
                   "DefaultValue": "if [ -d '/opt/parallelcluster' ]; then source /opt/parallelcluster/cfnconfig; sudo su - $cfn_cluster_user; fi; /bin/bash"
               }
           ],
           "PlatformTypes": [
               "Windows",
               "Linux",
               "MacOS"
           ],
           "DocumentType": "Session",
           "SchemaVersion": "1.0",
           "LatestVersion": "1",
           "DefaultVersion": "1",
           "DocumentFormat": "JSON",
           "Tags": []
       }
   }
   ```

   最新版本為 `1`。

# 使用 建立叢集 CloudFormation
<a name="tutorials_09_cfn-custom-resource-v3"></a>

了解如何使用 AWS ParallelCluster CloudFormation 自訂資源建立叢集。如需詳細資訊，請參閱[AWS CloudFormation 自訂資源](cloudformation-v3.md)。

使用 時 AWS ParallelCluster，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**事前準備：**
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ [Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 具有執行 CLI 所需[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)的 IAM [`pcluster`](pcluster-v3.md) 角色。

## 使用 CloudFormation 快速建立堆疊建立叢集
<a name="cfn-custom-resource-quick-v3"></a>

在本教學課程中，您會使用快速建立堆疊來部署 CloudFormation 範本，以建立叢集和下列 AWS 資源：
+ 使用 CloudFormation 快速建立堆疊建立的根 CloudFormation 堆疊。
+ 巢狀 CloudFormation 堆疊，其中包含預設政策、預設 VPC 設定和自訂資源提供者。
+ 您可以登入並執行任務的範例 AWS ParallelCluster 叢集堆疊和叢集。

**使用 建立叢集 AWS CloudFormation**

1. 登入 AWS 管理主控台。

1. 開啟 CloudFormation [快速建立連結](https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/create/review?stackName=mycluster&templateURL=https://us-east-1-aws-parallelcluster.s3.amazonaws.com/parallelcluster/3.15.0/templates/1-click/cluster-example.yaml)，以在 CloudFormation 主控台中建立下列資源：
   + 具有公有和私有子網路的 VPC 的巢狀 CloudFormation 堆疊，分別用於執行叢集前端節點和運算節點。
   + 巢狀 CloudFormation 堆疊，具有用於管理叢集的 AWS ParallelCluster 自訂資源。
   + 巢狀 CloudFormation 堆疊，具有管理叢集的預設政策。
   + 巢狀堆疊的根 CloudFormation 堆疊。
   + 具有Slurm排程器和已定義運算節點數量的 AWS ParallelCluster 叢集。  
![\[主控台 CloudFormation 快速建立使用者介面。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/cfn-quick-create.png)

1. 在**快速建立堆疊****參數**區段中，輸入下列參數的值：

   1. 針對 **KeyName**，輸入 Amazon EC2 金鑰對的名稱。

   1. 針對 **AvailabilityZone**，為您的叢集節點選擇 AZ，例如 `us-east-1a`。

1. 勾選方塊以確認頁面底部的每個存取功能。

1. 選擇**建立堆疊**。

1. 等待 CloudFormation 堆疊達到 `CREATE_COMPLETE` 狀態。

## 使用 CloudFormation 命令列界面 (CLI) 建立叢集
<a name="cfn-custom-resource-cli-v3"></a>

在本教學課程中，您會使用 CloudFormation 的 AWS 命令列界面 (CLI) 來部署建立叢集的 CloudFormation 範本。

**建立下列 AWS 資源：**
+ 使用 CloudFormation 快速建立堆疊建立的根 CloudFormation 堆疊。
+ 巢狀 CloudFormation 堆疊，其中包含預設政策、預設 VPC 設定和自訂資源提供者。
+ 您可以登入並執行任務的範例 AWS ParallelCluster 叢集堆疊和叢集。

以您自己的值取代以*紅色反白顯示的輸入*，例如*金鑰對*。

**使用 建立叢集 AWS CloudFormation**

1. 使用下列內容建立名為 `cluster_template.yaml`的 CloudFormation 範本：

   ```
   AWSTemplateFormatVersion: '2010-09-09'
   Description: > AWS ParallelCluster CloudFormation Template
   
   Parameters:
     KeyName:
       Description: KeyPair to login to the head node
       Type: AWS::EC2::KeyPair::KeyName
   
     AvailabilityZone:
       Description: Availability zone where instances will be launched
       Type: AWS::EC2::AvailabilityZone::Name
       Default: us-east-2a
   
   Mappings:
     ParallelCluster:
       Constants:
         Version: 3.15.0
   
   Resources:
     PclusterClusterProvider:
       Type: AWS::CloudFormation::Stack
       Properties:
         TemplateURL: !Sub
           - https://${AWS::Region}-aws-parallelcluster.s3.${AWS::Region}.${AWS::URLSuffix}/parallelcluster/${Version}/templates/custom_resource/cluster.yaml
           - { Version: !FindInMap [ParallelCluster, Constants, Version] }
   
     PclusterVpc:
       Type: AWS::CloudFormation::Stack
       Properties:
         Parameters:
           PublicCIDR: 10.0.0.0/24
           PrivateCIDR: 10.0.16.0/20
           AvailabilityZone: !Ref AvailabilityZone
         TemplateURL: !Sub
           - https://${AWS::Region}-aws-parallelcluster.s3.${AWS::Region}.${AWS::URLSuffix}/parallelcluster/${Version}/templates/networking/public-private-${Version}.cfn.json
           - { Version: !FindInMap [ParallelCluster, Constants, Version ] }
   
     PclusterCluster:
       Type: Custom::PclusterCluster
       Properties:
         ServiceToken: !GetAtt [ PclusterClusterProvider , Outputs.ServiceToken ]
         ClusterName: !Sub 'c-${AWS::StackName}'
         ClusterConfiguration:
           Image:
             Os: alinux2
           HeadNode:
             InstanceType: t2.medium
             Networking:
               SubnetId: !GetAtt [ PclusterVpc , Outputs.PublicSubnetId ]
             Ssh:
               KeyName: !Ref KeyName
           Scheduling:
             Scheduler: slurm
             SlurmQueues:
             - Name: queue0
               ComputeResources:
               - Name: queue0-cr0
                 InstanceType: t2.micro
               Networking:
                 SubnetIds:
                 -  !GetAtt [ PclusterVpc , Outputs.PrivateSubnetId ]
   Outputs:
     HeadNodeIp:
       Description: The Public IP address of the HeadNode
       Value: !GetAtt [ PclusterCluster, headNode.publicIpAddress ]
   ```

1. 執行下列 AWS CLI 命令來部署 CloudFormation 堆疊以進行叢集建立和管理。

   ```
   $ aws cloudformation deploy --template-file ./cluster_template.yaml \
     --stack-name mycluster \
     --parameter-overrides KeyName=keypair \
                           AvailabilityZone=us-east-2b \
     --capabilities CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND
   ```

## 檢視 CloudFormation 叢集輸出
<a name="cfn-custom-resource-view-v3"></a>

檢視 CloudFormation 叢集輸出，以取得有用的叢集詳細資訊。新增的 `ValidationMessages` 屬性可讓您從叢集建立和更新操作存取驗證訊息。

1. 導覽至 [CloudFormation 主控台](https://console.aws.amazon.com/cloudformation/home)，然後選取包含 AWS ParallelCluster 自訂資源的堆疊。

1. 選擇**堆疊詳細資訊**，然後選取**輸出**索引標籤。  
![\[主控台 CloudFormation 輸出資料表顯示 HeadNodeIp 和 ValidationMessages 的值。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/cfn-outputs.png)

   驗證訊息可能會被截斷。如需如何擷取日誌的詳細資訊，請參閱 [AWS ParallelCluster 故障診斷](troubleshooting-v3.md)。

## 存取您的叢集
<a name="cfn-custom-resource-access-v3"></a>

存取叢集。

**`ssh` 到叢集前端節點**

1. CloudFormation 堆疊部署完成後，請使用下列命令取得前端節點的 IP 地址：

   ```
   $ HEAD_NODE_IP=$(aws cloudformation describe-stacks --stack-name=mycluster --query "Stacks|[0].Outputs[?OutputKey=='HeadNodeIp']|[0].OutputValue" --output=text)
   ```

   您也可以從 CloudFormation 主控台叢集堆疊**輸出**索引標籤中的 **HeadNodeIp** 參數擷取前端節點 IP 地址。

   您可以在此處找到前端節點 IP 地址，因為它已新增至叢集 CloudFormation 範本的 `Outputs`區段，特別是此範例叢集。

1. 執行下列命令以連接至叢集前端節點：

   ```
   $ ssh -i keyname.pem ec2-user@$HEAD_NODE_IP
   ```

## 清除
<a name="cfn-custom-resource-cleanup-v3"></a>

刪除叢集。

1. 執行下列 AWS CLI 命令來刪除 CloudFormation 堆疊和叢集。

   ```
   $ aws cloudformation delete-stack --stack-name=mycluster
   ```

1. 執行下列命令來檢查堆疊刪除狀態。

   ```
   $ aws cloudformation describe-stacks --stack-name=mycluster
   ```

# 使用 Terraform 部署 ParallelCluster API
<a name="tutorial-deploy-terraform"></a>

在本教學課程中，您將定義簡單的 Terraform 專案來部署 ParallelCluster API。

**先決條件**
+ 已安裝 Terraform v1.5.7\$1。
+ 具有部署 ParallelCluster API 許可的 IAM 角色。請參閱 [所需的許可](tutorial-deploy-terraform-permissions.md)。

# 定義 Terraform 專案
<a name="tutorial-deploy-terraform-define"></a>

在本教學課程中，您將定義 Terraform 專案。

1. 建立名為 的目錄`my-pcluster-api`。

   您建立的所有檔案都將在此目錄中。

1. 建立 檔案`provider.tf`以設定 AWS 提供者。

   ```
   provider "aws" {
     region  = var.region
     profile = var.profile
   }
   ```

1. 建立 檔案`main.tf`以使用 ParallelCluster 模組定義資源。

   ```
   module "parallelcluster_pcluster_api" {
     source = "aws-tf/parallelcluster/aws//modules/pcluster_api"
     version = "1.1.0"
   
     region                = var.region
     api_stack_name        = var.api_stack_name
     api_version           = var.api_version
   
     parameters = {
       EnableIamAdminAccess = "true"
     }
   }
   ```

1. 建立 檔案`variables.tf`以定義可為此專案注入的變數。

   ```
   variable "region" {
     description = "The region the ParallelCluster API is deployed in."
     type        = string
     default     = "us-east-1"
   }
   
   variable "profile" {
     type        = string
     description = "The AWS profile used to deploy the clusters."
     default     = null
   }
   
   variable "api_stack_name" {
     type        = string
     description = "The name of the CloudFormation stack used to deploy the ParallelCluster API."
     default     = "ParallelCluster"
   }
   
   variable "api_version" {
     type        = string
     description = "The version of the ParallelCluster API."
   }
   ```

1. 建立 檔案`terraform.tfvars`以設定變數的任意值。

   以下 檔案`us-east-1`會使用堆疊名稱 在 中部署 ParallelCluster API 3.11.1`MyParallelClusterAPI-3111`。您將可以使用其堆疊名稱來參考此 ParallelCluster API 部署。
**注意**  
下列程式碼中的`api_version`指派可以取代為任何支援的 AWS ParallelCluster 版本。

   ```
   region = "us-east-1"
   api_stack_name = "MyParallelClusterAPI-3111"
   api_version = "3.11.1"
   ```

1. 建立 檔案`outputs.tf`以定義此專案傳回的輸出。

   ```
   output "pcluster_api_stack_outputs" {
     value = module.parallelcluster_pcluster_api.stack_outputs
   }
   ```

   專案目錄為：

   ```
   my-pcluster-api
   ├── main.tf - Terraform entrypoint to define the resources using the ParallelCluster module.
   ├── outputs.tf - Defines the outputs returned by Terraform.
   ├── providers.tf - Configures the AWS provider.
   ├── terraform.tfvars - Set the arbitrary values for the variables, i.e. region, PCAPI version, PCAPI stack name
   └── variables.tf - Defines the variables, e.g. region, PCAPI version, PCAPI stack name.
   ```

# 部署 API
<a name="tutorial-deploy-terraform-deploy-api"></a>

若要部署 API，請依序執行標準 Terraform 命令。

1. 建置專案：

   ```
   terraform init
   ```

1. 定義部署計畫：

   ```
   terraform plan -out tfplan
   ```

1. 部署計劃：

   ```
   terraform apply tfplan
   ```

# 所需的許可
<a name="tutorial-deploy-terraform-permissions"></a>

您需要下列許可，才能使用 Terraform 部署 ParallelCluster API：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "cloudformation:DescribeStacks",
                "cloudformation:GetTemplate"
            ],
            "Resource": "arn:aws:cloudformation:us-east-1:111122223333:stack/*",
            "Effect": "Allow",
            "Sid": "CloudFormationRead"
        },
        {
            "Action": [
                "cloudformation:CreateStack",
                "cloudformation:DeleteStack",
                "cloudformation:CreateChangeSet"
            ],
            "Resource": "arn:aws:cloudformation:us-east-1:111122223333:stack/MyParallelClusterAPI*",
            "Effect": "Allow",
            "Sid": "CloudFormationWrite"
        },
        {
            "Action": [
                "cloudformation:CreateChangeSet"
            ],
            "Resource": [
                "arn:aws:cloudformation:us-east-1:111122223333:aws:transform/Include",
                "arn:aws:cloudformation:us-east-1:111122223333:aws:transform/Serverless-2016-10-31"
            ],
            "Effect": "Allow",
            "Sid": "CloudFormationTransformWrite"
        },
        {
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:us-east-1:111122223333:*-aws-parallelcluster/parallelcluster/*/api/ParallelCluster.openapi.yaml",
                "arn:aws:s3:us-east-1:111122223333:*-aws-parallelcluster/parallelcluster/*/layers/aws-parallelcluster/lambda-layer.zip"
            ],
            "Effect": "Allow",
            "Sid": "S3ParallelClusterArtifacts"
        },
        {
            "Action": [
                "iam:CreateRole",
                "iam:DeleteRole",
                "iam:GetRole",
                "iam:CreatePolicy",
                "iam:DeletePolicy",
                "iam:GetPolicy",
                "iam:GetRolePolicy",
                "iam:AttachRolePolicy",
                "iam:DetachRolePolicy",
                "iam:PutRolePolicy",
                "iam:DeleteRolePolicy",
                "iam:ListPolicyVersions"
            ],
            "Resource": [
                "arn:aws:iam::111122223333:role/*",
                "arn:aws:iam::111122223333:policy/*"
            ],
            "Effect": "Allow",
            "Sid": "IAM"
        },
        {
            "Action": [
                "iam:PassRole"
            ],
            "Resource": [
                "arn:aws:iam::111122223333:role/ParallelClusterLambdaRole-*",
                "arn:aws:iam::111122223333:role/APIGatewayExecutionRole-*"
            ],
            "Effect": "Allow",
            "Sid": "IAMPassRole"
        },
        {
            "Action": [
                "lambda:CreateFunction",
                "lambda:DeleteFunction",
                "lambda:GetFunction",
                "lambda:PublishLayerVersion",
                "lambda:DeleteLayerVersion",
                "lambda:GetLayerVersion",
                "lambda:TagResource",
                "lambda:UntagResource"
            ],
            "Resource": [
                "arn:aws:lambda:us-east-1:111122223333:layer:PCLayer-*",
                "arn:aws:lambda:us-east-1:111122223333:function:*-ParallelClusterFunction-*"
            ],
            "Effect": "Allow",
            "Sid": "Lambda"
        },
        {
            "Action": [
                "logs:CreateLogGroup",
                "logs:DeleteLogGroup",
                "logs:DescribeLogGroups",
                "logs:PutRetentionPolicy",
                "logs:TagLogGroup",
                "logs:UntagLogGroup"
            ],
            "Resource": [
                "arn:aws:logs:us-east-1:111122223333:log-group:/aws/lambda/*-ParallelClusterFunction-*"
            ],
            "Effect": "Allow",
            "Sid": "Logs"
        },
        {
            "Action": [
                "apigateway:DELETE",
                "apigateway:GET",
                "apigateway:PATCH",
                "apigateway:POST",
                "apigateway:PUT",
                "apigateway:UpdateRestApiPolicy"
            ],
            "Resource": [
                "arn:aws:apigateway:us-east-1::/restapis",
                "arn:aws:apigateway:us-east-1::/restapis/*",
                "arn:aws:apigateway:us-east-1::/tags/*"
            ],
            "Effect": "Allow",
            "Sid": "APIGateway"
        }
    ]
}
```

------

# 使用 Terraform 建立叢集
<a name="tutorial-create-cluster-terraform"></a>

使用 時 AWS ParallelCluster，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**先決條件**
+ 已安裝 Terraform v1.5.7\$1。
+ [AWS ParallelCluster API](api-reference-v3.md) v3.8.0\$1 已部署在您的 帳戶中。請參閱 [使用 Terraform 部署 ParallelCluster API](tutorial-deploy-terraform.md)。
+ 具有叫用 ParallelCluster API 許可的 IAM 角色。請參閱 【必要許可】

# 定義 Terraform 專案
<a name="tutorial-create-cluster-terraform-define"></a>

在本教學課程中，您將定義簡單的 Terraform 專案來部署叢集。

1. 建立名為 的目錄`my-clusters`。

   您建立的所有檔案都將在此目錄中。

1. 建立 檔案`terraform.tf`以匯入 ParallelCluster 供應商。

   ```
   terraform {
     required_version = ">= 1.5.7"
     required_providers {
       aws-parallelcluster = {
         source  = "aws-tf/aws-parallelcluster"
         version = "~> 1.0"
       }
     }
   }
   ```

1. 建立 檔案`providers.tf`以設定 ParallelCluster 和 AWS 提供者。

   ```
   provider "aws" {
     region  = var.region
     profile = var.profile
   }
   
   provider "aws-parallelcluster" {
     region         = var.region
     profile        = var.profile
     api_stack_name = var.api_stack_name
     use_user_role  = true
   }
   ```

1. 建立 檔案`main.tf`以使用 ParallelCluster 模組定義資源。

   ```
   module "pcluster" {
     source  = "aws-tf/parallelcluster/aws"
     version = "1.1.0"
   
     region                = var.region
     api_stack_name        = var.api_stack_name
     api_version           = var.api_version
     deploy_pcluster_api   = false
   
     template_vars         = local.config_vars
     cluster_configs       = local.cluster_configs
     config_path           = "config/clusters.yaml"
   }
   ```

1. 建立 檔案`clusters.tf`，將多個叢集定義為 Terraform 本機變數。
**注意**  
您可以在 `cluster_config`元素中定義多個叢集。對於每個叢集，您可以明確定義本機變數內的叢集屬性 （請參閱 `DemoCluster01`) 或參考外部檔案 （請參閱 `DemoCluster02`)。

   若要檢閱您可以在組態元素中設定的叢集屬性，請參閱 [叢集組態檔案](cluster-configuration-file-v3.md)。

   若要檢閱您可以為建立叢集設定的選項，請參閱 [`pcluster create-cluster`](pcluster.create-cluster-v3.md)。

   ```
   locals {
     cluster_configs = {
       DemoCluster01 : {
         region : local.config_vars.region
         rollbackOnFailure : false
         validationFailureLevel : "WARNING"
         suppressValidators : [
           "type:KeyPairValidator"
         ]
         configuration : {
           Region : local.config_vars.region
           Image : {
             Os : "alinux2"
           }
           HeadNode : {
             InstanceType : "t3.small"
             Networking : {
               SubnetId : local.config_vars.subnet
             }
             Iam : {
               AdditionalIamPolicies : [
                 { Policy : "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" }
               ]
             }
           }
           Scheduling : {
             Scheduler : "slurm"
             SlurmQueues : [{
               Name : "queue1"
               CapacityType : "ONDEMAND"
               Networking : {
                 SubnetIds : [local.config_vars.subnet]
               }
               Iam : {
                 AdditionalIamPolicies : [
                   { Policy : "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" }
                 ]
               }
               ComputeResources : [{
                 Name : "compute"
                 InstanceType : "t3.small"
                 MinCount : "1"
                 MaxCount : "4"
               }]
             }]
             SlurmSettings : {
               QueueUpdateStrategy : "TERMINATE"
             }
           }
         }
       }
       DemoCluster02 : {
         configuration : "config/cluster_config.yaml"
       }
     }
   }
   ```

1. 建立 檔案`config/clusters.yaml`，將多個叢集定義為 YAML 組態。

   ```
   DemoCluster03:
     region: ${region}
     rollbackOnFailure: true
     validationFailureLevel: WARNING
     suppressValidators:
       - type:KeyPairValidator
     configuration: config/cluster_config.yaml
   DemoCluster04:
     region: ${region}
     rollbackOnFailure: false
     configuration: config/cluster_config.yaml
   ```

1. 建立 檔案 `config/cluster_config.yaml`，這是可插入 Terraform 變數的標準 ParallelCluster 組態檔案。

   若要檢閱您可以在組態元素中設定的叢集屬性，請參閱 [叢集組態檔案](cluster-configuration-file-v3.md)。

   ```
   Region: ${region}
   Image:
    Os: alinux2
   HeadNode:
    InstanceType: t3.small
    Networking:
      SubnetId: ${subnet}
    Iam:
      AdditionalIamPolicies:
        - Policy: arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
   Scheduling:
    Scheduler: slurm
    SlurmQueues:
      - Name: queue1
        CapacityType: ONDEMAND
        Networking:
          SubnetIds:
            - ${subnet}
        Iam:
          AdditionalIamPolicies:
            - Policy: arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
        ComputeResources:
          - Name: compute
            InstanceType: t3.small
            MinCount: 1
            MaxCount: 5
    SlurmSettings:
      QueueUpdateStrategy: TERMINATE
   ```

1. 建立 檔案`clusters_vars.tf`以定義可注入叢集組態的變數。

   此檔案可讓您定義可在叢集組態中使用的動態值，例如區域和子網路。

   此範例會直接從專案變數擷取值，但您可能需要使用自訂邏輯來判斷它們。

   ```
   locals {
     config_vars = {
       subnet = var.subnet_id
       region = var.cluster_region
     }
   }
   ```

1. 建立 檔案`variables.tf`以定義可為此專案注入的變數。

   ```
   variable "region" {
     description = "The region the ParallelCluster API is deployed in."
     type        = string
     default     = "us-east-1"
   }
   
   variable "cluster_region" {
     description = "The region the clusters will be deployed in."
     type        = string
     default     = "us-east-1"
   }
   
   variable "profile" {
     type        = string
     description = "The AWS profile used to deploy the clusters."
     default     = null
   }
   
   variable "subnet_id" {
     type        = string
     description = "The id of the subnet to be used for the ParallelCluster instances."
   }
   
   variable "api_stack_name" {
     type        = string
     description = "The name of the CloudFormation stack used to deploy the ParallelCluster API."
     default     = "ParallelCluster"
   }
   
   variable "api_version" {
     type        = string
     description = "The version of the ParallelCluster API."
   }
   ```

1. 建立 檔案`terraform.tfvars`以設定變數的任意值。

   以下檔案`subnet-123456789`使用已部署在`us-east-1`堆疊名稱為 的現有 ParallelCluster API 3.11.1，在`eu-west-1`子網路 中部署叢集。 `MyParallelClusterAPI-3111`

   ```
   region = "us-east-1"
   api_stack_name = "MyParallelClusterAPI-3111"
   api_version = "3.11.1"
   
   cluster_region = "eu-west-1"
   subnet_id = "subnet-123456789"
   ```

1. 建立 檔案`outputs.tf`以定義此專案傳回的輸出。

   ```
   output "clusters" {
     value = module.pcluster.clusters
   }
   ```

   專案目錄為：

   ```
   my-clusters
   ├── config
   │   ├── cluster_config.yaml - Cluster configuration, where terraform variables can be injected..
   │   └── clusters.yaml - File listing all the clusters to deploy.
   ├── clusters.tf - Clusters defined as Terraform local variables.
   ├── clusters_vars.tf - Variables that can be injected into cluster configurations.
   ├── main.tf - Terraform entrypoint where the ParallelCluster module is configured.
   ├── outputs.tf - Defines the cluster as a Terraform output.
   ├── providers.tf - Configures the providers: ParallelCluster and AWS.
   ├── terraform.tf - Import the ParallelCluster provider.
   ├── terraform.tfvars - Defines values for variables, e.g. region, PCAPI stack name.
   └── variables.tf - Defines the variables, e.g. region, PCAPI stack name.
   ```

# 部署叢集
<a name="tutorial-create-cluster-terraform-deploy"></a>

若要部署叢集，請依序執行標準 Terraform 命令。

**注意**  
此範例假設您已在帳戶中部署 ParallelCluster API。

1. 建置專案：

   ```
   terraform init
   ```

1. 定義部署計畫：

   ```
   terraform plan -out tfplan
   ```

1. 部署計劃：

   ```
   terraform apply tfplan
   ```

## 使用叢集部署 ParallelCluster API
<a name="tutorial-create-cluster-terraform-deploy-api"></a>

如果您尚未部署 ParallelCluster API，而且想要使用叢集部署它，請變更下列檔案：
+ `main.tf`

  ```
  module "pcluster" {
    source  = "aws-tf/aws/parallelcluster"
    version = "1.0.0"
  
    region                = var.region
    api_stack_name        = var.api_stack_name
    api_version           = var.api_version
    deploy_pcluster_api   = true
    parameters = {
      EnableIamAdminAccess = "true"
    }
    
    template_vars         = local.config_vars
    cluster_configs       = local.cluster_configs
    config_path           = "config/clusters.yaml"
  }
  ```
+ `providers.tf`

  ```
  provider "aws-parallelcluster" {
    region   = var.region
    profile  = var.profile
    endpoint = module.pcluster.pcluster_api_stack_outputs.ParallelClusterApiInvokeUrl
    role_arn = module.pcluster.pcluster_api_stack_outputs.ParallelClusterApiUserRole
  }
  ```

# 所需的許可
<a name="tutorial-create-cluster-terraform-permissions"></a>

您需要下列許可，才能使用 Terraform 部署叢集：
+ 擔任 ParallelCluster API 角色，負責與 ParallelCluster API 互動
+ 描述 ParallelCluster API 的 CloudFormation 堆疊，以驗證其存在並擷取其參數和輸出

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:sts::111122223333:role/PCAPIUserRole-*",
            "Effect": "Allow",
            "Sid": "AssumePCAPIUserRole"
        },
        {
            "Action": [
                "cloudformation:DescribeStacks"
            ],
            "Resource": "arn:aws:cloudformation:us-east-1:111122223333:stack/*",
            "Effect": "Allow",
            "Sid": "CloudFormation"
        }
    ]
}
```

------

# 使用 Terraform 建立自訂 AMI
<a name="tutorial-create-ami-terraform"></a>

使用 時 AWS ParallelCluster，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**先決條件**
+  已安裝 Terraform v1.5.7\$1。
+ [AWS ParallelCluster API](api-reference-v3.md) v3.8.0\$1 已部署在您的 帳戶中。請參閱 [使用 Terraform 建立叢集](tutorial-create-cluster-terraform.md)。
+ 具有叫用 ParallelCluster API 許可的 IAM 角色。請參閱 [所需的許可](tutorial-create-ami-terraform-permissions.md)。

# 定義 Terraform 專案
<a name="tutorial-create-ami-terraform-define"></a>

在本教學課程中，您將定義簡單的 Terraform 專案來部署 ParallelCluster 自訂 AMI。

1. 建立名為 的目錄`my-amis`。

   您建立的所有檔案都將在此目錄中。

1. 建立 檔案`terraform.tf`以匯入 ParallelCluster 供應商。

   ```
   terraform {
     required_version = ">= 1.5.7"
     required_providers {
       aws-parallelcluster = {
         source  = "aws-tf/aws-parallelcluster"
         version = "~> 1.0"
       }
     }
   }
   ```

1. 建立 檔案`providers.tf`以設定 ParallelCluster 和 AWS 提供者。

   ```
   provider "aws" {
     region  = var.region
     profile = var.profile
   }
   
   provider "aws-parallelcluster" {
     region         = var.region
     profile        = var.profile
     api_stack_name = var.api_stack_name
     use_user_role  = true
   }
   ```

1. 建立 檔案`main.tf`以使用 ParallelCluster 模組定義資源。

   若要檢閱您可以在 `image_configuration`元素中設定的映像屬性，請參閱 [建置映像組態檔案](image-builder-configuration-file-v3.md)。

   若要檢閱您可以為影像建立設定的選項，例如 `image_id`和 `rollback_on_failure`，請參閱 [`pcluster build-image`](pcluster.build-image-v3.md)。

   ```
   data "aws-parallelcluster_list_official_images" "parent_image" {
     region = var.region
     os = var.os
     architecture = var.architecture
   }
   
   resource "aws-parallelcluster_image" "demo01" {
     image_id            = "demo01"
     image_configuration = yamlencode({
       "Build":{
         "InstanceType": "c5.2xlarge",
         "ParentImage": data.aws-parallelcluster_list_official_images.parent_image.official_images[0].amiId,
         "UpdateOsPackages": {"Enabled": false}
       }
     })
     rollback_on_failure = false
   }
   ```

1. 建立 檔案`variables.tf`以定義可為此專案注入的變數。

   ```
   variable "region" {
     description = "The region the ParallelCluster API is deployed in."
     type        = string
     default     = "us-east-1"
   }
   
   variable "profile" {
     type        = string
     description = "The AWS profile used to deploy the clusters."
     default     = null
   }
   
   variable "api_stack_name" {
     type        = string
     description = "The name of the CloudFormation stack used to deploy the ParallelCluster API."
     default     = "ParallelCluster"
   }
   
   variable "api_version" {
     type        = string
     description = "The version of the ParallelCluster API."
   }
   
   variable "os" {
     type        = string
     description = "The OS of the ParallelCluster image."
   }
   
   variable "architecture" {
     type        = string
     description = "The architecture of the ParallelCluster image."
   }
   ```

1. 建立 檔案`terraform.tfvars`以設定變數的任意值。

   使用下列檔案，使用已部署在`us-east-1`堆疊名稱為 的現有 ParallelCluster API 3.11.1，`us-east-1`以適用於 x86\$164 架構的 Amazon Linux 2 在 中部署自訂 AMI。 `MyParallelClusterAPI-3111`

   ```
   region = "us-east-1"
   api_stack_name = "MyParallelClusterAPI-3111"
   api_version = "3.11.1"
   
   os = "alinux2"
   architecture = "x86_64"
   ```

1. 建立 檔案`outputs.tf`以定義此專案傳回的輸出。

   ```
   output "parent_image" {
     value = data.aws-parallelcluster_list_official_images.parent_image.official_images[0]
   }
   
   output "custom_image" {
     value = aws-parallelcluster_image.demo01
   }
   ```

   專案目錄為：

   ```
   my-amis
   ├── main.tf - Terraform entrypoint where the ParallelCluster module is configured.
   ├── outputs.tf - Defines the cluster as a Terraform output.
   ├── providers.tf - Configures the providers: ParallelCluster and AWS.
   ├── terraform.tf - Import the ParallelCluster provider.
   ├── terraform.tfvars - Defines values for variables, e.g. region, PCAPI stack name.
   └── variables.tf - Defines the variables, e.g. region, PCAPI stack name.
   ```

# 部署 AMI
<a name="tutorial-create-ami-terraform-deploy"></a>

若要部署 AMI，請依序執行標準 Terraform 命令。

1. 建置專案：

   ```
   terraform init
   ```

1. 定義部署計畫：

   ```
   terraform plan -out tfplan
   ```

1. 部署計劃：

   ```
   terraform apply tfplan
   ```

# 所需的許可
<a name="tutorial-create-ami-terraform-permissions"></a>

您需要下列許可，才能使用 Terraform 部署自訂 AMI：
+ 擔任 ParallelCluster API 角色，負責與 ParallelCluster API 互動
+ 描述 ParallelCluster API 的 CloudFormation 堆疊，以驗證其是否存在並擷取其參數和輸出

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:sts::111122223333:role/PCAPIUserRole-*",
            "Effect": "Allow",
            "Sid": "AssumePCAPIUserRole"
        },
        {
            "Action": [
                "cloudformation:DescribeStacks"
            ],
            "Resource": "arn:aws:cloudformation:us-east-1:111122223333:stack/*",
            "Effect": "Allow",
            "Sid": "CloudFormation"
        }
    ]
}
```

------

# AWS ParallelCluster UI 與 Identity Center 整合
<a name="tutorials_10_pcui-aws-ic-integration-v3"></a>

本教學課程的目標是示範如何針對單一登入解決方案整合 AWS ParallelCluster UI 與 IAM Identity Center，以統一 Active Directory 中可與 AWS ParallelCluster 叢集共用的使用者。

使用 時 AWS ParallelCluster，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**事前準備：**
+ 可依照此處的指示安裝的現有 AWS ParallelCluster UI。 [安裝 PCUI](install-pcui-v3.md)
+ 現有的 受管 Active Directory，最好也用於[整合 AWS ParallelCluster](tutorials_05_multi-user-ad.md)。

## 啟用 IAM Identity Center
<a name="enable-iam-identity-center-v3"></a>

如果您已將身分中心連接到您的 AWS Managed Microsoft AD (Active Directory)，則可以使用它，也可以跳到將**應用程式新增至 IAM Identity Center** 一節。

如果您還沒有連接到 的身分中心 AWS Managed Microsoft AD，請依照下列步驟進行設定。

**啟用身分中心**

1. 在 主控台中，導覽至 IAM Identity Center。（請確定您位於您擁有 的區域 AWS Managed Microsoft AD。)

1. 按一下**啟用**按鈕，這可能會詢問您是否要啟用組織，這是必要項目，因此您可以選取 來啟用它。**注意**：這將傳送電子郵件給您帳戶的管理員，其中包含您應遵循連結確認的確認電子郵件。

**將 Identity Center 連線至 Managed AD**

1. 在啟用身分中心後的下一頁，您應該會看到建議的設定步驟，在步驟 1 下，選取**選擇您的身分來源**。

1. 在身分來源區段中，按一下**動作**下拉式選單 （右上角），然後選取**變更身分來源**。

1. 選取 **Active Directory**。

1. 在**現有目錄**下，選擇您的目錄。

1. 按一下 Next (下一步)。

1. 檢閱您的變更，捲動至底部，在文字方塊中輸入 ACCEPT 進行確認，然後按一下**變更身分來源**。

1. 等待變更完成，然後您應該會在頂端看到綠色橫幅。

**將使用者和群組同步至 Identity Center**

1. 在綠色橫幅中，按一下**開始引導設定** （右上角的按鈕）  
![\[螢幕擷取畫面反白顯示「開始引導設定」按鈕。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/IAC_start_guided_setup_1.png)

1. 在**設定屬性映射**中，按一下**下一步**

1. 在設定同步範圍區段中，輸入您要同步至身分中心的使用者名稱，然後按一下**新增**

1. 新增使用者和群組完成後，請按一下**下一步**  
![\[螢幕擷取畫面反白顯示下一步按鈕。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/IAC_guided_setup_add_users_groups_2.png)

1. 檢閱您的變更，然後按一下**儲存組態**

1. 如果您在下一個畫面中看到有關使用者未同步的警告，請選取右上角的**繼續同步按鈕**。

1. 接下來，若要啟用使用者，請在左側**的使用者**索引標籤中選取使用者，然後按一下**啟用使用者存取** > **啟用使用者存取** 

   **注意**：如果您的頂端有警告橫幅，然後等待使用者同步 （嘗試重新整理按鈕以查看是否已同步），您可能需要選取繼續同步。  
![\[螢幕擷取畫面反白顯示使用者索引標籤。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/IAC_enable_user_access_3.png)

## 將應用程式新增至 IAM Identity Center
<a name="adding-apps-to-iam-identity-center-v3"></a>

將使用者與 IAM Identity Center 同步後，您將需要新增應用程式。這會設定哪些啟用 SSO 的應用程式可從 IAM Identity Center 入口網站使用。在此情況下，我們將新增 AWS ParallelCluster UI 做為應用程式，而 IAM Identity Center 將做為身分提供者。

下一個步驟會將 AWS ParallelCluster UI 新增為 IAM Identity Center 中的應用程式。 AWS ParallelCluster UI 是一種 Web 入口網站，可協助使用者管理其叢集。如需詳細資訊，請參閱 [AWS ParallelCluster UI](pcui-using-v3.md)。

**在 Identity Center 中設定應用程式**

1. 在 **IAM Identity Center** > **應用程式**下 （位於左側選單列，按一下應用程式）

1. 按一下**新增應用程式**

1. 選取**新增自訂 SAML 2.0 應用程式**

1. 按一下**下一步**

1. 選取您想要使用的顯示名稱和描述 （例如 PCUI 和 AWS ParallelCluster UI)

1. 在 **IAM Identity Center 中繼資料**下，複製 IAM Identity Center SAML 中繼資料檔案的連結並儲存以供稍後使用，這將在 Web 應用程式中設定 SSO 時使用

1. 在**應用程式屬性**下，在應用程式啟動 URL 中，放置您的 PCUI 地址。您可以前往 CloudFormation 主控台、選取對應至 PCUI 的堆疊 （例如 parallelcluster-ui)，以及前往**輸出**索引標籤尋找 ParallelClusterUIUrl

   例如 https://m2iwazsi1j.execute-api.us-east-1.amazonaws.com

1. 在**應用程式中繼資料**下，選擇**手動輸入中繼資料值**。然後提供下列值。

   1. **重要**：請務必將 domain-prefix、region 和 userpool-id 值取代為您環境的特定資訊。

   1. 開啟 **Amazon Cognito** > **使用者集區主控台**，即可取得網域字首、區域和使用者集區 ID  
![\[Cognito 使用者集區下的反白使用者集區名稱的螢幕擷取畫面\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/Amazon_cognito_user_pools_4.png)

   1. 選取對應至 PCUI 的使用者集區 （其將具有使用者集區名稱，例如 pcui-cd8a2-Cognito-153EK3TO45S98-userpool)

   1. 導覽至**應用程式整合**  
![\[應用程式整合標籤中反白 Cognito 網域的螢幕擷取畫面\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/Amazon_cognito_app_integration_5.png)

1. 應用程式聲明消費者服務 (ACS) URL：https：//https://<domain-prefix>.auth.<region>.amazoncognito.com/saml2/idpresponse

   應用程式 SAML 對象：urn：amazon：cognito：sp：<userpool-id>

1. 選擇**提交**。然後，前往您新增之應用程式**的詳細資訊**頁面。

1. 選取**動作**下拉式清單，然後選擇**編輯屬性映射**。然後，提供下列屬性。

   1. 應用程式的使用者屬性：**主體** （注意：**主體**已預先填入。) → 映射至 IAM Identity Center 中的此字串值或使用者屬性：**\$1\$1user：email\$1**，格式：**emailAddress**

   1. 應用程式的使用者屬性：**電子郵件** → 映射到此字串值或 IAM Identity Center 中的使用者屬性：**\$1\$1user：email\$1**，格式：**未指定**  
![\[螢幕擷取畫面反白顯示 PCUI 的屬性映射區段\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/IAC_attribute_mappings_PCUI_6.png)

1. 儲存您的變更。

1. 選擇**指派使用者**按鈕，然後將您的使用者指派給應用程式。這些是 Active Directory 中可存取 PCUI 介面的使用者。  
![\[螢幕擷取畫面反白顯示 為應用程式指派使用者。\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/IAC_PCUI_App_7.png)

**在使用者集區中將 IAM Identity Center 設定為 SAML IdP **

1. 在使用者集區設定中，選取**登入體驗** > **新增身分提供者**  
![\[螢幕擷取畫面反白 登入體驗索引標籤\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/Amazon_cognito_sign_in_expereince_8.png)

1. 選擇 SAML IdP

1. 對於**提供者名稱**，請提供 **IdentityCenter**

1. 在**中繼資料文件來源**下，選擇**輸入中繼資料文件端點 URL**，並提供在 Identity Center 的應用程式設定期間複製的 URL

1. 在 **屬性**下，針對電子郵件選擇電子郵件  
![\[螢幕擷取畫面反白 登入體驗索引標籤\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/Amazonw_cognito_SAML_9.png)

1. 選取 **新增身分供應商**。

**將 IdP 與使用者集區應用程式用戶端整合**

1. 接著，在使用者集區的**應用程式整合**區段下，選擇**應用程式用戶端清單下列出的用戶端**  
![\[螢幕擷取畫面反白 登入體驗索引標籤\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/Amazon_cognito_user_pool_app_client_10.png)

1. 在**託管 UI** 下選擇**編輯**

1. 在**身分提供者**下，也選擇 **IdentityCenter**。

1. 選擇 **Save changes (儲存變更)**

**驗證您的設定**

1. 接下來，我們將透過登入 PCUI 驗證剛建立的設定。登入 PCUI 入口網站，現在您應該會看到使用公司 ID 登入的選項：  
![\[螢幕擷取畫面反白 登入體驗索引標籤\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/Amazon_cognito_validate_step_11.png)

1. 按一下 **IdentityCenter** 按鈕應該會帶您前往 IAM Identity Center IdP 登入，後面接著包含 PCUI 的應用程式頁面，開啟該應用程式。

1. 進入下列畫面後，您的使用者將新增至 Cognito 使用者集區。  
![\[螢幕擷取畫面反白 登入體驗索引標籤\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/Amazon_cognito_continue_with_IC_12.png)

**讓您的使用者成為管理員**

1. 現在導覽至 **Amazon Cognito** > **使用者集區主控台**，然後選取應具有 identitycenter 字首的新建立使用者  
![\[螢幕擷取畫面反白 登入體驗索引標籤\]](http://docs.aws.amazon.com/zh_tw/parallelcluster/latest/ug/images/tutorials/pcui_awsic_integration/Amazon_cognito_user_pools_new_created_user_13.png)

1. 在**群組成員**資格下，選取**新增使用者至群組**，選擇**管理員**並按一下**新增**。

1. 現在當您按一下**繼續 IdentityCenter** 時，將會導覽至 UI AWS ParallelCluster 頁面。

# 使用 Pyxis 執行容器化任務
<a name="tutorials_11_running-containerized-jobs-with-pyxis"></a>

了解如何建立叢集，該叢集可以使用「Pyxis」執行容器化任務，這是一種 SPANK 外掛程式，可在 SLURM 中管理容器化任務。Pyxis 中的容器由 Enroot 管理，這是將傳統容器/OS 映像轉換為無權限沙盒的工具。如需詳細資訊，請參閱 [NVIDIA Pyxis](https://github.com/NVIDIA/pyxis) 和 [NVIDIA Enroot](https://github.com/NVIDIA/enroot)。

**注意**  
此功能適用於 AWS ParallelCluster v3.11.1
本教學課程中的指令碼會移動 (`mv`) 一些檔案，從原始位置將其刪除。如果您想要將這些檔案的副本保留在原始位置，請變更指令碼以改用 copy (`cp`) 命令。

使用 時 AWS ParallelCluster，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

**事前準備：**
+  AWS CLI [ 已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ [ Amazon EC2 金鑰對。](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)
+ 具有執行叢集 CLI 所需[許可](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)的 IAM 角色。[https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)

## 建立叢集
<a name="create-the-cluster"></a>

從 AWS ParallelCluster 3.11.1 開始，所有官方 AMIs都隨附預先安裝的 Pyxis 和 Enroot。特別是，SLURM 會重新編譯為使用「Pyxis 支援」，Enroot 會安裝為系統中的二進位檔。不過，您必須根據您的特定需求進行設定。Enroot 和 Pyxis 使用的資料夾將對叢集效能產生重大影響。如需詳細資訊，請參閱 [Pyxis 文件](https://github.com/NVIDIA/pyxis/wiki/Setup#slurm-plugstack-configuration)和 [Enroot 文件。](https://github.com/NVIDIA/pyxis/wiki/Setup#enroot-configuration-example)

為方便起見，您可以在 中找到適用於 Pyxis、Enroot 和 SPANK 的範例組態`/opt/parallelcluster/examples/`。

若要使用我們提供的範例組態來部署叢集，請完成下列教學課程。

**使用範例組態建立叢集**

必須先為 Enroot 建立持久性和揮發性目錄，然後為 Pyxis 建立執行期目錄，最後在整個叢集中啟用 Pyxis 做為 SPANK 外掛程式，才能在前端節點上設定 Pyxis 和 Enroot。

1. 在前端節點中執行以下指令碼做為 [OnNodeConfigured](HeadNode-v3.md#yaml-HeadNode-CustomActions-OnNodeConfigured) 自訂動作，以在前端節點上設定 Pyxis 和 Enroot。

   ```
   #!/bin/bash
   set -e
   
   echo "Executing $0"
   
   # Configure Enroot
   ENROOT_PERSISTENT_DIR="/var/enroot"
   ENROOT_VOLATILE_DIR="/run/enroot"
   
   sudo mkdir -p $ENROOT_PERSISTENT_DIR
   sudo chmod 1777 $ENROOT_PERSISTENT_DIR
   sudo mkdir -p $ENROOT_VOLATILE_DIR
   sudo chmod 1777 $ENROOT_VOLATILE_DIR
   sudo mv /opt/parallelcluster/examples/enroot/enroot.conf /etc/enroot/enroot.conf
   sudo chmod 0644 /etc/enroot/enroot.conf
   
   # Configure Pyxis
   PYXIS_RUNTIME_DIR="/run/pyxis"
   
   sudo mkdir -p $PYXIS_RUNTIME_DIR
   sudo chmod 1777 $PYXIS_RUNTIME_DIR
   
   sudo mkdir -p /opt/slurm/etc/plugstack.conf.d/
   sudo mv /opt/parallelcluster/examples/spank/plugstack.conf /opt/slurm/etc/
   sudo mv /opt/parallelcluster/examples/pyxis/pyxis.conf /opt/slurm/etc/plugstack.conf.d/
   sudo -i scontrol reconfigure
   ```

1. 在運算機群上，必須透過為 Enroot 建立持久性和揮發性目錄，以及為 Pyxis 建立執行時間目錄，來設定 Pyxis 和 Enroot。在運算節點中執行以下指令碼做為 [OnNodeStart](Scheduling-v3.md#yaml-Scheduling-SlurmQueues-CustomActions-OnNodeStart) 自訂動作，以在運算機群上設定 Pyxis 和 Enroot。

   ```
   #!/bin/bash
   set -e
   
   echo "Executing $0"
   
   # Configure Enroot
   ENROOT_PERSISTENT_DIR="/var/enroot"
   ENROOT_VOLATILE_DIR="/run/enroot"
   ENROOT_CONF_DIR="/etc/enroot"
   
   sudo mkdir -p $ENROOT_PERSISTENT_DIR
   sudo chmod 1777 $ENROOT_PERSISTENT_DIR
   sudo mkdir -p $ENROOT_VOLATILE_DIR
   sudo chmod 1777 $ENROOT_VOLATILE_DIR
   sudo mkdir -p $ENROOT_CONF_DIR
   sudo chmod 1777 $ENROOT_CONF_DIR
   sudo mv /opt/parallelcluster/examples/enroot/enroot.conf /etc/enroot/enroot.conf
   sudo chmod 0644 /etc/enroot/enroot.conf
   
   # Configure Pyxis
   PYXIS_RUNTIME_DIR="/run/pyxis"
   
   sudo mkdir -p $PYXIS_RUNTIME_DIR
   sudo chmod 1777 $PYXIS_RUNTIME_DIR 
   
   # In Ubuntu24.04 Apparmor blocks the creation of unprivileged user namespaces,
   # which is required by Enroot. So to run Enroot, it is required to disable this restriction.
   # See https://ubuntu.com/blog/ubuntu-23-10-restricted-unprivileged-user-namespaces
   source /etc/os-release
   if [ "${ID}${VERSION_ID}" == "ubuntu24.04" ]; then
       echo "kernel.apparmor_restrict_unprivileged_userns = 0" | sudo tee /etc/sysctl.d/99-pcluster-disable-apparmor-restrict-unprivileged-userns.conf
       sudo sysctl --system
   fi
   ```

## 提交任務
<a name="submit-jobs"></a>

現在，Pyxis 已在您的叢集中設定，您可以使用 sbatch and srun 命令來提交容器化任務，這些任務現在已擴充容器特定選項。

```
# Submitting an interactive job
srun -N 2 --container-image docker://ubuntu:22.04 hostname

# Submitting a batch job
sbatch -N 2 --wrap='srun --container-image docker://ubuntu:22.04 hostname'
```

# 使用啟用 EFA 的 FSx Lustre 建立叢集
<a name="tutorial-efa-enabled-fsx-lustre"></a>

在本教學課程中，您將建立使用啟用 EFA 的 FSx Lustre 檔案系統做為共用儲存體的叢集。在啟用 EFA 的情況下使用 FSx Lustre 檔案系統，可將效能提升高達 8 倍。若要驗證已啟用 EFA 的檔案系統是否為您需要的檔案系統，請參閱《*FSx for Lustre 使用者指南*》中的[使用已啟用 EFA 的檔案系統](https://docs.aws.amazon.com/fsx/latest/LustreGuide/efa-file-systems.html)。

使用 時 AWS ParallelCluster，您只需為建立或更新 AWS ParallelCluster 映像和叢集時建立 AWS 的資源付費。如需詳細資訊，請參閱[AWS 使用的 服務 AWS ParallelCluster](aws-services-v3.md)。

## 需求
<a name="tutorial-efa-enabled-fsx-lustre-requirements"></a>
+ [已安裝並設定](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) AWS CLI。
+ [已安裝並設定](install-v3-parallelcluster.md) ParallelCluster CLI。
+ 用於登入叢集的 [Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)。
+ 具有執行 ParallelCluster CLI 所需[許可](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)的 IAM 角色。

## 建立安全群組
<a name="tutorial-efa-enabled-fsx-lustre-security-groups"></a>

在將部署叢集和檔案系統的相同 VPC 中建立兩個安全群組：一個用於叢集節點上執行的用戶端，另一個用於檔案系統。

```
# Create security group for the FSx client
aws ec2 create-security-group \
    --group-name Fsx-Client-SecurityGroup \
    --description "Allow traffic for the FSx Lustre client" \
    --vpc-id vpc-cluster \
    --region region

# Create security group for the FSx file system
aws ec2 create-security-group \
    --group-name Fsx-FileSystem-SecurityGroup \
    --description "Allow traffic for the FSx Lustre File System" \
    --vpc-id vpc-cluster \
    --region region
```

在教學課程的其餘部分中，我們將假設 `sg-client`和 分別`sg-file-system`是用戶端和檔案系統的安全群組 ID。

根據 [EFA 的要求](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html#efa-start-security)，設定用戶端的安全群組，以允許所有傳出流量流向檔案系統。

```
# Allow all outbound traffic from the client to the file system
aws ec2 authorize-security-group-egress \
 --group-id sg-client \ 
 --protocol -1 \
 --port -1 \
 --source-group sg-file-system \
 --region region
```

設定檔案系統的安全群組，以允許其本身的所有傳入/傳出流量，以及 [EFA 要求](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html#efa-start-security)的所有來自用戶端的傳入流量。

```
# Allow all inbound traffic within this security group
aws ec2 authorize-security-group-ingress \
    --group-id sg-file-system \
    --protocol -1 \
    --port -1 \
    --source-group sg-file-system \
    --region region

# Allow all outbound traffic within this security group
aws ec2 authorize-security-group-egress \
    --group-id sg-file-system \
    --protocol -1 \
    --port -1 \
    --source-group sg-file-system \
    --region region

# Allow all inbound traffic from the client
aws ec2 authorize-security-group-ingress \
    --group-id sg-file-system \
    --protocol -1 \
    --port -1 \
    --source-group sg-client \
    --region region

# Allow all outbound traffic to the client
aws ec2 authorize-security-group-egress \
    --group-id sg-file-system \
    --protocol -1 \
    --port -1 \
    --source-group sg-client \
    --region region
```

## 建立檔案系統
<a name="tutorial-efa-enabled-fsx-lustre-create-filesystem"></a>

在運算節點所在的相同可用區域 (AZ) 內建立檔案系統；並在下列程式碼中`subnet-compute-nodes`以其 ID 取代 。這是允許 EFA 與您的檔案系統搭配使用的必要條件。請注意，在建立檔案系統的過程中，我們使用 EfaEnable 屬性啟用 EFA。

```
aws fsx create-file-system \
    --file-system-type LUSTRE \
    --storage-capacity 38400 \
    --storage-type SSD \
    --subnet-ids subnet-compute-nodes \
    --security-group-ids sg-file-system \
    --lustre-configuration DeploymentType=PERSISTENT_2,PerUnitStorageThroughput=125,EfaEnabled=true,MetadataConfiguration={Mode=AUTOMATIC} \
    --region region
```

請記下上一個命令傳回的檔案系統 ID。在教學課程的其餘部分中，`fs-id`使用此檔案系統 ID 取代 。

## 建立叢集
<a name="tutorial-efa-enabled-fsx-lustre-create-cluster"></a>

1. 使用 YAML 組態檔案中設定的 AWS ParallelCluster 下列組態建立叢集：

   1. 以支援的作業系統為基礎的 AMI，例如 Ubuntu 22.04。

   1. 運算節點必須使用具有 [Nitro v4\$1](https://docs.aws.amazon.com/ec2/latest/instancetypes/ec2-nitro-instances.html) 的 [EFA 支援的執行個體類型](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html#efa-instance-types)，例如 g6.16xlarge。
      + 運算節點必須位於檔案系統所在的相同 AZ 中。
      + 運算節點必須將 [Efa/Enabled](Scheduling-v3.md#yaml-Scheduling-SlurmQueues-ComputeResources-Efa-Enabled) 設定為 true。
      + 運算節點必須以 [OnNodeStart](Scheduling-v3.md#yaml-Scheduling-SlurmQueues-CustomActions-OnNodeStart) 自訂動作`configure-efa-fsx-lustre-client.sh`的形式執行組態指令碼。為了方便起見，[FSx 官方文件中](https://docs.aws.amazon.com/fsx/latest/LustreGuide/configure-efa-clients.html)提供的指令碼和公有儲存貯體中提供的指令碼旨在設定運算節點上的 FSx Lustre 用戶端，讓他們使用 EFA。

1. 建立叢集組態檔案 `config.yaml`：

   ```
   Region: region
   Image:
     Os: ubuntu2204
   HeadNode:
     InstanceType: c5.xlarge
     Networking:
       SubnetId: subnet-xxxxxxxxxx
       AdditionalSecurityGroups:
           - sg-client
     Ssh:
       KeyName: my-ssh-key
   Scheduling:
     Scheduler: slurm
     SlurmQueues:
       - Name: q1
         ComputeResources:
           - Name: cr1
             Instances:
               - InstanceType: g6.16xlarge
             MinCount: 1
             MaxCount: 3
             Efa:
               Enabled: true
         Networking:
           SubnetIds:
             - subnet-xxxxxxxxxx # Subnet in the same AZ where the file system is
           AdditionalSecurityGroups:
             - sg-client
           PlacementGroup:
             Enabled: false
         CustomActions:
           OnNodeStart:
             Script: https://us-east-1-aws-parallelcluster.s3.us-east-1.amazonaws.com/scripts/fsx-lustre-efa/configure-efa-fsx-lustre-client.sh
   SharedStorage:
     - MountDir: /fsx
       Name: my-fsxlustre-efa-external
       StorageType: FsxLustre
       FsxLustreSettings:
         FileSystemId: fs-id
   ```

   然後使用該組態建立叢集：

   ```
   pcluster create-cluster \
       --cluster-name fsx-efa-tutorial \
       --cluster-configuration config.yaml \
       --region region
   ```

## 使用 EFA 驗證 FSx 正在運作
<a name="tutorial-efa-enabled-fsx-lustre-validate"></a>

若要驗證 Lustre 網路流量是否使用 EFA，請使用 Lustre `lnetctl`工具來顯示指定網路介面的網路流量。為此，請在運算節點中執行下列命令：

```
# Take note of the number of packets flowing through the interface, 
# which are specified in statistics:send_count and statistics:recv_count
sudo lnetctl net show --net efa -v

# Generate traffic to the file system
echo 'Hello World' > /fsx/hello-world.txt

# Take note of the number of packets flowing through the interface, 
# which are specified in statistics:send_count and statistics:recv_count
sudo lnetctl net show --net efa -v
```

如果功能正常運作，流經界面的封包數量預期會增加。

# 使用 p6e-gb200 執行個體支援 NVIDIA-Imex
<a name="support-nvidia-imex-p6e-gb200-instance"></a>

本教學課程說明如何在 P6e-GB200 AWS ParallelCluster 上開始使用 ，以利用最高 GPU 效能進行 AI 訓練和推論。[p6e-gb200.36xlarge 執行個體只能透過 P6e-GB200 UltraServers 使用](https://aws.amazon.com/ec2/instance-types/p6/)，其中 `u-p6e-gb200x72`是 Ultraserver Size，而 `p6e-gb200.36xlarge`是 [InstanceType](Scheduling-v3.md#yaml-Scheduling-SlurmQueues-ComputeResources-InstanceType)，其會形成超伺服器。購買 Ultraserver 時`u-p6e-gb200x72`，可透過具有 18 個`p6e-gb200.36xlarge`執行個體[的適用於 ML 的 EC2 容量區塊](https://aws.amazon.com/ec2/capacityblocks/)取得。若要進一步了解，請參閱 [P6e-GB200](https://aws.amazon.com/ec2/instance-types/p6/)。

AWS ParallelCluster 3.14.0 版：
+ 提供此執行個體類型所需的完整 NVIDIA 軟體堆疊 （驅動程式、CUDA、EFA、NVIDIA-IMEX) 
+ 為 P6e-GB200 Ultraserver 建立 nvidia-imex 組態
+ 啟用和啟動 P6e-GB200 Ultraserver `nvidia-imex`的服務
+ 設定 Slurm Block 拓撲外掛程式，讓每個 P6e-GB200 Ultraserver (EC2 容量區塊） 都是大小正確的 Slurm Block （請參閱 3.14.0 版[版本備註和文件歷史記錄](document_history.md)的項目）。

不過，透過 NVLink 的 GPU-to-GPU 通訊需要額外的組態，特別是包含 ParallelCluster 不會自動產生之 IMEX 網域中運算節點 IP 地址[https://docs.nvidia.com/multi-node-nvlink-systems/imex-guide/config.html#imex-service-node-configuration-file-location](https://docs.nvidia.com/multi-node-nvlink-systems/imex-guide/config.html#imex-service-node-configuration-file-location)的檔案。為了協助產生此檔案，我們提供 Prolog 指令碼，可自動探索運算節點 IPs，並設定[https://docs.nvidia.com/multi-node-nvlink-systems/imex-guide/config.html#imex-service-node-configuration-file-location](https://docs.nvidia.com/multi-node-nvlink-systems/imex-guide/config.html#imex-service-node-configuration-file-location)下列 [ NVIDIA IMEX Slurm 任務排程器整合](https://docs.nvidia.com/multi-node-nvlink-systems/imex-guide/deployment.html#job-scheduler-integration)建議。本教學課程會逐步解說如何建立 prolog 指令碼、透過 HeadNode 自訂動作部署，以及驗證 IMEX 設定。

**注意**  
從 Amazon Linux 2023、Ubuntu 22.04 和 Ubuntu 24.04 的 v3.14.0 開始，支援 P6e-GB200。 AWS ParallelCluster 如需詳細的軟體版本和更新的支援分佈清單，請參閱[AWS ParallelCluster 變更日誌](https://github.com/aws/aws-parallelcluster/blob/develop/CHANGELOG.md)。

## 建立 Prolog 指令碼以管理 NVIDIA-Imex
<a name="support-nvidia-imex-p6e-gb200-instance-prolog"></a>

**限制：**
+ 此 prolog 指令碼將在提交專屬任務時執行。這是為了確保 IMEX 重新啟動不會中斷屬於 IMEX 網域之 p6e-Gb200 節點上的任何執行中任務。

以下是您應該在 Slurm 中設定為 Prolog 的`91_nvidia_imex_prolog.sh`指令碼。它用於自動更新運算節點上的 nvidia-imex 組態。指令碼名稱的字首為 `91`，以遵循 [ SchedMD 的命名慣例](https://slurm.schedmd.com/prolog_epilog.html)。這可確保它在序列中的任何其他 prolog 指令碼之前執行。指令碼會在任務啟動時重新設定 NVIDIA Imex 節點的組態，並重新載入必要的 NVIDIA 協助程式。

**注意**  
如果相同節點上同時啟動多個任務，則不會執行此指令碼，因此我們建議在提交時使用 `--exclusive`旗標。

```
#!/usr/bin/env bash

# This prolog script configures the NVIDIA IMEX on compute nodes involved in the job execution.
#
# In particular:
# - Checks whether the job is executed exclusively.
#   If not, it exits immediately because it requires jobs to be executed exclusively.
# - Checks if it is running on a p6e-gb200 instance type.
#   If not, it exits immediately because IMEX must be configured only on that instance type.
# - Checks if the IMEX service is enabled.
#   If not, it exits immediately because IMEX must be enabled to get configured.
# - Creates the IMEX default channel.
#   For more information about IMEX channels, see https://docs.nvidia.com/multi-node-nvlink-systems/imex-guide/imexchannels.html
# - Writes the private IP addresses of compute nodes into /etc/nvidia-imex/nodes_config.cfg.
# - Restarts the IMEX system service.
#
# REQUIREMENTS:
#  - This prolog assumes to be run only with exclusive jobs.

LOG_FILE_PATH="/var/log/parallelcluster/nvidia-imex-prolog.log"
SCONTROL_CMD="/opt/slurm/bin/scontrol"
IMEX_START_TIMEOUT=60
IMEX_STOP_TIMEOUT=15
ALLOWED_INSTANCE_TYPES="^(p6e-gb200)"
IMEX_SERVICE="nvidia-imex"
IMEX_NODES_CONFIG="/etc/nvidia-imex/nodes_config.cfg"

function info() {
  echo "$(date "+%Y-%m-%dT%H:%M:%S.%3N") [INFO] [PID:$$] [JOB:${SLURM_JOB_ID}] $1"
}

function warn() {
  echo "$(date "+%Y-%m-%dT%H:%M:%S.%3N") [WARN] [PID:$$] [JOB:${SLURM_JOB_ID}] $1"
}

function error() {
  echo "$(date "+%Y-%m-%dT%H:%M:%S.%3N") [ERROR] [PID:$$] [JOB:${SLURM_JOB_ID}] $1"
}

function error_exit() {
  error "$1" && exit 1
}

function prolog_end() {
    info "PROLOG End JobId=${SLURM_JOB_ID}: $0"
    info "----------------"
    exit 0
}

function get_instance_type() {
  local token=$(curl -X PUT -s "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
  curl -s -H "X-aws-ec2-metadata-token: ${token}" http://169.254.169.254/latest/meta-data/instance-type
}

function return_if_unsupported_instance_type() {
  local instance_type=$(get_instance_type)

  if [[ ! ${instance_type} =~ ${ALLOWED_INSTANCE_TYPES} ]]; then
    info "Skipping IMEX configuration because instance type ${instance_type} does not support it"
    prolog_end
  fi
}

function return_if_imex_disabled() {
  if ! systemctl is-enabled "${IMEX_SERVICE}" &>/dev/null; then
    warn "Skipping IMEX configuration because system service ${IMEX_SERVICE} is not enabled"
    prolog_end
  fi
}

function return_if_job_is_not_exclusive() {
  if [[ "${SLURM_JOB_OVERSUBSCRIBE}" =~ ^(NO|TOPO)$  ]]; then
    info "Job is exclusive, proceeding with IMEX configuration"
  else
    info "Skipping IMEX configuration because the job is not exclusive"
    prolog_end
  fi
}

function get_ips_from_node_names() {
  local _nodes=$1
  ${SCONTROL_CMD} -ao show node "${_nodes}" | sed 's/^.* NodeAddr=\([^ ]*\).*/\1/'
}

function get_compute_resource_name() {
  local _queue_name_prefix=$1
  local _slurmd_node_name=$2
  echo "${_slurmd_node_name}" | sed -E "s/${_queue_name_prefix}(.+)-[0-9]+$/\1/"
}

function reload_imex() {
  info "Stopping IMEX"
  timeout ${IMEX_STOP_TIMEOUT} systemctl stop ${IMEX_SERVICE}
  pkill -9 ${IMEX_SERVICE}

  info "Restarting IMEX"
  timeout ${IMEX_START_TIMEOUT} systemctl start ${IMEX_SERVICE}
}

function create_default_imex_channel() {
  info "Creating IMEX default channel"
  MAJOR_NUMBER=$(cat /proc/devices | grep nvidia-caps-imex-channels | cut -d' ' -f1)
  if [ ! -d "/dev/nvidia-caps-imex-channels" ]; then
    sudo mkdir /dev/nvidia-caps-imex-channels
  fi

  # Then check and create device node
  if [ ! -e "/dev/nvidia-caps-imex-channels/channel0" ]; then
    sudo mknod /dev/nvidia-caps-imex-channels/channel0 c $MAJOR_NUMBER 0
    info "IMEX default channel created"
  else
    info "IMEX default channel already exists"
  fi
}

{
  info "PROLOG Start JobId=${SLURM_JOB_ID}: $0"

  return_if_job_is_not_exclusive
  return_if_unsupported_instance_type
  return_if_imex_disabled

  create_default_imex_channel

  IPS_FROM_CR=$(get_ips_from_node_names "${SLURM_NODELIST}")

  info "Node Names: ${SLURM_NODELIST}"
  info "Node IPs: ${IPS_FROM_CR}"
  info "IMEX Nodes Config: ${IMEX_NODES_CONFIG}"

  info "Updating IMEX nodes config ${IMEX_NODES_CONFIG}"
  echo "${IPS_FROM_CR}" > "${IMEX_NODES_CONFIG}"
  reload_imex

  prolog_end

} 2>&1 | tee -a "${LOG_FILE_PATH}" | logger -t "91_nvidia_imex_prolog"
```

## 建立 HeadNode OnNodeStart 自訂動作指令碼
<a name="support-nvidia-imex-p6e-gb200-instance-action-script"></a>

建立`install_custom_action.sh`自訂動作，其將在運算節點存取的共用目錄中下載上述 prolog 指令碼`/opt/slurm/etc/scripts/prolog.d/`，並設定要執行的適當許可。

```
#!/bin/bash
set -e

echo "Executing $0"

PROLOG_NVIDIA_IMEX=/opt/slurm/etc/scripts/prolog.d/91_nvidia_imex_prolog.sh
aws s3 cp "s3://<Bucket>/91_nvidia_imex_prolog.sh" "${PROLOG_NVIDIA_IMEX}"
chmod 0755 "${PROLOG_NVIDIA_IMEX}"
```

## 建立叢集
<a name="support-nvidia-imex-p6e-gb200-instance-cluster"></a>

建立包含 P6e-GB200 執行個體的叢集。您可以在下面找到包含 Ultraserver 類型 的 SlurmQueues 的範例組態`u-p6e-gb200x72`。

P6e-GB200 目前僅適用於 Local Zones。有些 [Local Zones 不支援 NAT Gateway](https://docs.aws.amazon.com/local-zones/latest/ug/local-zones-connectivity-nat.html)，因此請遵循 [Local Zones 的連線選項](https://docs.aws.amazon.com/local-zones/latest/ug/local-zones-connectivity.html)，因為 ParallelCluster [設定受限環境的安全群組](security-groups-configuration.md)需要連線到 AWS 服務。請遵循 [使用容量區塊 (CB) 啟動執行個體](launch-instances-capacity-blocks.md)(AWS ParallelClusterLaunch)，因為 Ultraserver 僅供容量區塊使用。

```
HeadNode:
  CustomActions:
    OnNodeStart:
      Script: s3://<s3-bucket-name>/install_custom_action.sh
    S3Access:
      - BucketName: <s3-bucket-name>
  InstanceType: <HeadNode-instance-type>
  Networking:
    SubnetId: <subnet-abcd78901234567890>
  Ssh:
    KeyName: <Key-name>
Image:
  Os: ubuntu2404
Scheduling:
  Scheduler: slurm
  SlurmSettings:
    CustomSlurmSettings:
      - PrologFlags: "Alloc,NoHold"
      - MessageTimeout: 240
  SlurmQueues:
    - CapacityReservationTarget:
        CapacityReservationId: <cr-123456789012345678>
      CapacityType: CAPACITY_BLOCK
      ComputeResources: ### u-p6e-gb200x72
        - DisableSimultaneousMultithreading: true
          Efa:
            Enabled: true
          InstanceType: p6e-gb200.36xlarge  
          MaxCount: 18
          MinCount: 18
          Name: cr1
      Name: q1
      Networking:
        SubnetIds:
          - <subnet-1234567890123456>
```

## 驗證 IMEX 設定
<a name="support-nvidia-imex-p6e-gb200-instance-validate"></a>

當您提交 Slurm 任務時，將會執行 `91_nvidia_imex_prolog.sh` prolog。以下是檢查 NVIDIA-imex 網域狀態的範例任務。

```
#!/bin/bash
#SBATCH --job-name=nvidia-imex-status-job
#SBATCH --ntasks-per-node=1
#SBATCH --output=slurm-%j.out
#SBATCH --error=slurm-%j.err

QUEUE_NAME="q1"
COMPUTE_RES_NAME="cr1"
IMEX_CONFIG_FILE="/opt/parallelcluster/shared/nvidia-imex/config_${QUEUE_NAME}_${COMPUTE_RES_NAME}.cfg"

srun bash -c "/usr/bin/nvidia-imex-ctl -N -c ${IMEX_CONFIG_FILE} > result_\${SLURM_JOB_ID}_\$(hostname).out 2> result_\${SLURM_JOB_ID}_\$(hostname).err"
```

檢查任務的輸出：

```
Connectivity Table Legend:
I - Invalid - Node wasn't reachable, no connection status available
N - Never Connected
R - Recovering - Connection was lost, but clean up has not yet been triggered.
D - Disconnected - Connection was lost, and clean up has been triggreed.
A - Authenticating - If GSSAPI enabled, client has initiated mutual authentication.
!V! - Version mismatch, communication disabled.
!M! - Node map mismatch, communication disabled.
C - Connected - Ready for operation

5/12/2025 06:08:10.580
Nodes:
Node #0   - 172.31.48.81    - READY                - Version: 570.172
Node #1   - 172.31.48.98    - READY                - Version: 570.172
Node #2   - 172.31.48.221   - READY                - Version: 570.172
Node #3   - 172.31.49.228   - READY                - Version: 570.172
Node #4   - 172.31.50.39    - READY                - Version: 570.172
Node #5   - 172.31.50.44    - READY                - Version: 570.172
Node #6   - 172.31.51.66    - READY                - Version: 570.172
Node #7   - 172.31.51.157   - READY                - Version: 570.172
Node #8   - 172.31.52.239   - READY                - Version: 570.172
Node #9   - 172.31.53.80    - READY                - Version: 570.172
Node #10  - 172.31.54.95    - READY                - Version: 570.172
Node #11  - 172.31.54.183   - READY                - Version: 570.172
Node #12  - 172.31.54.203   - READY                - Version: 570.172
Node #13  - 172.31.54.241   - READY                - Version: 570.172
Node #14  - 172.31.55.59    - READY                - Version: 570.172
Node #15  - 172.31.55.187   - READY                - Version: 570.172
Node #16  - 172.31.55.197   - READY                - Version: 570.172
Node #17  - 172.31.56.47    - READY                - Version: 570.172

 Nodes From\To  0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17
       0        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C 
       1        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C 
       2        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C
       3        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C  
       4        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C 
       5        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C 
       6        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C
       7        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C 
       8        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C 
       9        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   
      10        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   
      11        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   
      12        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   
      13        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   
      14        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C  
      15        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C  
      16        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C  
      17        C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C   C  

Domain State: UP
```

# 使用啟動範本覆寫自訂運算節點網路介面
<a name="tutorial-network-customization-v3"></a>

從 AWS ParallelCluster 3.15.0 開始， `LaunchTemplateOverrides` 參數可讓您使用參考啟動範本中的組態覆寫預設網路介面組態，以自訂運算節點的網路介面。用於覆寫的啟動範本的網路介面區段會覆寫運算節點的整個網路介面區段。

本教學課程會逐步解說覆寫`p6-b300.48xlarge`運算節點預設網路組態的範例。當您需要與預設 AWS ParallelCluster 設定不同的特定網路介面組態時，此自訂很有用。在此範例中，我們為 P6-B300 執行個體設定使用案例 2，如 [Amazon EC2 EFA 支援的執行個體類型文件](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-acc-inst-types.html)所述。

**注意**  
建議您使用 AWS CLI 來建立啟動範本，而非主控台，以獲得最大的彈性。

**注意**  
啟動範本應該只包含網路介面覆寫。 AWS ParallelCluster 具有防止覆寫其他參數的驗證。

**警告**  
如果您使用覆寫以使用執行個體類型不支援的方式設定網路介面，則執行個體將無法啟動。

**先決條件**
+ AWS ParallelCluster [已安裝](install-v3-parallelcluster.md) 3.15.0 版或更新版本。
+  AWS CLI [已安裝並設定 。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ 您有一個 IAM 角色，具有執行 CLI [`pcluster`](pcluster-v3.md) 所需的[許可](iam-roles-in-parallelcluster-v3.md#iam-roles-in-parallelcluster-v3-example-user-policies)。

## 步驟 1：建立安全群組
<a name="tutorial-network-customization-v3-security-groups"></a>

建立要在覆寫中使用的啟動範本時，您必須參考安全群組。在叢集建立之前，運算資源的預設 AWS ParallelCluster 安全群組不存在，因此您必須建立自訂安全群組。然後，前端節點安全群組必須參考此安全群組，以允許前端節點和運算節點之間的流量。

如果您要更新現有叢集以自訂新容量，則可以在啟動範本中使用預設 AWS ParallelCluster 運算節點安全群組，而不是建立自訂叢集。

建立下列兩個安全群組：
+ **標頭節點額外安全群組** (`sg-1234abcd`)：
  + 傳入：來自運算安全群組的所有流量
+ **運算安全群組** (`sg-abcd1234`)：
  + 輸入：來自前端節點安全群組的所有流量
  + 輸入：來自自我的所有流量 compute-to-compute)
  + 輸出：預設全部允許

## 步驟 2：建立啟動範本
<a name="tutorial-network-customization-v3-launch-template"></a>

建立啟動範本，定義`p6-b300.48xlarge`運算節點的網路介面組態。對於主要網路界面 （網路卡索引 0、裝置索引 0)，請使用 ENA （預設） 網路界面。對於剩餘的網路卡，請建立僅限 EFA 的介面 （網路卡索引 1-16，裝置索引 0) 和 ENA （預設） 介面 （網路卡索引 1-16，裝置索引 1)。

執行下列 AWS CLI 命令來建立啟動範本 (`lt-123456789`)：

```
aws ec2 create-launch-template \
  --region us-east-1 \
  --launch-template-name override-lt \
  --launch-template-data '{
    "NetworkInterfaces": [
      {"NetworkCardIndex":0,  "DeviceIndex":0, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":1,  "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":1,  "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":2,  "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":2,  "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":3,  "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":3,  "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":4,  "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":4,  "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":5,  "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":5,  "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":6,  "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":6,  "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":7,  "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":7,  "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":8,  "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":8,  "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":9,  "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":9,  "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":10, "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":10, "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":11, "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":11, "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":12, "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":12, "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":13, "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":13, "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":14, "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":14, "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":15, "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":15, "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":16, "DeviceIndex":0, "InterfaceType":"efa-only", "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"},
      {"NetworkCardIndex":16, "DeviceIndex":1, "Groups":["sg-abcd1234"], "SubnetId":"subnet-123456789"}
    ]
  }'
```

## 步驟 3：建立具有啟動範本覆寫的叢集
<a name="tutorial-network-customization-v3-create-cluster"></a>

建立使用 `LaunchTemplateOverrides` 參數來參考您建立的啟動範本的叢集組態。

```
Region: us-east-1
HeadNode:
  InstanceType: c5.xlarge
  Networking:
    SubnetId: subnet-abcdefghi
    AdditionalSecurityGroups:
      # Add the head node SG that allows traffic from the compute node SG
      - sg-1234abcd
...

Scheduling:
  Scheduler: slurm
  SlurmQueues:
  - Name: queue0
    Networking:
      SubnetIds:
        - subnet-123456789
    ComputeResources:
      - Name: compute-resource1
        InstanceType: p6-b300.48xlarge
        Efa:
          Enabled: false # The override replaces all network interface configuration, so this setting is ignored
        LaunchTemplateOverrides:
          LaunchTemplateId: lt-123456789
          Version: 1 # If the launch template is updated, then the new version should be specified here.
```