

 適用於 JavaScript 的 AWS SDK v2 已end-of-support。我們建議您遷移至 [適用於 JavaScript 的 AWS SDK v3](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/)。如需如何遷移的其他詳細資訊和資訊，請參閱此[公告](https://aws.amazon.com/blogs/developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/)。

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

# 在 Amazon EC2 中使用安全群組
<a name="ec2-example-security-groups"></a>

![JavaScript code example that applies to Node.js execution](https://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**這個 Node.js 程式碼範例會說明：**
+ 如何擷取安全群組的相關資訊。
+ 如何建立安全群組以存取 Amazon EC2 執行個體。
+ 如何刪除現有的安全群組。

## 使用案例
<a name="ec2-example-security-groups-scenario"></a>

Amazon EC2 安全群組可做為虛擬防火牆，控制一或多個執行個體的流量。您在各個安全群組新增規則，允許流量往返於建立關聯的執行個體。您可以隨時修改安全群組的規則；系統會自動將新規則套用至與安全群組相關聯的所有執行個體。

在此範例中，您會使用一系列 Node.js 模組來執行數個涉及安全群組的 Amazon EC2 操作。Node.js 模組使用適用於 JavaScript 的 SDK，透過使用 Amazon EC2 用戶端類別的下列方法管理執行個體：
+ [`describeSecurityGroups`](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeSecurityGroups-property)
+ [`authorizeSecurityGroupIngress`](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#authorizeSecurityGroupIngress-property)
+ [`createSecurityGroup`](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#createSecurityGroup-property)
+ [`describeVpcs`](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeVpcs-property)
+ [`deleteSecurityGroup`](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#deleteSecurityGroup-property)

如需 Amazon EC2 安全群組的詳細資訊，請參閱[《Amazon EC2 使用者指南》中的適用於 Linux 執行個體的](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) *Amazon EC2 * Amazon 安全群組，或《[Amazon EC2 使用者指南》中的適用於 Windows 執行個體的 Amazon EC2 安全群組](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/using-network-security.html)。 *Amazon EC2 *

## 先決條件任務
<a name="ec2-example-security-groups-prerequisites"></a>

若要設定和執行此範例，請先完成這些任務：
+ 安裝 Node.js。如需安裝 Node.js 的詳細資訊，請參閱 [Node.js 網站](https://nodejs.org)。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 [從共用登入資料檔案中在 Node.js 中載入登入資料](loading-node-credentials-shared.md)。

## 說明您的安全群組
<a name="ec2-example-security-groups-describing"></a>

以檔名 `ec2_describesecuritygroups.js` 建立一個 Node.js 模組。請務必依前述的內容來設定軟體開發套件。若要存取 Amazon EC2，請建立 `AWS.EC2` 服務物件。建立要以參數的形式傳遞的 JSON 物件，包含您要描述的安全群組之群組 ID。然後呼叫 Amazon EC2 服務物件的 `describeSecurityGroups`方法。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  GroupIds: ["SECURITY_GROUP_ID"],
};

// Retrieve security group descriptions
ec2.describeSecurityGroups(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", JSON.stringify(data.SecurityGroups));
  }
});
```

若要執行範例，請在命令列中輸入以下內容。

```
node ec2_describesecuritygroups.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_describesecuritygroups.js)找到這個範本程式碼。

## 建立安全群組與規則
<a name="ec2-example-security-groups-creating"></a>

以檔名 `ec2_createsecuritygroup.js` 建立一個 Node.js 模組。請務必依前述的內容來設定軟體開發套件。若要存取 Amazon EC2，請建立 `AWS.EC2` 服務物件。為指定安全群組名稱、描述和 VPC 的 ID 的參數建立 JSON 物件。將參數傳遞至 `createSecurityGroup` 方法。

在順利建立安全群組後，您可以定義規則來允許傳入流量。為指定 Amazon EC2 執行個體將接收流量之 IP 通訊協定和傳入連接埠的參數建立 JSON 物件。將參數傳遞至 `authorizeSecurityGroupIngress` 方法。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Load credentials and set region from JSON file
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

// Variable to hold a ID of a VPC
var vpc = null;

// Retrieve the ID of a VPC
ec2.describeVpcs(function (err, data) {
  if (err) {
    console.log("Cannot retrieve a VPC", err);
  } else {
    vpc = data.Vpcs[0].VpcId;
    var paramsSecurityGroup = {
      Description: "DESCRIPTION",
      GroupName: "SECURITY_GROUP_NAME",
      VpcId: vpc,
    };
    // Create the instance
    ec2.createSecurityGroup(paramsSecurityGroup, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        var SecurityGroupId = data.GroupId;
        console.log("Success", SecurityGroupId);
        var paramsIngress = {
          GroupId: "SECURITY_GROUP_ID",
          IpPermissions: [
            {
              IpProtocol: "tcp",
              FromPort: 80,
              ToPort: 80,
              IpRanges: [{ CidrIp: "0.0.0.0/0" }],
            },
            {
              IpProtocol: "tcp",
              FromPort: 22,
              ToPort: 22,
              IpRanges: [{ CidrIp: "0.0.0.0/0" }],
            },
          ],
        };
        ec2.authorizeSecurityGroupIngress(paramsIngress, function (err, data) {
          if (err) {
            console.log("Error", err);
          } else {
            console.log("Ingress Successfully Set", data);
          }
        });
      }
    });
  }
});
```

若要執行範例，請在命令列中輸入以下內容。

```
node ec2_createsecuritygroup.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_createsecuritygroup.js)找到這個範本程式碼。

## 刪除安全群組
<a name="ec2-example-security-groups-deleting"></a>

以檔名 `ec2_deletesecuritygroup.js` 建立一個 Node.js 模組。請務必依前述的內容來設定軟體開發套件。若要存取 Amazon EC2，請建立 `AWS.EC2` 服務物件。建立 JSON 參數來指定要刪除的安全群組名稱。然後呼叫 `deleteSecurityGroup` 方法。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  GroupId: "SECURITY_GROUP_ID",
};

// Delete the security group
ec2.deleteSecurityGroup(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Security Group Deleted");
  }
});
```

若要執行範例，請在命令列中輸入以下內容。

```
node ec2_deletesecuritygroup.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_deletesecuritygroup.js)找到這個範本程式碼。