

AWS SDK for JavaScript v2가 지원 종료에 도달했습니다. [AWS SDK for JavaScript 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](http://docs.aws.amazon.com/ko_kr/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 모듈은 SDK for JavaScript로 아래의 Amazon EC2 클라이언트 클래스 메서드를 사용하여 인스턴스를 관리합니다
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeSecurityGroups-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeSecurityGroups-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#authorizeSecurityGroupIngress-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#authorizeSecurityGroupIngress-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#createSecurityGroup-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#createSecurityGroup-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeVpcs-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeVpcs-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#deleteSecurityGroup-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#deleteSecurityGroup-property)

Amazon EC2 보안 그룹에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [Linux 인스턴스용 Amazon EC2 Amazon 보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) 또는 **Amazon EC2 사용 설명서의 [Windows 인스턴스용 Amazon EC2 보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/using-network-security.html)을 참조하세요.

## 사전 필수 작업
<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 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 설명하려는 보안 그룹의 그룹 ID를 포함하여 파라미터로 전달할 JSON 객체를 생성합니다. 그런 다음 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 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. 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 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. 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)에서 찾을 수 있습니다.