

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 를 사용한 Amazon EC2 예제 AWS SDK for C\$1\$1
<a name="examples-ec2"></a>

Amazon Elastic Compute Cloud(Amazon EC2)는 확장 가능한 컴퓨팅 용량 즉, Amazon 데이터 센터 내 서버를 제공하는 웹 서비스로, 사용자가 소프트웨어 시스템을 빌드하고 호스팅하는 데 활용할 수 있습니다. 다음 예제를 사용하면 AWS SDK for C\$1\$1로 [Amazon EC2](https://aws.amazon.com/ec2)를 프로그래밍할 수 있습니다.

**참고**  
이 안내서에는 특정 기술을 시연하는 데 필요한 코드만 제공되며 [전체 예제 코드는 GitHub에서 확인할 수 있습니다](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp). GitHub에서 단일 소스 파일을 다운로드하거나, 리포지토리를 로컬에 복제하여 모든 예제를 가져오고 빌드하고 실행할 수 있습니다.

**Topics**
+ [Amazon EC2 인스턴스 관리](examples-ec2-instances.md)
+ [Amazon EC2에서 탄력적 IP 주소 사용](examples-ec2-elastic-ip.md)
+ [Amazon EC2에 리전 및 가용 영역 사용](examples-ec2-regions-zones.md)
+ [Amazon EC2 키 페어로 작업](examples-ec2-key-pairs.md)
+ [Amazon EC2의 보안 그룹 작업](examples-ec2-security-groups.md)

# Amazon EC2 인스턴스 관리
<a name="examples-ec2-instances"></a>

## 사전 조건
<a name="codeExamplePrereq"></a>

시작하기 전에 [AWS SDK for C\$1\$1사용 시작하기](getting-started.md)를 읽어보시기 바랍니다.

예제 코드를 다운로드하고 [코드 예제 시작하기](getting-started-code-examples.md)에 설명된 대로 솔루션을 빌드합니다.

예제를 실행하려면 코드에서 요청을 만드는 데 사용하는 사용자 프로필에 AWS (서비스 및 작업에 대한) 적절한 권한이 있어야 합니다. 자세한 내용은 자격 [AWS 증명 제공을](credentials.md) 참조하세요.

## 인스턴스 생성
<a name="create-an-instance"></a>

EC2Client의 `RunInstances` 함수를 직접적으로 호출하여 새 Amazon EC2 인스턴스를 생성하고, 사용할 [Amazon Machine Image(AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)와 [인스턴스 유형](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html)을 포함한 [RunInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_run_instances_request.html)를 해당 함수에 제공합니다.

 **포함 파일** 

```
#include <aws/core/Aws.h>
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/RunInstancesRequest.h>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::RunInstancesRequest runRequest;
    runRequest.SetImageId(amiId);
    runRequest.SetInstanceType(Aws::EC2::Model::InstanceType::t1_micro);
    runRequest.SetMinCount(1);
    runRequest.SetMaxCount(1);

    Aws::EC2::Model::RunInstancesOutcome runOutcome = ec2Client.RunInstances(
            runRequest);
    if (!runOutcome.IsSuccess()) {
        std::cerr << "Failed to launch EC2 instance " << instanceName <<
                  " based on ami " << amiId << ":" <<
                  runOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    const Aws::Vector<Aws::EC2::Model::Instance> &instances = runOutcome.GetResult().GetInstances();
    if (instances.empty()) {
        std::cerr << "Failed to launch EC2 instance " << instanceName <<
                  " based on ami " << amiId << ":" <<
                  runOutcome.GetError().GetMessage() << std::endl;
        return false;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/run_instances.cpp)를 참조하세요.

## 인스턴스 시작
<a name="start-an-instance"></a>

Amazon EC2 인스턴스를 시작하려면 EC2Client의 `StartInstances` 함수를 직접적으로 호출하고, 시작할 인스턴스의 ID가 포함된 [StartInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_start_instances_request.html)를 해당 함수에 제공합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/StartInstancesRequest.h>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::StartInstancesRequest startRequest;
    startRequest.AddInstanceIds(instanceId);
    startRequest.SetDryRun(true);

    Aws::EC2::Model::StartInstancesOutcome dryRunOutcome = ec2Client.StartInstances(startRequest);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to start instance. A dry run should trigger an error."
                << std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType() !=
               Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to start instance " << instanceId << ": "
                  << dryRunOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    startRequest.SetDryRun(false);
    Aws::EC2::Model::StartInstancesOutcome startInstancesOutcome = ec2Client.StartInstances(startRequest);

    if (!startInstancesOutcome.IsSuccess()) {
        std::cout << "Failed to start instance " << instanceId << ": " <<
                  startInstancesOutcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully started instance " << instanceId <<
                  std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/start_stop_instance.cpp)를 참조하세요.

## 인스턴스 중지
<a name="stop-an-instance"></a>

Amazon EC2 인스턴스를 중지하려면 EC2Client의 `StopInstances` 함수를 직접적으로 호출하고, 중지할 인스턴스의 ID가 포함된 [StopInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_stop_instances_request.html)를 해당 함수에 제공합니다.

 **포함 파일** 

```
#include <aws/ec2/model/StopInstancesRequest.h>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::StopInstancesRequest request;
    request.AddInstanceIds(instanceId);
    request.SetDryRun(true);

    Aws::EC2::Model::StopInstancesOutcome dryRunOutcome = ec2Client.StopInstances(request);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to stop instance. A dry run should trigger an error."
                << std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType() !=
               Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to stop instance " << instanceId << ": "
                  << dryRunOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    request.SetDryRun(false);
    Aws::EC2::Model::StopInstancesOutcome outcome = ec2Client.StopInstances(request);
    if (!outcome.IsSuccess()) {
        std::cout << "Failed to stop instance " << instanceId << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully stopped instance " << instanceId <<
                  std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/start_stop_instance.cpp)를 참조하세요.

## 인스턴스 재부팅
<a name="reboot-an-instance"></a>

Amazon EC2 인스턴스를 재부팅하려면 EC2Client의 `RebootInstances` 함수를 직접적으로 호출하고, 재부팅할 인스턴스의 ID가 포함된 [RebootInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_reboot_instances_request.html)를 해당 함수에 제공합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/RebootInstancesRequest.h>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::RebootInstancesRequest request;
    request.AddInstanceIds(instanceId);
    request.SetDryRun(true);

    Aws::EC2::Model::RebootInstancesOutcome dry_run_outcome = ec2Client.RebootInstances(request);
    if (dry_run_outcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to reboot on instance. A dry run should trigger an error."
                <<
                std::endl;
        return false;
    } else if (dry_run_outcome.GetError().GetErrorType()
               != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to reboot instance " << instanceId << ": "
                  << dry_run_outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    request.SetDryRun(false);
    Aws::EC2::Model::RebootInstancesOutcome outcome = ec2Client.RebootInstances(request);
    if (!outcome.IsSuccess()) {
        std::cout << "Failed to reboot instance " << instanceId << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully rebooted instance " << instanceId <<
                  std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/reboot_instance.cpp)를 참조하세요.

## 인스턴스 설명
<a name="describe-instances"></a>

인스턴스를 나열하려면 [DescribeInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_instances_request.html)를 생성하고 EC2Client의 `DescribeInstances` 함수를 직접적으로 호출합니다. 그러면 AWS 계정 및에 대한 Amazon EC2 인스턴스를 나열하는 데 사용할 수 있는 [DescribeInstancesResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_instances_response.html) 객체가 반환됩니다 AWS 리전.

인스턴스는 *예약*별로 그룹화됩니다. 각 예약은 인스턴스를 시작하는 `StartInstances` 호출에 해당합니다. 인스턴스를 나열하려면 먼저 `DescribeInstancesResponse` 클래스의 `GetReservations` 함수를 직접적으로 호출한 다음 반환된 각 Reservation 객체에서 `getInstances`를 직접적으로 호출해야 합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeInstancesRequest.h>
#include <aws/ec2/model/DescribeInstancesResponse.h>
#include <iomanip>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeInstancesRequest request;
    bool header = false;
    bool done = false;
    while (!done) {
        Aws::EC2::Model::DescribeInstancesOutcome outcome = ec2Client.DescribeInstances(request);
        if (outcome.IsSuccess()) {
            if (!header) {
                std::cout << std::left <<
                          std::setw(48) << "Name" <<
                          std::setw(20) << "ID" <<
                          std::setw(25) << "Ami" <<
                          std::setw(15) << "Type" <<
                          std::setw(15) << "State" <<
                          std::setw(15) << "Monitoring" << std::endl;
                header = true;
            }

            const std::vector<Aws::EC2::Model::Reservation> &reservations =
                    outcome.GetResult().GetReservations();

            for (const auto &reservation: reservations) {
                const std::vector<Aws::EC2::Model::Instance> &instances =
                        reservation.GetInstances();
                for (const auto &instance: instances) {
                    Aws::String instanceStateString =
                            Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
                                    instance.GetState().GetName());

                    Aws::String typeString =
                            Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
                                    instance.GetInstanceType());

                    Aws::String monitorString =
                            Aws::EC2::Model::MonitoringStateMapper::GetNameForMonitoringState(
                                    instance.GetMonitoring().GetState());
                    Aws::String name = "Unknown";

                    const std::vector<Aws::EC2::Model::Tag> &tags = instance.GetTags();
                    auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
                                                 [](const Aws::EC2::Model::Tag &tag) {
                                                     return tag.GetKey() == "Name";
                                                 });
                    if (nameIter != tags.cend()) {
                        name = nameIter->GetValue();
                    }
                    std::cout <<
                              std::setw(48) << name <<
                              std::setw(20) << instance.GetInstanceId() <<
                              std::setw(25) << instance.GetImageId() <<
                              std::setw(15) << typeString <<
                              std::setw(15) << instanceStateString <<
                              std::setw(15) << monitorString << std::endl;
                }
            }

            if (!outcome.GetResult().GetNextToken().empty()) {
                request.SetNextToken(outcome.GetResult().GetNextToken());
            } else {
                done = true;
            }
        } else {
            std::cerr << "Failed to describe EC2 instances:" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }
```

결과는 페이지 단위로 제공됩니다. 결과 객체의 `GetNextToken` 함수에서 반환된 값을 원래 요청 객체의 `SetNextToken` 함수에 전달한 후 동일한 요청 객체를 다음 `DescribeInstances` 호출에 사용하면 추가 결과를 얻을 수 있습니다.

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_instances.cpp)를 참조하세요.

## 인스턴스 모니터링 활성화
<a name="enable-instance-monitoring"></a>

CPU와 네트워크 사용률, 사용 가능한 메모리, 남은 디스크 공간 등 Amazon EC2 인스턴스의 다양한 측면을 모니터링할 수 있습니다. 인스턴스 모니터링에 대한 자세한 내용은 Amazon EC2 사용 설명서에서 [Amazon EC2 모니터링](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring_ec2.html)을 참조하세요.

인스턴스 모니터링을 시작하려면 모니터링할 인스턴스의 ID로 [MonitorInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_monitor_instances_request.html)를 생성한 후 EC2Client의 `MonitorInstances` 함수에 전달합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/MonitorInstancesRequest.h>
#include <aws/ec2/model/UnmonitorInstancesRequest.h>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::MonitorInstancesRequest request;
    request.AddInstanceIds(instanceId);
    request.SetDryRun(true);

    Aws::EC2::Model::MonitorInstancesOutcome dryRunOutcome = ec2Client.MonitorInstances(request);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to enable monitoring on instance. A dry run should trigger an error."
                <<
                std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType()
               != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cerr << "Failed dry run to enable monitoring on instance " <<
                  instanceId << ": " << dryRunOutcome.GetError().GetMessage() <<
                  std::endl;
        return false;
    }

    request.SetDryRun(false);
    Aws::EC2::Model::MonitorInstancesOutcome monitorInstancesOutcome = ec2Client.MonitorInstances(request);
    if (!monitorInstancesOutcome.IsSuccess()) {
        std::cerr << "Failed to enable monitoring on instance " <<
                  instanceId << ": " <<
                  monitorInstancesOutcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully enabled monitoring on instance " <<
                  instanceId << std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/monitor_instance.cpp)를 참조하세요.

## 인스턴스 모니터링 비활성화
<a name="disable-instance-monitoring"></a>

인스턴스 모니터링을 중지하려면 모니터링을 중지할 인스턴스의 ID로 [UnmonitorInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_unmonitor_instances_request.html)를 생성한 후 EC2Client의 `UnmonitorInstances` 함수에 전달합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/MonitorInstancesRequest.h>
#include <aws/ec2/model/UnmonitorInstancesRequest.h>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::UnmonitorInstancesRequest unrequest;
    unrequest.AddInstanceIds(instanceId);
    unrequest.SetDryRun(true);

    Aws::EC2::Model::UnmonitorInstancesOutcome dryRunOutcome = ec2Client.UnmonitorInstances(unrequest);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to disable monitoring on instance. A dry run should trigger an error."
                <<
                std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType() !=
               Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to disable monitoring on instance " <<
                  instanceId << ": " << dryRunOutcome.GetError().GetMessage() <<
                  std::endl;
        return false;
    }

    unrequest.SetDryRun(false);
    Aws::EC2::Model::UnmonitorInstancesOutcome unmonitorInstancesOutcome = ec2Client.UnmonitorInstances(unrequest);
    if (!unmonitorInstancesOutcome.IsSuccess()) {
        std::cout << "Failed to disable monitoring on instance " << instanceId
                  << ": " << unmonitorInstancesOutcome.GetError().GetMessage() <<
                  std::endl;
    } else {
        std::cout << "Successfully disable monitoring on instance " <<
                  instanceId << std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/monitor_instance.cpp)를 참조하세요.

## 추가 정보
<a name="more-information"></a>
+  Amazon EC2 API 참조의 [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html)
+  Amazon EC2 API 참조의 [DescribeInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html)
+  Amazon EC2 API 참조의 [StartInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_StartInstances.html)
+  Amazon EC2 API 참조의 [StopInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_StopInstances.html)
+  Amazon EC2 API 참조의 [RebootInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RebootInstances.html)
+  Amazon EC2 API 참조의 [DescribeInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html)
+  Amazon EC2 API 참조의 [MonitorInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_MonitorInstances.html)
+  Amazon EC2 API 참조의 [UnmonitorInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_UnmonitorInstances.html)

# Amazon EC2에서 탄력적 IP 주소 사용
<a name="examples-ec2-elastic-ip"></a>

## 사전 조건
<a name="codeExamplePrereq"></a>

시작하기 전에 [AWS SDK for C\$1\$1사용 시작하기](getting-started.md)를 읽어보시기 바랍니다.

예제 코드를 다운로드하고 [코드 예제 시작하기](getting-started-code-examples.md)에 설명된 대로 솔루션을 빌드합니다.

예제를 실행하려면 코드에서 요청을 만드는 데 사용하는 사용자 프로필에 AWS (서비스 및 작업에 대한) 적절한 권한이 있어야 합니다. 자세한 내용은 자격 [AWS 증명 제공을](credentials.md) 참조하세요.

## 탄력적 IP 주소 할당
<a name="allocate-an-elastic-ip-address"></a>

탄력적 IP 주소를 사용하려면 먼저 계정에 주소를 할당한 후 인스턴스 또는 네트워크 인터페이스와 연결합니다.

탄력적 IP 주소를 할당하려면 EC2Client의 `AllocateAddress` 함수를 네트워크 유형(클래식 EC2 또는 VPC)이 포함된 [AllocateAddressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_allocate_address_request.html) 객체와 함께 직접적으로 호출합니다.

**주의**  
EC2-Classic은 2022년 8월 15일에 사용 중지될 예정입니다. EC2-Classic에서 VPC로 마이그레이션하는 것이 좋습니다. 자세한 내용은 [Linux 인스턴스용 Amazon EC2 사용 설명서](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) 또는 [Windows 인스턴스용 Amazon EC2 사용 설명서](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/vpc-migrate.html)의 **EC2-Classic에서 VPC로 마이그레이션**을 참조하세요. 또는 블로그 게시물[EC2-Classic 네트워킹은 사용 중지 중입니다 - 준비 방법은 다음과 같습니다](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/)를 참조하세요.

응답 객체의 [AllocateAddressResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_allocate_address_response.html) 클래스에는 할당 ID가 포함되어 있는데, 이 할당 ID를 사용하여 주소를 인스턴스와 연결할 수 있습니다. 할당 ID와 인스턴스 ID를 EC2Client의 `AssociateAddress` 함수에 [AssociateAddressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_associate_address_request.html)로 전달하면 됩니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/AllocateAddressRequest.h>
#include <aws/ec2/model/AssociateAddressRequest.h>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::AllocateAddressRequest request;
    request.SetDomain(Aws::EC2::Model::DomainType::vpc);

    const Aws::EC2::Model::AllocateAddressOutcome outcome =
            ec2Client.AllocateAddress(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to allocate Elastic IP address:" <<
                  outcome.GetError().GetMessage() << std::endl;
        return false;
    }
    const Aws::EC2::Model::AllocateAddressResponse &response = outcome.GetResult();
    allocationID = response.GetAllocationId();
    publicIPAddress = response.GetPublicIp();


    Aws::EC2::Model::AssociateAddressRequest associate_request;
    associate_request.SetInstanceId(instanceId);
    associate_request.SetAllocationId(allocationID);

    const Aws::EC2::Model::AssociateAddressOutcome associate_outcome =
            ec2Client.AssociateAddress(associate_request);
    if (!associate_outcome.IsSuccess()) {
        std::cerr << "Failed to associate Elastic IP address " << allocationID
                  << " with instance " << instanceId << ":" <<
                  associate_outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    std::cout << "Successfully associated Elastic IP address " << allocationID
              << " with instance " << instanceId << std::endl;
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/allocate_address.cpp)를 참조하세요.

## 탄력적 IP 주소 설명
<a name="describe-elastic-ip-addresses"></a>

계정에 지정된 탄력적 IP 주소를 나열하려면 EC2Client의 `DescribeAddresses` 함수를 직접적으로 호출합니다. 반환되는 결과 객체에는 [DescribeAddressesResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_addresses_response.html)가 포함되어 있는데, 이를 사용하여 계정의 탄력적 IP 주소를 나타내는 [Address](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_address.html) 객체 목록을 얻을 수 있습니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeAddressesRequest.h>
#include <aws/ec2/model/DescribeAddressesResponse.h>
#include <iomanip>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeAddressesRequest request;
    Aws::EC2::Model::DescribeAddressesOutcome outcome = ec2Client.DescribeAddresses(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left << std::setw(20) << "InstanceId" <<
                  std::setw(15) << "Public IP" << std::setw(10) << "Domain" <<
                  std::setw(30) << "Allocation ID" << std::setw(25) <<
                  "NIC ID" << std::endl;

        const Aws::Vector<Aws::EC2::Model::Address> &addresses = outcome.GetResult().GetAddresses();
        for (const auto &address: addresses) {
            Aws::String domainString =
                    Aws::EC2::Model::DomainTypeMapper::GetNameForDomainType(
                            address.GetDomain());

            std::cout << std::left << std::setw(20) <<
                      address.GetInstanceId() << std::setw(15) <<
                      address.GetPublicIp() << std::setw(10) << domainString <<
                      std::setw(30) << address.GetAllocationId() << std::setw(25)
                      << address.GetNetworkInterfaceId() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe Elastic IP addresses:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_addresses.cpp)를 참조하세요.

## 탄력적 IP 주소 릴리스
<a name="release-an-elastic-ip-address"></a>

탄력적 IP 주소를 릴리스하려면 EC2Client의 `ReleaseAddress` 함수를 직접적으로 호출하고 릴리스할 탄력적 IP 주소의 할당 ID가 포함된 [ReleaseAddressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_release_address_request.html)를 해당 함수에 전달합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/ReleaseAddressRequest.h>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2(clientConfiguration);

    Aws::EC2::Model::ReleaseAddressRequest request;
    request.SetAllocationId(allocationID);

    Aws::EC2::Model::ReleaseAddressOutcome outcome = ec2.ReleaseAddress(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to release Elastic IP address " <<
                  allocationID << ":" << outcome.GetError().GetMessage() <<
                  std::endl;
    } else {
        std::cout << "Successfully released Elastic IP address " <<
                  allocationID << std::endl;
    }
```

탄력적 IP 주소를 릴리스하면 AWS IP 주소 풀로 릴리스되고 나중에 사용하지 못할 수 있습니다. 해당 주소와 통신하는 모든 서버 또는 장치와 DNS 레코드를 업데이트해야 합니다. 이미 릴리스한 탄력적 IP 주소를 릴리스하려고 하면 주소가 이미 다른 AWS 계정에 할당된 경우 *AuthFailure* 오류가 발생합니다.

기본 VPC를 사용하는 경우 탄력적 IP 주소를 릴리스하면 해당 주소가 연결된 모든 인스턴스와의 연결이 자동으로 해제됩니다. 탄력적 IP 주소를 릴리스하지 않고 연결을 해제하려면 EC2Client의 `DisassociateAddress` 함수를 사용합니다.

기본이 아닌 VPC를 사용하는 경우, 릴리스하기 전에 *반드시* `DisassociateAddress`를 사용해 탄력적 IP 주소를 연결 해제합니다. 그렇지 않으면 Amazon EC2에서 오류(*InvalidIPAddress.InUse*)를 반환합니다.

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/release_address.cpp)를 참조하세요.

