

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

# 使用 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"
        }
    ]
}
```

------