

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# を使用した 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 における Elastic 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>

新しい EC2 インスタンスを作成するには、EC2Client の `RunInstances` 関数の呼び出しで、使用する [Amazon マシンイメージ (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 における Elastic 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)」を参照してください。

## Elastic IP アドレスを割り当てる
<a name="allocate-an-elastic-ip-address"></a>

Elastic IP アドレスを使用するにはまずアカウントに 1 つ割り当ててから、それをインスタンスまたはネットワークインターフェイスに関連付けます。

Elastic IP アドレスを割り当てるには、ネットワークタイプ (Classic 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) オブジェクトを使用して EC2Client の `AllocateAddress` 関数を呼び出します。

**警告**  
2022 年 8 月 15 日に、EC2-Classic の提供を終了しｈます。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 Networking は販売終了になります — 準備方法はこちら](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 を使用することで、そのアドレスをインスタンスに関連付けることができます。その際は、EC2Client の `AssociateAddress` 関数の呼び出しで、割り当て ID とインスタンス ID を [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)をご覧ください。

## Elastic IP アドレスの記述
<a name="describe-elastic-ip-addresses"></a>

Elastic 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) が含まれています。このオブジェクトを使用して、アカウントの Elastic 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)をご覧ください。

## Elastic IP アドレスを解放する
<a name="release-an-elastic-ip-address"></a>

Elastic IP アドレスを解放するには、EC2Client の `ReleaseAddress` 関数を呼び出して、解放する Elastic 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;
    }
```

Elastic IP アドレスを解放すると、そのアドレスは AWS IP アドレスプールに解放され、その後使用できなくなる可能性があります。DNS レコード、およびそのアドレスと通信するすべてのサーバーまたはデバイスを更新してください。既にリリースした Elastic IP アドレスを解放しようとすると、そのアドレスがすでに別の AWS アカウントに割り当てられている場合、*AuthFailure* エラーが発生します。

*デフォルト VPC* を使用している場合、Elastic IP アドレスを解放すると、関連付けられているインスタンスから自動的に関連付けが解除されます。Elastic IP アドレスを解放せずに関連付けのみを解除するには、EC2Client の `DisassociateAddress` 関数を使用します。

デフォルト以外の VPC を使用している場合は、開放しようとする前に*必ず* `DisassociateAddress` を使用して Elastic 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 ユーザーガイド」の「[Elastic 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 リージョン で使用できる を一覧表示するには 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`関数を呼び出します。

結果オブジェクトに入れて [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 インスタンスへのインバウンド (ingress) とアウトバウンド (egress) トラフィックの両方を制御できます。

セキュリティグループに Ingress ルールを追加するには、EC2Client の `AuthorizeSecurityGroupIngress` 関数の呼び出しで、セキュリティグループの名前と割り当てるアクセスルール ([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)) を [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) オブジェクトで指定して渡します。以下の例では、セキュリティグループへの 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;
    }
```

セキュリティグループに egress ルールを追加するには、EC2Client の `AuthorizeSecurityGroupEgress` 関数の呼び出しで、同様のデータを [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) で指定して渡します。

[完全な例](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)」