## 추가 정보
<a name="more-information"></a>
+  Amazon EC2 사용 설명서의 [탄력적 IP 주소](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)
+  Amazon EC2 API 참조의 [AllocateAddress](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AllocateAddress.html)
+  Amazon EC2 API 참조의 [DescribeAddresses](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAddresses.html)
+  Amazon EC2 API 참조의 [ReleaseAddress](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ReleaseAddress.html)

# Amazon EC2에 리전 및 가용 영역 사용
<a name="examples-ec2-regions-zones"></a>

## 사전 조건
<a name="codeExamplePrereq"></a>

시작하기 전에 [AWS SDK for C\$1\$1사용 시작하기](getting-started.md)를 읽어보시기 바랍니다.

예제 코드를 다운로드하고 [코드 예제 시작하기](getting-started-code-examples.md)에 설명된 대로 솔루션을 빌드합니다.

예제를 실행하려면 코드에서 요청을 만드는 데 사용하는 사용자 프로필에 AWS (서비스 및 작업에 대한) 적절한 권한이 있어야 합니다. 자세한 내용은 자격 [AWS 증명 제공을](credentials.md) 참조하세요.

## 리전 설명
<a name="describe-regions"></a>

사용 AWS 리전 가능한를 나열하려면 [DescribeRegionsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_regions_request.html)를 사용하여 EC2Client의 `DescribeRegions` 함수를 AWS 계정호출합니다.

결과 객체에 [DescribeRegionsResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_regions_response.html)가 표시됩니다. `GetRegions` 함수를 직접적으로 호출하면 각 리전을 나타내는 [Region](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_region.html) 객체 목록을 확인할 수 있습니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeRegionsRequest.h>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::DescribeRegionsRequest request;
    Aws::EC2::Model::DescribeRegionsOutcome outcome = ec2Client.DescribeRegions(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left <<
                  std::setw(32) << "RegionName" <<
                  std::setw(64) << "Endpoint" << std::endl;

        const auto &regions = outcome.GetResult().GetRegions();
        for (const auto &region: regions) {
            std::cout << std::left <<
                      std::setw(32) << region.GetRegionName() <<
                      std::setw(64) << region.GetEndpoint() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe regions:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_regions_and_zones.cpp)를 참조하세요.

## 가용 영역 설명
<a name="describe-availability-zones"></a>

계정에서 사용 가능한 가용 영역을 나열하려면 EC2Client의 `DescribeAvailabilityZones` 함수를 [DescribeAvailabilityZonesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_availability_zones_request.html)와 함께 직접적으로 호출합니다.

결과 객체에 [DescribeAvailabilityZonesResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_availability_zones_response.html)가 표시됩니다. `GetAvailabilityZones` 함수를 직접적으로 호출하면 각 가용 영역을 나타내는 [AvailabilityZone](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_availability_zone.html) 객체 목록을 확인할 수 있습니다.

 **포함 파일** 

```
#include <aws/ec2/model/DescribeAvailabilityZonesRequest.h>
```

 **코드** 

```
    Aws::EC2::Model::DescribeAvailabilityZonesRequest request;
    Aws::EC2::Model::DescribeAvailabilityZonesOutcome outcome = ec2Client.DescribeAvailabilityZones(request);

    if (outcome.IsSuccess()) {
        std::cout << std::left <<
                  std::setw(32) << "ZoneName" <<
                  std::setw(20) << "State" <<
                  std::setw(32) << "Region" << std::endl;

        const auto &zones =
                outcome.GetResult().GetAvailabilityZones();

        for (const auto &zone: zones) {
            Aws::String stateString =
                    Aws::EC2::Model::AvailabilityZoneStateMapper::GetNameForAvailabilityZoneState(
                            zone.GetState());
            std::cout << std::left <<
                      std::setw(32) << zone.GetZoneName() <<
                      std::setw(20) << stateString <<
                      std::setw(32) << zone.GetRegionName() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe availability zones:" <<
                  outcome.GetError().GetMessage() << std::endl;

    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_regions_and_zones.cpp)를 참조하세요.

## 추가 정보
<a name="more-information"></a>
+  Amazon EC2 사용 설명서의 [리전 및 가용 영역](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)
+  Amazon EC2 API 참조의 [DescribeRegions](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeRegions.html)
+  Amazon EC2 API 참조의 [DescribeAvailabilityZones](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html)

# Amazon EC2 키 페어로 작업
<a name="examples-ec2-key-pairs"></a>

## 사전 조건
<a name="codeExamplePrereq"></a>

시작하기 전에 [AWS SDK for C\$1\$1사용 시작하기](getting-started.md)를 읽어보시기 바랍니다.

예제 코드를 다운로드하고 [코드 예제 시작하기](getting-started-code-examples.md)에 설명된 대로 솔루션을 빌드합니다.

예제를 실행하려면 코드에서 요청을 만드는 데 사용하는 사용자 프로필에 AWS (서비스 및 작업에 대한) 적절한 권한이 있어야 합니다. 자세한 내용은 자격 [AWS 증명 제공을](credentials.md) 참조하세요.

## 키 페어 생성
<a name="create-a-key-pair"></a>

키 페어를 생성하려면 EC2Client의 `CreateKeyPair` 함수를 키 이름이 포함된 [CreateKeyPairRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_create_key_pair_request.html)와 함께 직접적으로 호출합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/CreateKeyPairRequest.h>
#include <iostream>
#include <fstream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::CreateKeyPairRequest request;
    request.SetKeyName(keyPairName);

    Aws::EC2::Model::CreateKeyPairOutcome outcome = ec2Client.CreateKeyPair(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to create key pair - "  << keyPairName << ". " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully created key pair named " <<
                  keyPairName << std::endl;
        if (!keyFilePath.empty()) {
            std::ofstream keyFile(keyFilePath.c_str());
            keyFile << outcome.GetResult().GetKeyMaterial();
            keyFile.close();
            std::cout << "Keys written to the file " <<
                      keyFilePath << std::endl;
        }

    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/create_key_pair.cpp)를 참조하세요.

## 키 페어 설명
<a name="describe-key-pairs"></a>

키 페어를 나열하거나 키 페어에 대한 정보를 가져오려면 EC2Client의 `DescribeKeyPairs` 함수를 [DescribeKeyPairsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_key_pairs_request.html)와 함께 직접적으로 호출합니다.

[DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_key_pairs_response.html)를 수신하게 되며 이 객체의 `GetKeyPairs` 함수를 직접적으로 호출하여 키 페어 목록에 액세스할 수 있습니다. 그러면 [KeyPairInfo](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_key_pair_info.html) 객체 목록이 반환됩니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeKeyPairsRequest.h>
#include <aws/ec2/model/DescribeKeyPairsResponse.h>
#include <iomanip>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeKeyPairsRequest request;

    Aws::EC2::Model::DescribeKeyPairsOutcome outcome = ec2Client.DescribeKeyPairs(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left <<
                  std::setw(32) << "Name" <<
                  std::setw(64) << "Fingerprint" << std::endl;

        const std::vector<Aws::EC2::Model::KeyPairInfo> &key_pairs =
                outcome.GetResult().GetKeyPairs();
        for (const auto &key_pair: key_pairs) {
            std::cout << std::left <<
                      std::setw(32) << key_pair.GetKeyName() <<
                      std::setw(64) << key_pair.GetKeyFingerprint() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe key pairs:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_key_pairs.cpp)를 참조하세요.

## 키 페어 삭제
<a name="delete-a-key-pair"></a>

키 페어를 삭제하려면 EC2Client의 `DeleteKeyPair` 함수를 직접적으로 호출하고 삭제할 키 페어 이름이 포함된 [DeleteKeyPairRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_delete_key_pair_request.html)를 해당 함수에 전달합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DeleteKeyPairRequest.h>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DeleteKeyPairRequest request;

    request.SetKeyName(keyPairName);
    const Aws::EC2::Model::DeleteKeyPairOutcome outcome = ec2Client.DeleteKeyPair(
            request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to delete key pair " << keyPairName <<
                  ":" << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted key pair named " << keyPairName <<
                  std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/delete_key_pair.cpp)를 참조하세요.

## 추가 정보
<a name="more-information"></a>
+  Amazon EC2 사용 설명서의 [Amazon EC2 키 페어](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)
+  Amazon EC2 API 참조의 [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html)
+  Amazon EC2 API 참조의 [DescribeKeyPairs](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeKeyPairs.html)
+  Amazon EC2 API 참조의 [DeleteKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteKeyPair.html)

# Amazon EC2의 보안 그룹 작업
<a name="examples-ec2-security-groups"></a>

## 사전 조건
<a name="codeExamplePrereq"></a>

시작하기 전에 [AWS SDK for C\$1\$1사용 시작하기](getting-started.md)를 읽어보시기 바랍니다.

예제 코드를 다운로드하고 [코드 예제 시작하기](getting-started-code-examples.md)에 설명된 대로 솔루션을 빌드합니다.

예제를 실행하려면 코드에서 요청을 만드는 데 사용하는 사용자 프로필에 AWS (서비스 및 작업에 대한) 적절한 권한이 있어야 합니다. 자세한 내용은 자격 [AWS 증명 제공을](credentials.md) 참조하세요.

## 보안 그룹 생성
<a name="create-a-security-group"></a>

보안 그룹을 생성하려면 EC2Client의 `CreateSecurityGroup` 함수를 키 이름이 포함된 [CreateSecurityGroupRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_create_security_group_request.html)와 함께 직접적으로 호출합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/CreateSecurityGroupRequest.h>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::CreateSecurityGroupRequest request;

    request.SetGroupName(groupName);
    request.SetDescription(description);
    request.SetVpcId(vpcID);

    const Aws::EC2::Model::CreateSecurityGroupOutcome outcome =
            ec2Client.CreateSecurityGroup(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to create security group:" <<
                  outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    std::cout << "Successfully created security group named " << groupName <<
              std::endl;
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/create_security_group.cpp)를 참조하세요.

## 보안 그룹 구성
<a name="configure-a-security-group"></a>

보안 그룹은 Amazon EC2 인스턴스에 대한 인바운드(수신) 및 아웃바운드(송신) 트래픽을 모두 제어할 수 있습니다.

보안 그룹에 수신 규칙을 추가하려면 EC2Client의 `AuthorizeSecurityGroupIngress` 함수를 사용합니다. 이때 [AuthorizeSecurityGroupIngressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_authorize_security_group_ingress_request.html) 객체 내에서 보안 그룹의 이름과 보안 그룹에 할당하려는 액세스 규칙([IpPermission](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_ip_permission.html))을 제공해야 합니다. 다음 예제에서는 IP 권한을 보안 그룹에 추가하는 방법을 보여줍니다.

 **포함 파일** 

```
#include <aws/ec2/model/AuthorizeSecurityGroupIngressRequest.h>
```

 **코드** 

```
    Aws::EC2::Model::AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest;
    authorizeSecurityGroupIngressRequest.SetGroupId(groupID);
```

```
    Aws::String ingressIPRange = "203.0.113.0/24";  // Configure this for your allowed IP range.
    Aws::EC2::Model::IpRange ip_range;
    ip_range.SetCidrIp(ingressIPRange);

    Aws::EC2::Model::IpPermission permission1;
    permission1.SetIpProtocol("tcp");
    permission1.SetToPort(80);
    permission1.SetFromPort(80);
    permission1.AddIpRanges(ip_range);

    authorize_request.AddIpPermissions(permission1);

    Aws::EC2::Model::IpPermission permission2;
    permission2.SetIpProtocol("tcp");
    permission2.SetToPort(22);
    permission2.SetFromPort(22);
    permission2.AddIpRanges(ip_range);

    authorize_request.AddIpPermissions(permission2);
```

```
    Aws::EC2::Model::AuthorizeSecurityGroupIngressOutcome authorizeSecurityGroupIngressOutcome =
            ec2Client.AuthorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    if (authorizeSecurityGroupIngressOutcome.IsSuccess()) {
        std::cout << "Successfully authorized security group ingress." << std::endl;
    } else {
        std::cerr << "Error authorizing security group ingress: "
                  << authorizeSecurityGroupIngressOutcome.GetError().GetMessage() << std::endl;
    }
```

보안 그룹에 송신 규칙을 추가하려면 [AuthorizeSecurityGroupEgressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_authorize_security_group_egress_request.html)의 유사한 데이터를 EC2Client의 `AuthorizeSecurityGroupEgress` 함수에 제공합니다.

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/create_security_group.cpp)를 참조하세요.

## 보안 그룹 설명
<a name="describe-security-groups"></a>

보안 그룹을 설명하거나 보안 그룹에 대한 정보를 가져오려면 EC2Client의 `DescribeSecurityGroups` 함수를 [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_security_groups_request.html)와 함께 직접적으로 호출합니다.

결과 객체에서 [DescribeSecurityGroupsResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_security_groups_response.html)를 수신하게 되며, 이 객체의 `GetSecurityGroups` 함수를 직접적으로 호출하여 보안 그룹 목록에 액세스할 수 있습니다. 그러면 [SecurityGroup](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_security_group.html) 객체 목록이 반환됩니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeSecurityGroupsRequest.h>
#include <aws/ec2/model/DescribeSecurityGroupsResponse.h>
#include <iomanip>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeSecurityGroupsRequest request;

    if (!groupID.empty()) {
        request.AddGroupIds(groupID);
    }

    Aws::String nextToken;
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::EC2::Model::DescribeSecurityGroupsOutcome outcome = ec2Client.DescribeSecurityGroups(request);
        if (outcome.IsSuccess()) {
            std::cout << std::left <<
                      std::setw(32) << "Name" <<
                      std::setw(30) << "GroupId" <<
                      std::setw(30) << "VpcId" <<
                      std::setw(64) << "Description" << std::endl;

            const std::vector<Aws::EC2::Model::SecurityGroup> &securityGroups =
                    outcome.GetResult().GetSecurityGroups();

            for (const auto &securityGroup: securityGroups) {
                std::cout << std::left <<
                          std::setw(32) << securityGroup.GetGroupName() <<
                          std::setw(30) << securityGroup.GetGroupId() <<
                          std::setw(30) << securityGroup.GetVpcId() <<
                          std::setw(64) << securityGroup.GetDescription() <<
                          std::endl;
            }
        } else {
            std::cerr << "Failed to describe security groups:" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        nextToken = outcome.GetResult().GetNextToken();
    } while (!nextToken.empty());
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_security_groups.cpp)를 참조하세요.

## 보안 그룹 삭제
<a name="delete-a-security-group"></a>

보안 그룹을 삭제하려면 EC2Client의 `DeleteSecurityGroup` 함수를 직접적으로 호출합니다. 이때 삭제할 보안 그룹의 ID가 포함된 [DeleteSecurityGroupRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_delete_security_group_request.html)를 전달합니다.

 **포함 파일** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DeleteSecurityGroupRequest.h>
#include <iostream>
```

 **코드** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DeleteSecurityGroupRequest request;

    request.SetGroupId(securityGroupID);
    Aws::EC2::Model::DeleteSecurityGroupOutcome outcome = ec2Client.DeleteSecurityGroup(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to delete security group " << securityGroupID <<
                  ":" << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted security group " << securityGroupID <<
                  std::endl;
    }
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/delete_security_group.cpp)를 참조하세요.

## 추가 정보
<a name="more-information"></a>
+  Amazon EC2 사용 설명서의 [Amazon EC2 보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)
+  Amazon EC2 사용 설명서의 [Linux 인스턴스의 인바운드 트래픽 권한 부여](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html)
+  Amazon EC2 API 참조의 [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html)
+  Amazon EC2 API 참조의 [DescribeSecurityGroups](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSecurityGroups.html)
+  Amazon EC2 API 참조의 [DeleteSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteSecurityGroup.html)
+  Amazon EC2 API 참조의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AuthorizeSecurityGroupIngress.html)