

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

# AWS SDKs를 사용한 Amazon EC2 작업
<a name="service_code_examples_actions"></a>

다음 코드 예제에서는 AWS SDKs를 사용하여 개별 Amazon EC2 작업을 수행하는 방법을 보여줍니다. 각 예제에는 GitHub에 대한 링크가 포함되어 있습니다. 여기에서 코드 설정 및 실행에 대한 지침을 찾을 수 있습니다.

이들 발췌문은 Amazon EC2 API를 직접적으로 호출하며, 컨텍스트에서 실행되어야 하는 더 큰 프로그램에서 발췌한 코드입니다. [AWS SDKs를 사용한 Amazon EC2 시나리오](service_code_examples_scenarios.md)에서 컨텍스트에 맞는 작업을 볼 수 있습니다.

 다음 예제에는 가장 일반적으로 사용되는 작업만 포함되어 있습니다. 전체 목록은 [Amazon Elastic Compute Cloud API 참조](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Welcome.html)에서 확인하세요.

**Topics**
+ [`AcceptVpcPeeringConnection`](example_ec2_AcceptVpcPeeringConnection_section.md)
+ [`AllocateAddress`](example_ec2_AllocateAddress_section.md)
+ [`AllocateHosts`](example_ec2_AllocateHosts_section.md)
+ [`AssignPrivateIpAddresses`](example_ec2_AssignPrivateIpAddresses_section.md)
+ [`AssociateAddress`](example_ec2_AssociateAddress_section.md)
+ [`AssociateDhcpOptions`](example_ec2_AssociateDhcpOptions_section.md)
+ [`AssociateRouteTable`](example_ec2_AssociateRouteTable_section.md)
+ [`AttachInternetGateway`](example_ec2_AttachInternetGateway_section.md)
+ [`AttachNetworkInterface`](example_ec2_AttachNetworkInterface_section.md)
+ [`AttachVolume`](example_ec2_AttachVolume_section.md)
+ [`AttachVpnGateway`](example_ec2_AttachVpnGateway_section.md)
+ [`AuthorizeSecurityGroupEgress`](example_ec2_AuthorizeSecurityGroupEgress_section.md)
+ [`AuthorizeSecurityGroupIngress`](example_ec2_AuthorizeSecurityGroupIngress_section.md)
+ [`CancelCapacityReservation`](example_ec2_CancelCapacityReservation_section.md)
+ [`CancelImportTask`](example_ec2_CancelImportTask_section.md)
+ [`CancelSpotFleetRequests`](example_ec2_CancelSpotFleetRequests_section.md)
+ [`CancelSpotInstanceRequests`](example_ec2_CancelSpotInstanceRequests_section.md)
+ [`ConfirmProductInstance`](example_ec2_ConfirmProductInstance_section.md)
+ [`CopyImage`](example_ec2_CopyImage_section.md)
+ [`CopySnapshot`](example_ec2_CopySnapshot_section.md)
+ [`CreateCapacityReservation`](example_ec2_CreateCapacityReservation_section.md)
+ [`CreateCustomerGateway`](example_ec2_CreateCustomerGateway_section.md)
+ [`CreateDhcpOptions`](example_ec2_CreateDhcpOptions_section.md)
+ [`CreateFlowLogs`](example_ec2_CreateFlowLogs_section.md)
+ [`CreateImage`](example_ec2_CreateImage_section.md)
+ [`CreateInstanceExportTask`](example_ec2_CreateInstanceExportTask_section.md)
+ [`CreateInternetGateway`](example_ec2_CreateInternetGateway_section.md)
+ [`CreateKeyPair`](example_ec2_CreateKeyPair_section.md)
+ [`CreateLaunchTemplate`](example_ec2_CreateLaunchTemplate_section.md)
+ [`CreateNetworkAcl`](example_ec2_CreateNetworkAcl_section.md)
+ [`CreateNetworkAclEntry`](example_ec2_CreateNetworkAclEntry_section.md)
+ [`CreateNetworkInterface`](example_ec2_CreateNetworkInterface_section.md)
+ [`CreatePlacementGroup`](example_ec2_CreatePlacementGroup_section.md)
+ [`CreateRoute`](example_ec2_CreateRoute_section.md)
+ [`CreateRouteTable`](example_ec2_CreateRouteTable_section.md)
+ [`CreateSecurityGroup`](example_ec2_CreateSecurityGroup_section.md)
+ [`CreateSnapshot`](example_ec2_CreateSnapshot_section.md)
+ [`CreateSpotDatafeedSubscription`](example_ec2_CreateSpotDatafeedSubscription_section.md)
+ [`CreateSubnet`](example_ec2_CreateSubnet_section.md)
+ [`CreateTags`](example_ec2_CreateTags_section.md)
+ [`CreateVolume`](example_ec2_CreateVolume_section.md)
+ [`CreateVpc`](example_ec2_CreateVpc_section.md)
+ [`CreateVpcEndpoint`](example_ec2_CreateVpcEndpoint_section.md)
+ [`CreateVpnConnection`](example_ec2_CreateVpnConnection_section.md)
+ [`CreateVpnConnectionRoute`](example_ec2_CreateVpnConnectionRoute_section.md)
+ [`CreateVpnGateway`](example_ec2_CreateVpnGateway_section.md)
+ [`DeleteCustomerGateway`](example_ec2_DeleteCustomerGateway_section.md)
+ [`DeleteDhcpOptions`](example_ec2_DeleteDhcpOptions_section.md)
+ [`DeleteFlowLogs`](example_ec2_DeleteFlowLogs_section.md)
+ [`DeleteInternetGateway`](example_ec2_DeleteInternetGateway_section.md)
+ [`DeleteKeyPair`](example_ec2_DeleteKeyPair_section.md)
+ [`DeleteLaunchTemplate`](example_ec2_DeleteLaunchTemplate_section.md)
+ [`DeleteNetworkAcl`](example_ec2_DeleteNetworkAcl_section.md)
+ [`DeleteNetworkAclEntry`](example_ec2_DeleteNetworkAclEntry_section.md)
+ [`DeleteNetworkInterface`](example_ec2_DeleteNetworkInterface_section.md)
+ [`DeletePlacementGroup`](example_ec2_DeletePlacementGroup_section.md)
+ [`DeleteRoute`](example_ec2_DeleteRoute_section.md)
+ [`DeleteRouteTable`](example_ec2_DeleteRouteTable_section.md)
+ [`DeleteSecurityGroup`](example_ec2_DeleteSecurityGroup_section.md)
+ [`DeleteSnapshot`](example_ec2_DeleteSnapshot_section.md)
+ [`DeleteSpotDatafeedSubscription`](example_ec2_DeleteSpotDatafeedSubscription_section.md)
+ [`DeleteSubnet`](example_ec2_DeleteSubnet_section.md)
+ [`DeleteTags`](example_ec2_DeleteTags_section.md)
+ [`DeleteVolume`](example_ec2_DeleteVolume_section.md)
+ [`DeleteVpc`](example_ec2_DeleteVpc_section.md)
+ [`DeleteVpcEndpoints`](example_ec2_DeleteVpcEndpoints_section.md)
+ [`DeleteVpnConnection`](example_ec2_DeleteVpnConnection_section.md)
+ [`DeleteVpnConnectionRoute`](example_ec2_DeleteVpnConnectionRoute_section.md)
+ [`DeleteVpnGateway`](example_ec2_DeleteVpnGateway_section.md)
+ [`DeregisterImage`](example_ec2_DeregisterImage_section.md)
+ [`DescribeAccountAttributes`](example_ec2_DescribeAccountAttributes_section.md)
+ [`DescribeAddresses`](example_ec2_DescribeAddresses_section.md)
+ [`DescribeAvailabilityZones`](example_ec2_DescribeAvailabilityZones_section.md)
+ [`DescribeBundleTasks`](example_ec2_DescribeBundleTasks_section.md)
+ [`DescribeCapacityReservations`](example_ec2_DescribeCapacityReservations_section.md)
+ [`DescribeCustomerGateways`](example_ec2_DescribeCustomerGateways_section.md)
+ [`DescribeDhcpOptions`](example_ec2_DescribeDhcpOptions_section.md)
+ [`DescribeFlowLogs`](example_ec2_DescribeFlowLogs_section.md)
+ [`DescribeHostReservationOfferings`](example_ec2_DescribeHostReservationOfferings_section.md)
+ [`DescribeHosts`](example_ec2_DescribeHosts_section.md)
+ [`DescribeIamInstanceProfileAssociations`](example_ec2_DescribeIamInstanceProfileAssociations_section.md)
+ [`DescribeIdFormat`](example_ec2_DescribeIdFormat_section.md)
+ [`DescribeIdentityIdFormat`](example_ec2_DescribeIdentityIdFormat_section.md)
+ [`DescribeImageAttribute`](example_ec2_DescribeImageAttribute_section.md)
+ [`DescribeImages`](example_ec2_DescribeImages_section.md)
+ [`DescribeImportImageTasks`](example_ec2_DescribeImportImageTasks_section.md)
+ [`DescribeImportSnapshotTasks`](example_ec2_DescribeImportSnapshotTasks_section.md)
+ [`DescribeInstanceAttribute`](example_ec2_DescribeInstanceAttribute_section.md)
+ [`DescribeInstanceStatus`](example_ec2_DescribeInstanceStatus_section.md)
+ [`DescribeInstanceTypes`](example_ec2_DescribeInstanceTypes_section.md)
+ [`DescribeInstances`](example_ec2_DescribeInstances_section.md)
+ [`DescribeInternetGateways`](example_ec2_DescribeInternetGateways_section.md)
+ [`DescribeKeyPairs`](example_ec2_DescribeKeyPairs_section.md)
+ [`DescribeNetworkAcls`](example_ec2_DescribeNetworkAcls_section.md)
+ [`DescribeNetworkInterfaceAttribute`](example_ec2_DescribeNetworkInterfaceAttribute_section.md)
+ [`DescribeNetworkInterfaces`](example_ec2_DescribeNetworkInterfaces_section.md)
+ [`DescribePlacementGroups`](example_ec2_DescribePlacementGroups_section.md)
+ [`DescribePrefixLists`](example_ec2_DescribePrefixLists_section.md)
+ [`DescribeRegions`](example_ec2_DescribeRegions_section.md)
+ [`DescribeRouteTables`](example_ec2_DescribeRouteTables_section.md)
+ [`DescribeScheduledInstanceAvailability`](example_ec2_DescribeScheduledInstanceAvailability_section.md)
+ [`DescribeScheduledInstances`](example_ec2_DescribeScheduledInstances_section.md)
+ [`DescribeSecurityGroups`](example_ec2_DescribeSecurityGroups_section.md)
+ [`DescribeSnapshotAttribute`](example_ec2_DescribeSnapshotAttribute_section.md)
+ [`DescribeSnapshots`](example_ec2_DescribeSnapshots_section.md)
+ [`DescribeSpotDatafeedSubscription`](example_ec2_DescribeSpotDatafeedSubscription_section.md)
+ [`DescribeSpotFleetInstances`](example_ec2_DescribeSpotFleetInstances_section.md)
+ [`DescribeSpotFleetRequestHistory`](example_ec2_DescribeSpotFleetRequestHistory_section.md)
+ [`DescribeSpotFleetRequests`](example_ec2_DescribeSpotFleetRequests_section.md)
+ [`DescribeSpotInstanceRequests`](example_ec2_DescribeSpotInstanceRequests_section.md)
+ [`DescribeSpotPriceHistory`](example_ec2_DescribeSpotPriceHistory_section.md)
+ [`DescribeSubnets`](example_ec2_DescribeSubnets_section.md)
+ [`DescribeTags`](example_ec2_DescribeTags_section.md)
+ [`DescribeVolumeAttribute`](example_ec2_DescribeVolumeAttribute_section.md)
+ [`DescribeVolumeStatus`](example_ec2_DescribeVolumeStatus_section.md)
+ [`DescribeVolumes`](example_ec2_DescribeVolumes_section.md)
+ [`DescribeVpcAttribute`](example_ec2_DescribeVpcAttribute_section.md)
+ [`DescribeVpcClassicLink`](example_ec2_DescribeVpcClassicLink_section.md)
+ [`DescribeVpcClassicLinkDnsSupport`](example_ec2_DescribeVpcClassicLinkDnsSupport_section.md)
+ [`DescribeVpcEndpointServices`](example_ec2_DescribeVpcEndpointServices_section.md)
+ [`DescribeVpcEndpoints`](example_ec2_DescribeVpcEndpoints_section.md)
+ [`DescribeVpcs`](example_ec2_DescribeVpcs_section.md)
+ [`DescribeVpnConnections`](example_ec2_DescribeVpnConnections_section.md)
+ [`DescribeVpnGateways`](example_ec2_DescribeVpnGateways_section.md)
+ [`DetachInternetGateway`](example_ec2_DetachInternetGateway_section.md)
+ [`DetachNetworkInterface`](example_ec2_DetachNetworkInterface_section.md)
+ [`DetachVolume`](example_ec2_DetachVolume_section.md)
+ [`DetachVpnGateway`](example_ec2_DetachVpnGateway_section.md)
+ [`DisableVgwRoutePropagation`](example_ec2_DisableVgwRoutePropagation_section.md)
+ [`DisableVpcClassicLink`](example_ec2_DisableVpcClassicLink_section.md)
+ [`DisableVpcClassicLinkDnsSupport`](example_ec2_DisableVpcClassicLinkDnsSupport_section.md)
+ [`DisassociateAddress`](example_ec2_DisassociateAddress_section.md)
+ [`DisassociateRouteTable`](example_ec2_DisassociateRouteTable_section.md)
+ [`EnableVgwRoutePropagation`](example_ec2_EnableVgwRoutePropagation_section.md)
+ [`EnableVolumeIo`](example_ec2_EnableVolumeIo_section.md)
+ [`EnableVpcClassicLink`](example_ec2_EnableVpcClassicLink_section.md)
+ [`EnableVpcClassicLinkDnsSupport`](example_ec2_EnableVpcClassicLinkDnsSupport_section.md)
+ [`GetConsoleOutput`](example_ec2_GetConsoleOutput_section.md)
+ [`GetHostReservationPurchasePreview`](example_ec2_GetHostReservationPurchasePreview_section.md)
+ [`GetPasswordData`](example_ec2_GetPasswordData_section.md)
+ [`ImportImage`](example_ec2_ImportImage_section.md)
+ [`ImportKeyPair`](example_ec2_ImportKeyPair_section.md)
+ [`ImportSnapshot`](example_ec2_ImportSnapshot_section.md)
+ [`ModifyCapacityReservation`](example_ec2_ModifyCapacityReservation_section.md)
+ [`ModifyHosts`](example_ec2_ModifyHosts_section.md)
+ [`ModifyIdFormat`](example_ec2_ModifyIdFormat_section.md)
+ [`ModifyImageAttribute`](example_ec2_ModifyImageAttribute_section.md)
+ [`ModifyInstanceAttribute`](example_ec2_ModifyInstanceAttribute_section.md)
+ [`ModifyInstanceCreditSpecification`](example_ec2_ModifyInstanceCreditSpecification_section.md)
+ [`ModifyNetworkInterfaceAttribute`](example_ec2_ModifyNetworkInterfaceAttribute_section.md)
+ [`ModifyReservedInstances`](example_ec2_ModifyReservedInstances_section.md)
+ [`ModifySnapshotAttribute`](example_ec2_ModifySnapshotAttribute_section.md)
+ [`ModifySpotFleetRequest`](example_ec2_ModifySpotFleetRequest_section.md)
+ [`ModifySubnetAttribute`](example_ec2_ModifySubnetAttribute_section.md)
+ [`ModifyVolumeAttribute`](example_ec2_ModifyVolumeAttribute_section.md)
+ [`ModifyVpcAttribute`](example_ec2_ModifyVpcAttribute_section.md)
+ [`MonitorInstances`](example_ec2_MonitorInstances_section.md)
+ [`MoveAddressToVpc`](example_ec2_MoveAddressToVpc_section.md)
+ [`PurchaseHostReservation`](example_ec2_PurchaseHostReservation_section.md)
+ [`PurchaseScheduledInstances`](example_ec2_PurchaseScheduledInstances_section.md)
+ [`RebootInstances`](example_ec2_RebootInstances_section.md)
+ [`RegisterImage`](example_ec2_RegisterImage_section.md)
+ [`RejectVpcPeeringConnection`](example_ec2_RejectVpcPeeringConnection_section.md)
+ [`ReleaseAddress`](example_ec2_ReleaseAddress_section.md)
+ [`ReleaseHosts`](example_ec2_ReleaseHosts_section.md)
+ [`ReplaceIamInstanceProfileAssociation`](example_ec2_ReplaceIamInstanceProfileAssociation_section.md)
+ [`ReplaceNetworkAclAssociation`](example_ec2_ReplaceNetworkAclAssociation_section.md)
+ [`ReplaceNetworkAclEntry`](example_ec2_ReplaceNetworkAclEntry_section.md)
+ [`ReplaceRoute`](example_ec2_ReplaceRoute_section.md)
+ [`ReplaceRouteTableAssociation`](example_ec2_ReplaceRouteTableAssociation_section.md)
+ [`ReportInstanceStatus`](example_ec2_ReportInstanceStatus_section.md)
+ [`RequestSpotFleet`](example_ec2_RequestSpotFleet_section.md)
+ [`RequestSpotInstances`](example_ec2_RequestSpotInstances_section.md)
+ [`ResetImageAttribute`](example_ec2_ResetImageAttribute_section.md)
+ [`ResetInstanceAttribute`](example_ec2_ResetInstanceAttribute_section.md)
+ [`ResetNetworkInterfaceAttribute`](example_ec2_ResetNetworkInterfaceAttribute_section.md)
+ [`ResetSnapshotAttribute`](example_ec2_ResetSnapshotAttribute_section.md)
+ [`RevokeSecurityGroupEgress`](example_ec2_RevokeSecurityGroupEgress_section.md)
+ [`RevokeSecurityGroupIngress`](example_ec2_RevokeSecurityGroupIngress_section.md)
+ [`RunInstances`](example_ec2_RunInstances_section.md)
+ [`RunScheduledInstances`](example_ec2_RunScheduledInstances_section.md)
+ [`StartInstances`](example_ec2_StartInstances_section.md)
+ [`StopInstances`](example_ec2_StopInstances_section.md)
+ [`TerminateInstances`](example_ec2_TerminateInstances_section.md)
+ [`UnassignPrivateIpAddresses`](example_ec2_UnassignPrivateIpAddresses_section.md)
+ [`UnmonitorInstances`](example_ec2_UnmonitorInstances_section.md)
+ [`UpdateSecurityGroupRuleDescriptionsIngress`](example_ec2_UpdateSecurityGroupRuleDescriptionsIngress_section.md)

# CLI로 `AcceptVpcPeeringConnection` 사용
<a name="example_ec2_AcceptVpcPeeringConnection_section"></a>

다음 코드 예시는 `AcceptVpcPeeringConnection`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPC 피어링 연결 허용**  
이 예시에서는 지정된 VPC 피어링 연결 요청을 수락합니다.  
명령:  

```
aws ec2 accept-vpc-peering-connection --vpc-peering-connection-id pcx-1a2b3c4d
```
출력:  

```
{
  "VpcPeeringConnection": {
    "Status": {
      "Message": "Provisioning",
      "Code": "provisioning"
    },
    "Tags": [],
    "AccepterVpcInfo": {
      "OwnerId": "444455556666",
      "VpcId": "vpc-44455566",
      "CidrBlock": "10.0.1.0/28"
    },
    "VpcPeeringConnectionId": "pcx-1a2b3c4d",
    "RequesterVpcInfo": {
      "OwnerId": "444455556666",
      "VpcId": "vpc-111abc45",
      "CidrBlock": "10.0.0.0/28"
    }
  }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AcceptVpcPeeringConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/accept-vpc-peering-connection.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 요청된 VpcPeeringConnectionId pcx-1dfad234b56ff78be를 승인합니다.**  

```
Approve-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-1dfad234b56ff78be
```
**출력:**  

```
AccepterVpcInfo        : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
ExpirationTime         : 1/1/0001 12:00:00 AM
RequesterVpcInfo       : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
Status                 : Amazon.EC2.Model.VpcPeeringConnectionStateReason
Tags                   : {}
VpcPeeringConnectionId : pcx-1dfad234b56ff78be
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AcceptVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 요청된 VpcPeeringConnectionId pcx-1dfad234b56ff78be를 승인합니다.**  

```
Approve-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-1dfad234b56ff78be
```
**출력:**  

```
AccepterVpcInfo        : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
ExpirationTime         : 1/1/0001 12:00:00 AM
RequesterVpcInfo       : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
Status                 : Amazon.EC2.Model.VpcPeeringConnectionStateReason
Tags                   : {}
VpcPeeringConnectionId : pcx-1dfad234b56ff78be
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AcceptVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `AllocateAddress` 함께 사용
<a name="example_ec2_AllocateAddress_section"></a>

다음 코드 예시는 `AllocateAddress`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Allocates an Elastic IP address that can be associated with an Amazon EC2
    // instance. By using an Elastic IP address, you can keep the public IP address
    // constant even when you restart the associated instance.
    /// </summary>
    /// <returns>The response object for the allocated address.</returns>
    public async Task<AllocateAddressResponse> AllocateAddress()
    {
        var request = new AllocateAddressRequest();

        try
        {
            var response = await _amazonEC2.AllocateAddressAsync(request);
            Console.WriteLine($"Allocated IP: {response.PublicIp} with allocation ID {response.AllocationId}.");
            return response;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "AddressLimitExceeded")
            {
                // For more information on Elastic IP address quotas, see:
                // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#using-instance-addressing-limit
                _logger.LogError($"Unable to allocate Elastic IP, address limit exceeded. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while allocating Elastic IP.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET  API 참조*의 [AllocateAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/AllocateAddress)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_allocate_address
#
# This function allocates an Elastic IP address for use with Amazon Elastic Compute Cloud (Amazon EC2) instances in a specific AWS Region.
#
# Parameters:
#       -d domain - The domain for the Elastic IP address (either 'vpc' or 'standard').
#
# Returns:
#       The allocated Elastic IP address, or an error message if the operation fails.
# And:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_allocate_address() {
  local domain response

  # Function to display usage information
  function usage() {
    echo "function ec2_allocate_address"
    echo "Allocates an Elastic IP address for use with Amazon Elastic Compute Cloud (Amazon EC2) instances in a specific AWS Region."
    echo "  -d domain - The domain for the Elastic IP address (either 'vpc' or 'standard')."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "d:h" option; do
    case "${option}" in
      d) domain="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$domain" ]]; then
    errecho "ERROR: You must provide a domain with the -d parameter (either 'vpc' or 'standard')."
    return 1
  fi

  if [[ "$domain" != "vpc" && "$domain" != "standard" ]]; then
    errecho "ERROR: Invalid domain value. Must be either 'vpc' or 'standard'."
    return 1
  fi

  # Allocate the Elastic IP address
  response=$(aws ec2 allocate-address \
    --domain "$domain" \
    --query "[PublicIp,AllocationId]" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports allocate-address operation failed."
    errecho "$response"
    return 1
  }

  echo "$response"
  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [AllocateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AllocateAddress)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Allocate an Elastic IP address and associate it with an Amazon Elastic Compute Cloud
//! (Amazon EC2) instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param[out] publicIPAddress: String to return the public IP address.
  \param[out] allocationID: String to return the allocation ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::allocateAndAssociateAddress(const Aws::String &instanceId, Aws::String &publicIPAddress,
                                              Aws::String &allocationID,
                                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    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();


    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1  API 참조*의 [AllocateAddress](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/AllocateAddress)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: Amazon 주소 풀에서 탄력적 IP 주소를 할당하는 방법**  
다음 `allocate-address` 예제는 탄력적 IP 주소를 할당합니다. Amazon EC2는 Amazon 주소 풀에서 주소를 선택합니다.  

```
aws ec2 allocate-address
```
출력:  

```
{
    "PublicIp": "70.224.234.241",
    "AllocationId": "eipalloc-01435ba59eEXAMPLE",
    "PublicIpv4Pool": "amazon",
    "NetworkBorderGroup": "us-west-2",
    "Domain": "vpc"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [탄력적 IP 주소](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)를 참조하세요.  
**예제 2: 탄력적 IP 주소를 할당하고 네트워크 경계 그룹에 연결하는 방법**  
다음 `allocate-address` 예제에서는 탄력적 IP 주소를 할당하고 해당 주소를 지정된 네트워크 경계 그룹에 연결합니다.  

```
aws ec2 allocate-address \
    --network-border-group us-west-2-lax-1
```
출력:  

```
{
    "PublicIp": "70.224.234.241",
    "AllocationId": "eipalloc-e03dd489ceEXAMPLE",
    "PublicIpv4Pool": "amazon",
    "NetworkBorderGroup": "us-west-2-lax-1",
    "Domain": "vpc"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [탄력적 IP 주소](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)를 참조하세요.  
**예 3: 소유한 주소 풀에서 탄력적 IP 주소를 할당하는 방법**  
다음 `allocate-address` 예제에서는 Amazon Web Services 계정으로 가져온 주소 풀에서 탄력적 IP 주소를 할당합니다. Amazon EC2는 주소 풀에서 주소를 선택합니다.  

```
aws ec2 allocate-address \
    --public-ipv4-pool ipv4pool-ec2-1234567890abcdef0
```
출력:  

```
{
    "AllocationId": "eipalloc-02463d08ceEXAMPLE",
    "NetworkBorderGroup": "us-west-2",
    "CustomerOwnedIp": "18.218.95.81",
    "CustomerOwnedIpv4Pool": "ipv4pool-ec2-1234567890abcdef0",
    "Domain": "vpc"
    "NetworkBorderGroup": "us-west-2",
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [탄력적 IP 주소](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)를 참조하세요.  
**예제 4: IPAM 풀에서 탄력적 IP 주소 할당**  
다음 `allocate-address` 예제에서는 Amazon VPC IP Address Manager(IPAM) 풀에서 특정 /32 탄력적 IP 주소를 할당합니다.  

```
aws ec2 allocate-address \
    --region us-east-1 \
    --ipam-pool-id ipam-pool-1234567890abcdef0 \
    --address 192.0.2.0
```
출력:  

```
{
    "PublicIp": "192.0.2.0",
    "AllocationId": "eipalloc-abcdef01234567890",
    "PublicIpv4Pool": "ipam-pool-1234567890abcdef0",
    "NetworkBorderGroup": "us-east-1",
    "Domain": "vpc"
}
```
자세한 내용은 **Amazon VPC IPAM 사용 설명서의 [IPAM 풀에서 순차적 탄력적 IP 주소 할당](https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-eip-pool.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [AllocateAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/allocate-address.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Allocates an Elastic IP address asynchronously in the VPC domain.
     *
     * @return a {@link CompletableFuture} containing the allocation ID of the allocated Elastic IP address
     */
    public CompletableFuture<String> allocateAddressAsync() {
        AllocateAddressRequest allocateRequest = AllocateAddressRequest.builder()
            .domain(DomainType.VPC)
            .build();

        CompletableFuture<AllocateAddressResponse> responseFuture = getAsyncClient().allocateAddress(allocateRequest);
        return responseFuture.thenApply(AllocateAddressResponse::allocationId).whenComplete((result, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to allocate address", ex);
            }
        });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x  API 참조*의 [AllocateAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/AllocateAddress)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { AllocateAddressCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Allocates an Elastic IP address to your AWS account.
 */
export const main = async () => {
  const client = new EC2Client({});
  const command = new AllocateAddressCommand({});

  try {
    const { AllocationId, PublicIp } = await client.send(command);
    console.log("A new IP address has been allocated to your account:");
    console.log(`ID: ${AllocationId} Public IP: ${PublicIp}`);
    console.log(
      "You can view your IP addresses in the AWS Management Console for Amazon EC2. Look under Network & Security > Elastic IPs",
    );
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide these values?`);
    } else {
      throw caught;
    }
  }
};
import { fileURLToPath } from "node:url";
// Call function if run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```
+  API 세부 정보는 *AWS SDK for JavaScript  API 참조*의 [AllocateAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/AllocateAddressCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun getAllocateAddress(instanceIdVal: String?): String? {
    val allocateRequest =
        AllocateAddressRequest {
            domain = DomainType.Vpc
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val allocateResponse = ec2.allocateAddress(allocateRequest)
        val allocationIdVal = allocateResponse.allocationId

        val request =
            AssociateAddressRequest {
                instanceId = instanceIdVal
                allocationId = allocationIdVal
            }

        val associateResponse = ec2.associateAddress(request)
        return associateResponse.associationId
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [AllocateAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 VPC의 인스턴스에 사용할 탄력적 IP 주소를 할당합니다.**  

```
New-EC2Address -Domain Vpc
```
**출력:**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
eipalloc-12345678    vpc         198.51.100.2
```
**예제 2: 이 예제에서는 EC2-Classic의 인스턴스에 사용할 탄력적 IP 주소를 할당합니다.**  

```
New-EC2Address
```
**출력:**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
                     standard    203.0.113.17
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AllocateAddress](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 VPC의 인스턴스에 사용할 탄력적 IP 주소를 할당합니다.**  

```
New-EC2Address -Domain Vpc
```
**출력:**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
eipalloc-12345678    vpc         198.51.100.2
```
**예제 2: 이 예제에서는 EC2-Classic의 인스턴스에 사용할 탄력적 IP 주소를 할당합니다.**  

```
New-EC2Address
```
**출력:**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
                     standard    203.0.113.17
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AllocateAddress](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class ElasticIpWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface."""

    class ElasticIp:
        """Represents an Elastic IP and its associated instance."""

        def __init__(
            self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None
        ) -> None:
            """
            Initializes the ElasticIp object.

            :param allocation_id: The allocation ID of the Elastic IP.
            :param public_ip: The public IP address of the Elastic IP.
            :param instance_id: The ID of the associated EC2 instance, if any.
            """
            self.allocation_id = allocation_id
            self.public_ip = public_ip
            self.instance_id = instance_id

    def __init__(self, ec2_client: Any) -> None:
        """
        Initializes the ElasticIpWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client
        self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = []

    @classmethod
    def from_client(cls) -> "ElasticIpWrapper":
        """
        Creates an ElasticIpWrapper instance with a default EC2 client.

        :return: An instance of ElasticIpWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def allocate(self) -> "ElasticIpWrapper.ElasticIp":
        """
        Allocates an Elastic IP address that can be associated with an Amazon EC2
        instance. By using an Elastic IP address, you can keep the public IP address
        constant even when you restart the associated instance.

        :return: The ElasticIp object for the newly created Elastic IP address.
        :raises ClientError: If the allocation fails, such as reaching the maximum limit of Elastic IPs.
        """
        try:
            response = self.ec2_client.allocate_address(Domain="vpc")
            elastic_ip = self.ElasticIp(
                allocation_id=response["AllocationId"], public_ip=response["PublicIp"]
            )
            self.elastic_ips.append(elastic_ip)
        except ClientError as err:
            if err.response["Error"]["Code"] == "AddressLimitExceeded":
                logger.error(
                    "Max IP's reached. Release unused addresses or contact AWS Support for an increase."
                )
            raise err
        return elastic_ip
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [AllocateAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/AllocateAddress)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
# Creates an Elastic IP address in Amazon Virtual Private Cloud (Amazon VPC).
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @return [String] The allocation ID corresponding to the Elastic IP address.
# @example
#   puts allocate_elastic_ip_address(Aws::EC2::Client.new(region: 'us-west-2'))
def allocate_elastic_ip_address(ec2_client)
  response = ec2_client.allocate_address(domain: 'vpc')
  response.allocation_id
rescue StandardError => e
  puts "Error allocating Elastic IP address: #{e.message}"
  'Error'
end
```
+  API 세부 정보는 *AWS SDK for Ruby  API 참조*의 [AllocateAddress](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/AllocateAddress)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn allocate_ip_address(&self) -> Result<AllocateAddressOutput, EC2Error> {
        self.client
            .allocate_address()
            .domain(DomainType::Vpc)
            .send()
            .await
            .map_err(EC2Error::from)
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [AllocateAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.allocate_address)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->allocateaddress( iv_domain = 'vpc' ).   " oo_result is returned for testing purposes. "
        MESSAGE 'Allocated an Elastic IP address.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [AllocateAddress](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Allocate an Elastic IP address.
    ///
    /// - Returns: A string containing the ID of the Elastic IP.
    func allocateAddress() async -> String? {
        do {
            let output = try await ec2Client.allocateAddress(
                input: AllocateAddressInput(
                    domain: EC2ClientTypes.DomainType.vpc
                )
            )

            guard let allocationId = output.allocationId else {
                return nil
            }

            return allocationId
        } catch {
            print("*** Unable to allocate the IP address: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [AllocateAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/allocateaddress(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `AllocateHosts` 사용
<a name="example_ec2_AllocateHosts_section"></a>

다음 코드 예시는 `AllocateHosts`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 전용 호스트 할당**  
다음 `allocate-hosts` 예시에서는 `m5.large` 인스턴스를 시작할 수 있는 `eu-west-1a` 가용 영역에 단일 전용 호스트를 할당합니다. 기본적으로 전용 호스트는 대상 인스턴스 시작만 허용하며 호스트 복구는 지원하지 않습니다.  

```
aws ec2 allocate-hosts \
    --instance-type m5.large \
    --availability-zone eu-west-1a \
    --quantity 1
```
출력:  

```
{
    "HostIds": [
        "h-07879acf49EXAMPLE"
    ]
}
```
**예시 2: 자동 배치 및 호스트 복구가 활성화된 전용 호스트 할당**  
다음 `allocate-hosts` 예시에서는 자동 배치 및 호스트 복구가 활성화된 `eu-west-1a` 가용 영역에 단일 전용 호스트를 할당합니다.  

```
aws ec2 allocate-hosts \
    --instance-type m5.large \
    --availability-zone eu-west-1a \
    --auto-placement on \
    --host-recovery on \
    --quantity 1
```
출력:  

```
{
     "HostIds": [
         "h-07879acf49EXAMPLE"
     ]
}
```
**예시 3: 태그가 있는 전용 호스트 할당**  
다음 `allocate-hosts` 예시에서는 단일 전용 호스트를 할당하고 키 이름이 `purpose`, 값이 `production`인 태그를 적용합니다  

```
aws ec2 allocate-hosts \
    --instance-type m5.large \
    --availability-zone eu-west-1a \
    --quantity 1 \
    --tag-specifications 'ResourceType=dedicated-host,Tags={Key=purpose,Value=production}'
```
출력:  

```
{
    "HostIds": [
        "h-07879acf49EXAMPLE"
    ]
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [전용 호스트 할당](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-hosts-allocating.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AllocateHosts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/allocate-hosts.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스 유형 및 가용 영역에 대해 계정에 전용 호스트를 할당합니다.**  

```
New-EC2Host -AutoPlacement on -AvailabilityZone eu-west-1b -InstanceType m4.xlarge -Quantity 1
```
**출력:**  

```
h-01e23f4cd567890f3
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AllocateHosts](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스 유형 및 가용 영역에 대해 계정에 전용 호스트를 할당합니다.**  

```
New-EC2Host -AutoPlacement on -AvailabilityZone eu-west-1b -InstanceType m4.xlarge -Quantity 1
```
**출력:**  

```
h-01e23f4cd567890f3
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AllocateHosts](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `AssignPrivateIpAddresses` 사용
<a name="example_ec2_AssignPrivateIpAddresses_section"></a>

다음 코드 예시는 `AssignPrivateIpAddresses`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**특정 보조 프라이빗 IP 주소에 네트워크 인터페이스 할당**  
이 예시에서는 지정된 보조 프라이빗 IP 주소를 지정된 네트워크 인터페이스에 할당합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 assign-private-ip-addresses --network-interface-id eni-e5aa89a3 --private-ip-addresses 10.0.0.82
```
**Amazon EC2가 선택한 보조 프라이빗 IP 주소를 네트워크 인터페이스 할당**  
이 예시에서는 지정된 네트워크 인터페이스에 두 개의 보조 프라이빗 IP 주소를 할당합니다. Amazon EC2는 네트워크 인터페이스가 연결된 서브넷의 CIDR 블록 범위에서 사용 가능한 IP 주소 중에서 이러한 IP 주소를 자동으로 할당합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 assign-private-ip-addresses --network-interface-id eni-e5aa89a3 --secondary-private-ip-address-count 2
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AssignPrivateIpAddresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/assign-private-ip-addresses.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 보조 프라이빗 IP 주소를 지정된 네트워크 인터페이스에 할당합니다.**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
**예제 2: 이 예제에서는 두 개의 보조 프라이빗 IP 주소를 생성하고 이를 지정된 네트워크 인터페이스에 할당합니다.**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -SecondaryPrivateIpAddressCount 2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AssignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 보조 프라이빗 IP 주소를 지정된 네트워크 인터페이스에 할당합니다.**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
**예제 2: 이 예제에서는 두 개의 보조 프라이빗 IP 주소를 생성하고 이를 지정된 네트워크 인터페이스에 할당합니다.**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -SecondaryPrivateIpAddressCount 2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AssignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `AssociateAddress` 함께 사용
<a name="example_ec2_AssociateAddress_section"></a>

다음 코드 예시는 `AssociateAddress`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Associates an Elastic IP address with an instance. When this association is
    /// created, the Elastic IP's public IP address is immediately used as the public
    /// IP address of the associated instance.
    /// </summary>
    /// <param name="allocationId">The allocation Id of an Elastic IP address.</param>
    /// <param name="instanceId">The instance Id of the EC2 instance to
    /// associate the address with.</param>
    /// <returns>The association Id that represents
    /// the association of the Elastic IP address with an instance.</returns>
    public async Task<string> AssociateAddress(string allocationId, string instanceId)
    {
        try
        {
            var request = new AssociateAddressRequest
            {
                AllocationId = allocationId,
                InstanceId = instanceId
            };

            var response = await _amazonEC2.AssociateAddressAsync(request);
            return response.AssociationId;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to associate address. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while associating the Elastic IP.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET  API 참조*의 [AssociateAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/AssociateAddress)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_associate_address
#
# This function associates an Elastic IP address with an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       -a allocation_id - The allocation ID of the Elastic IP address to associate.
#       -i instance_id - The ID of the EC2 instance to associate the Elastic IP address with.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_associate_address() {
  local allocation_id instance_id response

  # Function to display usage information
  function usage() {
    echo "function ec2_associate_address"
    echo "Associates an Elastic IP address with an Amazon Elastic Compute Cloud (Amazon EC2) instance."
    echo "  -a allocation_id - The allocation ID of the Elastic IP address to associate."
    echo "  -i instance_id - The ID of the EC2 instance to associate the Elastic IP address with."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "a:i:h" option; do
    case "${option}" in
      a) allocation_id="${OPTARG}" ;;
      i) instance_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$allocation_id" ]]; then
    errecho "ERROR: You must provide an allocation ID with the -a parameter."
    return 1
  fi

  if [[ -z "$instance_id" ]]; then
    errecho "ERROR: You must provide an instance ID with the -i parameter."
    return 1
  fi

  # Associate the Elastic IP address
  response=$(aws ec2 associate-address \
    --allocation-id "$allocation_id" \
    --instance-id "$instance_id" \
    --query "AssociationId" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports associate-address operation failed."
    errecho "$response"
    return 1
  }

  echo "$response"
  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [AssociateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AssociateAddress)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

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

//! Associate an Elastic IP address with an EC2 instance.
/*!
  \param instanceId: An EC2 instance ID.
  \param allocationId: An Elastic IP allocation ID.
  \param[out] associationID: String to receive the association ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: True if the address was associated with the instance; otherwise, false.
 */
bool AwsDoc::EC2::associateAddress(const Aws::String &instanceId, const Aws::String &allocationId,
                                   Aws::String &associationID,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::AssociateAddressRequest request;
    request.SetInstanceId(instanceId);
    request.SetAllocationId(allocationId);

    Aws::EC2::Model::AssociateAddressOutcome outcome = ec2Client.AssociateAddress(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to associate address " << allocationId <<
                  " with instance " << instanceId << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully associated address " << allocationId <<
                  " with instance " << instanceId << std::endl;
        associationID = outcome.GetResult().GetAssociationId();
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1  API 참조*의 [AssociateAddress](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/AssociateAddress)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 인스턴스와 탄력적 IP 주소 연결**  
다음 `associate-address` 예제에서는 지정된 EC2 인스턴스와 탄력적 IP 주소를 연결합니다.  

```
aws ec2 associate-address \
    --instance-id i-0b263919b6498b123 \
    --allocation-id eipalloc-64d5890a
```
출력:  

```
{
    "AssociationId": "eipassoc-2bebb745"
}
```
**예제 2: 네트워크 인터페이스와 탄력적 IP 주소 연결**  
다음 `associate-address` 예제에서는 지정된 탄력적 IP 주소와 지정된 네트워크 인터페이스를 연결합니다.  

```
aws ec2 associate-address
    --allocation-id eipalloc-64d5890a \
    --network-interface-id eni-1a2b3c4d
```
출력:  

```
{
    "AssociationId": "eipassoc-2bebb745"
}
```
**예제 3: 탄력적 IP 주소와 프라이빗 IP 주소 연결**  
다음 `associate-address` 예제에서는 지정된 탄력적 IP 주소를 지정된 네트워크 인터페이스의 지정된 프라이빗 IP 주소와 연결합니다.  

```
aws ec2 associate-address \
    --allocation-id eipalloc-64d5890a \
    --network-interface-id eni-1a2b3c4d \
    --private-ip-address 10.0.0.85
```
출력:  

```
{
    "AssociationId": "eipassoc-2bebb745"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [탄력적 IP 주소](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AssociateAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-address.html) 섹션을 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Associates an Elastic IP address with an EC2 instance asynchronously.
     *
     * @param instanceId    the ID of the EC2 instance to associate the Elastic IP address with
     * @param allocationId  the allocation ID of the Elastic IP address to associate
     * @return a {@link CompletableFuture} that completes with the association ID when the operation is successful,
     *         or throws a {@link RuntimeException} if the operation fails
     */
    public CompletableFuture<String> associateAddressAsync(String instanceId, String allocationId) {
        AssociateAddressRequest associateRequest = AssociateAddressRequest.builder()
            .instanceId(instanceId)
            .allocationId(allocationId)
            .build();

        CompletableFuture<AssociateAddressResponse> responseFuture = getAsyncClient().associateAddress(associateRequest);
        return responseFuture.thenApply(response -> {
            if (response.associationId() != null) {
                return response.associationId();
            } else {
                throw new RuntimeException("Association ID is null after associating address.");
            }
        }).whenComplete((result, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to associate address", ex);
            }
        });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x  API 참조*의 [AssociateAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/AssociateAddress)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { AssociateAddressCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones)
 * with an instance or a network interface.
 * @param {{ instanceId: string, allocationId: string }} options
 */
export const main = async ({ instanceId, allocationId }) => {
  const client = new EC2Client({});
  const command = new AssociateAddressCommand({
    // You need to allocate an Elastic IP address before associating it with an instance.
    // You can do that with the AllocateAddressCommand.
    AllocationId: allocationId,
    // You need to create an EC2 instance before an IP address can be associated with it.
    // You can do that with the RunInstancesCommand.
    InstanceId: instanceId,
  });

  try {
    const { AssociationId } = await client.send(command);
    console.log(
      `Address with allocation ID ${allocationId} is now associated with instance ${instanceId}.`,
      `The association ID is ${AssociationId}.`,
    );
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidAllocationID.NotFound"
    ) {
      console.warn(
        `${caught.message}. Did you provide the ID of a valid Elastic IP address AllocationId?`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript  API 참조*의 [AssociateAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/AssociateAddressCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun associateAddressSc(
    instanceIdVal: String?,
    allocationIdVal: String?,
): String? {
    val associateRequest =
        AssociateAddressRequest {
            instanceId = instanceIdVal
            allocationId = allocationIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val associateResponse = ec2.associateAddress(associateRequest)
        return associateResponse.associationId
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [AssociateAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 탄력적 IP 주소를 VPC의 지정된 인스턴스와 연결합니다.**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -AllocationId eipalloc-12345678
```
**출력:**  

```
eipassoc-12345678
```
**예제 2: 이 예제에서는 지정된 탄력적 IP 주소를 EC2-Classic의 지정된 인스턴스와 연결합니다.**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -PublicIp 203.0.113.17
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AssociateAddress](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 탄력적 IP 주소를 VPC의 지정된 인스턴스와 연결합니다.**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -AllocationId eipalloc-12345678
```
**출력:**  

```
eipassoc-12345678
```
**예제 2: 이 예제에서는 지정된 탄력적 IP 주소를 EC2-Classic의 지정된 인스턴스와 연결합니다.**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -PublicIp 203.0.113.17
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AssociateAddress](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class ElasticIpWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface."""

    class ElasticIp:
        """Represents an Elastic IP and its associated instance."""

        def __init__(
            self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None
        ) -> None:
            """
            Initializes the ElasticIp object.

            :param allocation_id: The allocation ID of the Elastic IP.
            :param public_ip: The public IP address of the Elastic IP.
            :param instance_id: The ID of the associated EC2 instance, if any.
            """
            self.allocation_id = allocation_id
            self.public_ip = public_ip
            self.instance_id = instance_id

    def __init__(self, ec2_client: Any) -> None:
        """
        Initializes the ElasticIpWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client
        self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = []

    @classmethod
    def from_client(cls) -> "ElasticIpWrapper":
        """
        Creates an ElasticIpWrapper instance with a default EC2 client.

        :return: An instance of ElasticIpWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def associate(
        self, allocation_id: str, instance_id: str
    ) -> Union[Dict[str, Any], None]:
        """
        Associates an Elastic IP address with an instance. When this association is
        created, the Elastic IP's public IP address is immediately used as the public
        IP address of the associated instance.

        :param allocation_id: The allocation ID of the Elastic IP.
        :param instance_id: The ID of the Amazon EC2 instance.
        :return: A response that contains the ID of the association, or None if no Elastic IP is found.
        :raises ClientError: If the association fails, such as when the instance ID is not found.
        """
        elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id)
        if elastic_ip is None:
            logger.info(f"No Elastic IP found with allocation ID {allocation_id}.")
            return None

        try:
            response = self.ec2_client.associate_address(
                AllocationId=allocation_id, InstanceId=instance_id
            )
            elastic_ip.instance_id = (
                instance_id  # Track the instance associated with this Elastic IP.
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidInstanceID.NotFound":
                logger.error(
                    f"Failed to associate Elastic IP {allocation_id} with {instance_id} "
                    "because the specified instance ID does not exist or has not propagated fully. "
                    "Verify the instance ID and try again, or wait a few moments before attempting to "
                    "associate the Elastic IP address."
                )
            raise
        return response
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [AssociateAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/AssociateAddress)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
# Associates an Elastic IP address with an Amazon Elastic Compute Cloud
# (Amazon EC2) instance.
#
# Prerequisites:
#
# - The allocation ID corresponding to the Elastic IP address.
# - The Amazon EC2 instance.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param allocation_id [String] The ID of the allocation corresponding to
#   the Elastic IP address.
# @param instance_id [String] The ID of the instance.
# @return [String] The assocation ID corresponding to the association of the
#   Elastic IP address to the instance.
# @example
#   puts allocate_elastic_ip_address(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'eipalloc-04452e528a66279EX',
#     'i-033c48ef067af3dEX')
def associate_elastic_ip_address_with_instance(
  ec2_client,
  allocation_id,
  instance_id
)
  response = ec2_client.associate_address(
    allocation_id: allocation_id,
    instance_id: instance_id
  )
  response.association_id
rescue StandardError => e
  puts "Error associating Elastic IP address with instance: #{e.message}"
  'Error'
end
```
+  API 세부 정보는 *AWS SDK for Ruby  API 참조*의 [AssociateAddress](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/AssociateAddress)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn associate_ip_address(
        &self,
        allocation_id: &str,
        instance_id: &str,
    ) -> Result<AssociateAddressOutput, EC2Error> {
        let response = self
            .client
            .associate_address()
            .allocation_id(allocation_id)
            .instance_id(instance_id)
            .send()
            .await?;
        Ok(response)
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [AssociateAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.associate_address)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->associateaddress(                         " oo_result is returned for testing purposes. "
            iv_allocationid = iv_allocation_id
            iv_instanceid = iv_instance_id ).
        MESSAGE 'Associated an Elastic IP address with an EC2 instance.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [AssociateAddress](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Associate the specified allocated Elastic IP to a given instance.
    /// 
    /// - Parameters:
    ///   - instanceId: The instance to associate the Elastic IP with.
    ///   - allocationId: The ID of the allocated Elastic IP to associate with
    ///     the instance.
    ///
    /// - Returns: The association ID of the association.
    func associateAddress(instanceId: String?, allocationId: String?) async -> String? {
        do {
            let output = try await ec2Client.associateAddress(
                input: AssociateAddressInput(
                    allocationId: allocationId,
                    instanceId: instanceId
                )
            )

            return output.associationId
        } catch {
            print("*** Unable to associate the IP address: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [AssociateAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/associateaddress(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `AssociateDhcpOptions` 사용
<a name="example_ec2_AssociateDhcpOptions_section"></a>

다음 코드 예시는 `AssociateDhcpOptions`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPC와 DHCP 옵션 세트 연결**  
이 예시에서는 지정된 DHCP 옵션 세트를 지정된 VPC와 연결합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 associate-dhcp-options --dhcp-options-id dopt-d9070ebb --vpc-id vpc-a01106c2
```
**VPC와 기본 DHCP 옵션 세트 연결**  
이 예시에서는 기본 DHCP 옵션 설정을 지정된 VPC와 연결합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 associate-dhcp-options --dhcp-options-id default --vpc-id vpc-a01106c2
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AssociateDhcpOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-dhcp-options.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 DHCP 옵션 세트를 지정된 VPC와 연결합니다.**  

```
Register-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d -VpcId vpc-12345678
```
**예제 2: 이 예제에서는 기본 DHCP 옵션 세트를 지정된 VPC와 연결합니다.**  

```
Register-EC2DhcpOption -DhcpOptionsId default -VpcId vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AssociateDhcpOptions](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 DHCP 옵션 세트를 지정된 VPC와 연결합니다.**  

```
Register-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d -VpcId vpc-12345678
```
**예제 2: 이 예제에서는 기본 DHCP 옵션 세트를 지정된 VPC와 연결합니다.**  

```
Register-EC2DhcpOption -DhcpOptionsId default -VpcId vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AssociateDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `AssociateRouteTable` 사용
<a name="example_ec2_AssociateRouteTable_section"></a>

다음 코드 예시는 `AssociateRouteTable`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**서브넷에 라우팅 테이블 연결**  
이 예시에서는 지정된 라우팅 테이블을 지정된 서브넷과 연결합니다.  
명령:  

```
aws ec2 associate-route-table --route-table-id rtb-22574640 --subnet-id subnet-9d4a7b6c
```
출력:  

```
{
    "AssociationId": "rtbassoc-781d0d1a"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AssociateRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-route-table.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블을 지정된 서브넷과 연결합니다.**  

```
Register-EC2RouteTable -RouteTableId rtb-1a2b3c4d -SubnetId subnet-1a2b3c4d
```
**출력:**  

```
rtbassoc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AssociateRouteTable](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블을 지정된 서브넷과 연결합니다.**  

```
Register-EC2RouteTable -RouteTableId rtb-1a2b3c4d -SubnetId subnet-1a2b3c4d
```
**출력:**  

```
rtbassoc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AssociateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `AttachInternetGateway` 사용
<a name="example_ec2_AttachInternetGateway_section"></a>

다음 코드 예시는 `AttachInternetGateway`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**VPC에 인터넷 게이트웨이 연결**  
다음 `attach-internet-gateway` 예시에서는 지정된 인터넷 게이트웨이를 특정 VPC에 연결합니다.  

```
aws ec2 attach-internet-gateway \
    --internet-gateway-id igw-0d0fb496b3EXAMPLE \
    --vpc-id vpc-0a60eb65b4EXAMPLE
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *Amazon VPC 사용 설명서*의 [인터넷 게이트웨이](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AttachInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-internet-gateway.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인터넷 게이트웨이를 특정 VPC에 연결합니다.**  

```
Add-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
**예제 2: 이 예제에서는 VPC와 인터넷 게이트웨이를 생성한 다음 인터넷 게이트웨이를 VPC에 연결합니다.**  

```
$vpc = New-EC2Vpc -CidrBlock 10.0.0.0/16
New-EC2InternetGateway | Add-EC2InternetGateway -VpcId $vpc.VpcId
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AttachInternetGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인터넷 게이트웨이를 특정 VPC에 연결합니다.**  

```
Add-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
**예제 2: 이 예제에서는 VPC와 인터넷 게이트웨이를 생성한 다음 인터넷 게이트웨이를 VPC에 연결합니다.**  

```
$vpc = New-EC2Vpc -CidrBlock 10.0.0.0/16
New-EC2InternetGateway | Add-EC2InternetGateway -VpcId $vpc.VpcId
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AttachInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `AttachNetworkInterface` 사용
<a name="example_ec2_AttachNetworkInterface_section"></a>

다음 코드 예시는 `AttachNetworkInterface`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 인스턴스에 네트워크 인터페이스 연결**  
다음 `attach-network-interface` 예시에서는 지정된 네트워크 인터페이스를 지정된 인스턴스에 연결합니다.  

```
aws ec2 attach-network-interface \
    --network-interface-id eni-0dc56a8d4640ad10a \
    --instance-id i-1234567890abcdef0 \
    --device-index 1
```
출력:  

```
{
    "AttachmentId": "eni-attach-01a8fc87363f07cf9"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [탄력적 네트워크 인터페이스](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html)를 참조하세요.  
**예시 2: 여러 네트워크 카드가 있는 인스턴스에 네트워크 인터페이스 연결**  
다음 `attach-network-interface` 예시에서는 지정된 네트워크 인터페이스를 지정된 인스턴스 및 네트워크 카드에 연결합니다.  

```
aws ec2 attach-network-interface \
    --network-interface-id eni-07483b1897541ad83 \
    --instance-id i-01234567890abcdef \
    --network-card-index 1 \
    --device-index 1
```
출력:  

```
{
    "AttachmentId": "eni-attach-0fbd7ee87a88cd06c"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [탄력적 네트워크 인터페이스](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AttachNetworkInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-network-interface.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1 : 이 예제에서는 지정된 네트워크 인터페이스를 지정된 인스턴스에 연결합니다.**  

```
Add-EC2NetworkInterface -NetworkInterfaceId eni-12345678 -InstanceId i-1a2b3c4d -DeviceIndex 1
```
**출력:**  

```
eni-attach-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AttachNetworkInterface](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1 : 이 예제에서는 지정된 네트워크 인터페이스를 지정된 인스턴스에 연결합니다.**  

```
Add-EC2NetworkInterface -NetworkInterfaceId eni-12345678 -InstanceId i-1a2b3c4d -DeviceIndex 1
```
**출력:**  

```
eni-attach-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AttachNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `AttachVolume` 사용
<a name="example_ec2_AttachVolume_section"></a>

다음 코드 예시는 `AttachVolume`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스에 볼륨 연결**  
이 예시에서는 볼륨(`vol-1234567890abcdef0`)을 인스턴스(`i-01474ef662b89480`)에 `/dev/sdf`로 첨부합니다.  
명령:  

```
aws ec2 attach-volume --volume-id vol-1234567890abcdef0 --instance-id i-01474ef662b89480 --device /dev/sdf
```
출력:  

```
{
    "AttachTime": "YYYY-MM-DDTHH:MM:SS.000Z",
    "InstanceId": "i-01474ef662b89480",
    "VolumeId": "vol-1234567890abcdef0",
    "State": "attaching",
    "Device": "/dev/sdf"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AttachVolume](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-volume.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 볼륨을 지정된 인스턴스에 연결하고 지정된 디바이스 이름으로 노출합니다.**  

```
Add-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
**출력:**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : attaching
VolumeId            : vol-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AttachVolume](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 볼륨을 지정된 인스턴스에 연결하고 지정된 디바이스 이름으로 노출합니다.**  

```
Add-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
**출력:**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : attaching
VolumeId            : vol-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AttachVolume](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `AttachVpnGateway` 사용
<a name="example_ec2_AttachVpnGateway_section"></a>

다음 코드 예시는 `AttachVpnGateway`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPC에 가상 프라이빗 게이트웨이 연결**  
다음 `attach-vpn-gateway` 예시에서는 지정된 가상 프라이빗 게이트웨이를 지정된 VPC에 연결합니다.  

```
aws ec2 attach-vpn-gateway \
    --vpn-gateway-id vgw-9a4cacf3 \
    --vpc-id vpc-a01106c2
```
출력:  

```
{
    "VpcAttachment": {
        "State": "attaching",
        "VpcId": "vpc-a01106c2"
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AttachVpnGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-vpn-gateway.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 지정된 VPC에 연결합니다.**  

```
Add-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
**출력:**  

```
State        VpcId
-----        -----
attaching    vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AttachVpnGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 지정된 VPC에 연결합니다.**  

```
Add-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
**출력:**  

```
State        VpcId
-----        -----
attaching    vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AttachVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `AuthorizeSecurityGroupEgress` 사용
<a name="example_ec2_AuthorizeSecurityGroupEgress_section"></a>

다음 코드 예시는 `AuthorizeSecurityGroupEgress`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 아웃바운드 트래픽을 특정 주소 범위로 허용하는 규칙 추가**  
다음 `authorize-security-group-egress` 예제에서는 TCP 포트 80에서 지정된 주소 범위에 대한 액세스 권한을 부여하는 규칙을 추가합니다.  

```
aws ec2 authorize-security-group-egress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=80,ToPort=80,IpRanges=[{CidrIp=10.0.0.0/16}]'
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0b15794cdb17bf29c",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": true,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "CidrIpv4": "10.0.0.0/16"
        }
    ]
}
```
**예제 2: 특정 보안 그룹에 아웃바운드 트래픽을 허용하는 규칙 추가**  
다음 `authorize-security-group-egress` 예제에서는 TCP 포트 80에서 지정된 보안 그룹에 대한 액세스 권한을 부여하는 규칙을 추가합니다.  

```
aws ec2 authorize-security-group-egress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=80,ToPort=80,UserIdGroupPairs=[{GroupId=sg-0aad1c26bbeec5c22}]'
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0b5dd815afcea9cc3",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": true,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "ReferencedGroupInfo": {
                "GroupId": "sg-0aad1c26bbeec5c22",
                "UserId": "123456789012"
            }
        }
    ]
}
```
자세한 내용을 알아보려면 *Amazon VPC 사용 설명서*의 [보안 그룹](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [AuthorizeSecurityGroupEgress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/authorize-security-group-egress.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 EC2-VPC에 지정된 보안 그룹에 대한 송신 규칙을 정의합니다. 이 규칙은 지정된 IP 주소 범위에 대해 TCP 포트 80 액세스 권한을 부여합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**예제 2: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**예제 3: 이 예제에서는 지정된 소스 보안 그룹에 대해 TCP 포트 80 액세스 권한을 부여합니다.**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AuthorizeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 EC2-VPC에 지정된 보안 그룹에 대한 송신 규칙을 정의합니다. 이 규칙은 지정된 IP 주소 범위에 대해 TCP 포트 80 액세스 권한을 부여합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**예제 2: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**예제 3: 이 예제에서는 지정된 소스 보안 그룹에 대해 TCP 포트 80 액세스 권한을 부여합니다.**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AuthorizeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `AuthorizeSecurityGroupIngress` 함께 사용
<a name="example_ec2_AuthorizeSecurityGroupIngress_section"></a>

다음 코드 예시는 `AuthorizeSecurityGroupIngress`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Authorize the local computer ingress to EC2 instances associated
    /// with the virtual private cloud (VPC) security group.
    /// </summary>
    /// <param name="groupName">The name of the security group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AuthorizeSecurityGroupIngress(string groupName)
    {
        try
        {
            // Get the IP address for the local computer.
            var ipAddress = await GetIpAddress();
            Console.WriteLine($"Your IP address is: {ipAddress}");
            var ipRanges =
                new List<IpRange> { new IpRange { CidrIp = $"{ipAddress}/32" } };
            var permission = new IpPermission
            {
                Ipv4Ranges = ipRanges,
                IpProtocol = "tcp",
                FromPort = 22,
                ToPort = 22
            };
            var permissions = new List<IpPermission> { permission };
            var response = await _amazonEC2.AuthorizeSecurityGroupIngressAsync(
                new AuthorizeSecurityGroupIngressRequest(groupName, permissions));
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidPermission.Duplicate")
            {
                _logger.LogError(
                    $"The ingress rule already exists. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while authorizing ingress.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Authorize the local computer for ingress to
    /// the Amazon EC2 SecurityGroup.
    /// </summary>
    /// <returns>The IPv4 address of the computer running the scenario.</returns>
    private static async Task<string> GetIpAddress()
    {
        var httpClient = new HttpClient();
        var ipString = await httpClient.GetStringAsync("https://checkip.amazonaws.com");

        // The IP address is returned with a new line
        // character on the end. Trim off the whitespace and
        // return the value to the caller.
        return ipString.Trim();
    }
```
+  API 세부 정보는 *AWS SDK for .NET  API 참조*의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/AuthorizeSecurityGroupIngress)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_authorize_security_group_ingress
#
# This function authorizes an ingress rule for an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Parameters:
#       -g security_group_id - The ID of the security group.
#       -i ip_address - The IP address or CIDR block to authorize.
#       -p protocol - The protocol to authorize (e.g., tcp, udp, icmp).
#       -f from_port - The start of the port range to authorize.
#       -t to_port - The end of the port range to authorize.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_authorize_security_group_ingress() {
  local security_group_id ip_address protocol from_port to_port response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_authorize_security_group_ingress"
    echo "Authorizes an ingress rule for an Amazon Elastic Compute Cloud (Amazon EC2) security group."
    echo "  -g security_group_id - The ID of the security group."
    echo "  -i ip_address - The IP address or CIDR block to authorize."
    echo "  -p protocol - The protocol to authorize (e.g., tcp, udp, icmp)."
    echo "  -f from_port - The start of the port range to authorize."
    echo "  -t to_port - The end of the port range to authorize."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "g:i:p:f:t:h" option; do
    case "${option}" in
      g) security_group_id="${OPTARG}" ;;
      i) ip_address="${OPTARG}" ;;
      p) protocol="${OPTARG}" ;;
      f) from_port="${OPTARG}" ;;
      t) to_port="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$security_group_id" ]]; then
    errecho "ERROR: You must provide a security group ID with the -g parameter."
    usage
    return 1
  fi

  if [[ -z "$ip_address" ]]; then
    errecho "ERROR: You must provide an IP address or CIDR block with the -i parameter."
    usage
    return 1
  fi

  if [[ -z "$protocol" ]]; then
    errecho "ERROR: You must provide a protocol with the -p parameter."
    usage
    return 1
  fi

  if [[ -z "$from_port" ]]; then
    errecho "ERROR: You must provide a start port with the -f parameter."
    usage
    return 1
  fi

  if [[ -z "$to_port" ]]; then
    errecho "ERROR: You must provide an end port with the -t parameter."
    usage
    return 1
  fi

  response=$(aws ec2 authorize-security-group-ingress \
    --group-id "$security_group_id" \
    --cidr "${ip_address}/32" \
    --protocol "$protocol" \
    --port "$from_port-$to_port" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports authorize-security-group-ingress operation failed.$response"
    return 1
  }

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AuthorizeSecurityGroupIngress)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Authorize ingress to an Amazon Elastic Compute Cloud (Amazon EC2) group.
/*!
  \param groupID: The EC2 group ID.
  \param clientConfiguration: The ClientConfiguration object.
  \return bool: True if the operation was successful, false otherwise.
 */
bool
AwsDoc::EC2::authorizeSecurityGroupIngress(const Aws::String &groupID,
                                           const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest;
    authorizeSecurityGroupIngressRequest.SetGroupId(groupID);
    buildSampleIngressRule(authorizeSecurityGroupIngressRequest);

    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;
    }

    return authorizeSecurityGroupIngressOutcome.IsSuccess();
}
```
수신 규칙을 빌드하는 유틸리티 함수입니다.  

```
//! Build a sample ingress rule.
/*!
  \param authorize_request: An 'AuthorizeSecurityGroupIngressRequest' instance.
  \return void:
 */
void buildSampleIngressRule(
        Aws::EC2::Model::AuthorizeSecurityGroupIngressRequest &authorize_request) {
    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);
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1  API 참조*의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/AuthorizeSecurityGroupIngress)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 인바운드 SSH 트래픽을 허용하는 규칙을 추가하는 방법**  
다음 `authorize-security-group-ingress` 예제에서는 TCP 포트 22(SSH)의 인바운드 트래픽을 허용하는 규칙을 추가합니다.  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --protocol tcp \
    --port 22 \
    --cidr 203.0.113.0/24
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-01afa97ef3e1bedfc",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 22,
            "ToPort": 22,
            "CidrIpv4": "203.0.113.0/24"
        }
    ]
}
```
**예제 2: 다른 보안 그룹의 인바운드 HTTP 트래픽을 허용하는 규칙을 추가하는 방법**  
다음 `authorize-security-group-ingress` 예제에서는 소스 보안 그룹 `sg-1a2b3c4d`에서 TCP 포트 80의 인바운드 액세스를 허용하는 규칙을 추가합니다. 보안 그룹은 동일한 VPC 또는 피어 VPC에 있어야 합니다(VPC 피어링 연결이 필요함). 유입 트래픽은 퍼블릭 IP 주소 또는 탄력적 IP 주소가 아닌 소스 보안 그룹과 연결된 인스턴스의 프라이빗 IP 주소를 기반으로 허용됩니다.  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --protocol tcp \
    --port 80 \
    --source-group sg-1a2b3c4d
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-01f4be99110f638a7",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "ReferencedGroupInfo": {
                "GroupId": "sg-1a2b3c4d",
                "UserId": "123456789012"
            }
        }
    ]
}
```
**예제 3: 동일한 직접 호출에서 여러 규칙을 추가하는 방법**  
다음 `authorize-security-group-ingress` 예제에서는 `ip-permissions` 파라미터를 사용하여 TCP 포트 3389(RDP)의 인바운드 액세스를 허용하는 하나의 인바운드 규칙과 Ping/ICMP를 허용하는 다른 인바운드 규칙(총 2개)을 추가합니다.  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=3389,ToPort=3389,IpRanges=[{CidrIp=172.31.0.0/16}]' 'IpProtocol=icmp,FromPort=-1,ToPort=-1,IpRanges=[{CidrIp=172.31.0.0/16}]'
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-00e06e5d3690f29f3",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 3389,
            "ToPort": 3389,
            "CidrIpv4": "172.31.0.0/16"
        },
        {
            "SecurityGroupRuleId": "sgr-0a133dd4493944b87",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": -1,
            "ToPort": -1,
            "CidrIpv4": "172.31.0.0/16"
        }
    ]
}
```
**예제 4: ICMP 트래픽에 대한 규칙을 추가하는 방법**  
다음 `authorize-security-group-ingress` 예제에서는 `ip-permissions` 파라미터를 사용하여 어디서나 ICMP 메시지 `Destination Unreachable: Fragmentation Needed and Don't Fragment was Set`(유형 3, 코드 4)를 허용하는 인바운드 규칙을 추가합니다.  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=icmp,FromPort=3,ToPort=4,IpRanges=[{CidrIp=0.0.0.0/0}]'
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0de3811019069b787",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "icmp",
            "FromPort": 3,
            "ToPort": 4,
            "CidrIpv4": "0.0.0.0/0"
        }
    ]
}
```
**예제 5: IPv6 트래픽에 대한 규칙을 추가하는 방법**  
다음 `authorize-security-group-ingress` 예제에서는 `ip-permissions` 파라미터를 사용하여 IPv6 범위 `2001:db8:1234:1a00::/64`에서 SSH 액세스(포트 22)를 허용하는 인바운드 규칙을 추가합니다.  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=22,ToPort=22,Ipv6Ranges=[{CidrIpv6=2001:db8:1234:1a00::/64}]'
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0455bc68b60805563",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 22,
            "ToPort": 22,
            "CidrIpv6": "2001:db8:1234:1a00::/64"
        }
    ]
}
```
**예제 6: ICMPv6 트래픽에 대한 규칙을 추가하는 방법**  
다음 `authorize-security-group-ingress` 예제에서는 `ip-permissions` 파라미터를 사용하여 어디서나 ICMPv6 트래픽을 허용하는 인바운드 규칙을 추가합니다.  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=icmpv6,Ipv6Ranges=[{CidrIpv6=::/0}]'
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-04b612d9363ab6327",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "icmpv6",
            "FromPort": -1,
            "ToPort": -1,
            "CidrIpv6": "::/0"
        }
    ]
}
```
**예제 7: 설명이 포함된 규칙 추가**  
다음 `authorize-security-group-ingress` 예제에서는 `ip-permissions` 파라미터를 사용하여 지정된 IPv4 주소 범위에서 RDP 트래픽을 허용하는 인바운드 규칙을 추가합니다. 이 규칙에는 나중에 식별하는 데 도움이 되는 설명이 포함됩니다.  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=3389,ToPort=3389,IpRanges=[{CidrIp=203.0.113.0/24,Description='RDP access from NY office'}]'
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0397bbcc01e974db3",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 3389,
            "ToPort": 3389,
            "CidrIpv4": "203.0.113.0/24",
            "Description": "RDP access from NY office"
        }
    ]
}
```
**예제 8: 접두사 목록을 사용하는 인바운드 규칙을 추가하는 방법**  
다음 `authorize-security-group-ingress` 예제에서는 `ip-permissions` 파라미터를 사용하여 지정된 접두사 목록에 있는 CIDR 범위의 모든 트래픽을 허용하는 인바운드 규칙을 추가합니다.  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-04a351bfe432d4e71 \
    --ip-permissions 'IpProtocol=all,PrefixListIds=[{PrefixListId=pl-002dc3ec097de1514}]'
```
출력:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-09c74b32f677c6c7c",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "-1",
            "FromPort": -1,
            "ToPort": -1,
            "PrefixListId": "pl-0721453c7ac4ec009"
        }
    ]
}
```
자세한 내용을 알아보려면 *Amazon VPC 사용 설명서*의 [보안 그룹](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [AuthorizeSecurityGroupIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/authorize-security-group-ingress.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Creates a new security group asynchronously with the specified group name, description, and VPC ID. It also
     * authorizes inbound traffic on ports 80 and 22 from the specified IP address.
     *
     * @param groupName    the name of the security group to create
     * @param groupDesc    the description of the security group
     * @param vpcId        the ID of the VPC in which to create the security group
     * @param myIpAddress  the IP address from which to allow inbound traffic (e.g., "192.168.1.1/0" to allow traffic from
     *                     any IP address in the 192.168.1.0/24 subnet)
     * @return a CompletableFuture that, when completed, returns the ID of the created security group
     * @throws RuntimeException if there was a failure creating the security group or authorizing the inbound traffic
     */
    public CompletableFuture<String> createSecurityGroupAsync(String groupName, String groupDesc, String vpcId, String myIpAddress) {
        CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder()
            .groupName(groupName)
            .description(groupDesc)
            .vpcId(vpcId)
            .build();

        return getAsyncClient().createSecurityGroup(createRequest)
            .thenCompose(createResponse -> {
                String groupId = createResponse.groupId();
                IpRange ipRange = IpRange.builder()
                    .cidrIp(myIpAddress + "/32")
                    .build();

                IpPermission ipPerm = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(80)
                    .fromPort(80)
                    .ipRanges(ipRange)
                    .build();

                IpPermission ipPerm2 = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(22)
                    .fromPort(22)
                    .ipRanges(ipRange)
                    .build();

                AuthorizeSecurityGroupIngressRequest authRequest = AuthorizeSecurityGroupIngressRequest.builder()
                    .groupName(groupName)
                    .ipPermissions(ipPerm, ipPerm2)
                    .build();

                return getAsyncClient().authorizeSecurityGroupIngress(authRequest)
                    .thenApply(authResponse -> groupId);
            })
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    if (exception instanceof CompletionException && exception.getCause() instanceof Ec2Exception) {
                        throw (Ec2Exception) exception.getCause();
                    } else {
                        throw new RuntimeException("Failed to create security group: " + exception.getMessage(), exception);
                    }
                }
            });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x  API 참조*의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/AuthorizeSecurityGroupIngress)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import {
  AuthorizeSecurityGroupIngressCommand,
  EC2Client,
} from "@aws-sdk/client-ec2";

/**
 * Adds the specified inbound (ingress) rules to a security group.
 * @param {{ groupId: string, ipAddress: string }} options
 */
export const main = async ({ groupId, ipAddress }) => {
  const client = new EC2Client({});
  const command = new AuthorizeSecurityGroupIngressCommand({
    // Use a group ID from the AWS console or
    // the DescribeSecurityGroupsCommand.
    GroupId: groupId,
    IpPermissions: [
      {
        IpProtocol: "tcp",
        FromPort: 22,
        ToPort: 22,
        // The IP address to authorize.
        // For more information on this notation, see
        // https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation
        IpRanges: [{ CidrIp: `${ipAddress}/32` }],
      },
    ],
  });

  try {
    const { SecurityGroupRules } = await client.send(command);
    console.log(JSON.stringify(SecurityGroupRules, null, 2));
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidGroupId.Malformed") {
      console.warn(`${caught.message}. Please provide a valid GroupId.`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript  API 참조*의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/AuthorizeSecurityGroupIngressCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun createEC2SecurityGroupSc(
    groupNameVal: String?,
    groupDescVal: String?,
    vpcIdVal: String?,
    myIpAddress: String?,
): String? {
    val request =
        CreateSecurityGroupRequest {
            groupName = groupNameVal
            description = groupDescVal
            vpcId = vpcIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val resp = ec2.createSecurityGroup(request)
        val ipRange =
            IpRange {
                cidrIp = "$myIpAddress/0"
            }

        val ipPerm =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 80
                fromPort = 80
                ipRanges = listOf(ipRange)
            }

        val ipPerm2 =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 22
                fromPort = 22
                ipRanges = listOf(ipRange)
            }

        val authRequest =
            AuthorizeSecurityGroupIngressRequest {
                groupName = groupNameVal
                ipPermissions = listOf(ipPerm, ipPerm2)
            }
        ec2.authorizeSecurityGroupIngress(authRequest)
        println("Successfully added ingress policy to Security Group $groupNameVal")
        return resp.groupId
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [AuthorizeSecurityGroupIngress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 EC2-VPC의 보안 그룹에 대한 수신 규칙을 정의합니다. 이러한 규칙은 특정 IP 주소에 대해 SSH(포트 22) 및 RDC(포트 3389) 액세스 권한을 부여합니다. 보안 그룹 이름이 아닌 보안 그룹 ID를 사용하여 EC2-VPC의 보안 그룹을 식별해야 한다는 점에 유의하세요. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**예제 2: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip1 = New-Object Amazon.EC2.Model.IpPermission
$ip1.IpProtocol = "tcp"
$ip1.FromPort = 22
$ip1.ToPort = 22
$ip1.IpRanges.Add("203.0.113.25/32")

$ip2 = new-object Amazon.EC2.Model.IpPermission
$ip2.IpProtocol = "tcp"
$ip2.FromPort = 3389
$ip2.ToPort = 3389
$ip2.IpRanges.Add("203.0.113.25/32")

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**예제 3: 이 예제에서는 EC2-Classic의 보안 그룹에 대한 수신 규칙을 정의합니다. 이러한 규칙은 특정 IP 주소에 대해 SSH(포트 22) 및 RDC(포트 3389) 액세스 권한을 부여합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**예제 4: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip1 = New-Object Amazon.EC2.Model.IpPermission
$ip1.IpProtocol = "tcp"
$ip1.FromPort = 22
$ip1.ToPort = 22
$ip1.IpRanges.Add("203.0.113.25/32")

$ip2 = new-object Amazon.EC2.Model.IpPermission
$ip2.IpProtocol = "tcp"
$ip2.FromPort = 3389
$ip2.ToPort = 3389
$ip2.IpRanges.Add("203.0.113.25/32")

Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**예제 5: 이 예제에서는 지정된 소스 보안 그룹(sg-1a2b3c4d)에서 지정된 보안 그룹(sg-12345678)으로의 TCP 포트 8081 액세스 권한을 부여합니다.**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="8081"; ToPort="8081"; UserIdGroupPairs=$ug } )
```
**예제 6: 이 예제에서는 설명이 포함된 TCP 포트 22 트래픽에 대한 보안 그룹 sg-1234abcd의 수신 규칙에 CIDR 5.5.5.5/32를 추가합니다.**  

```
$IpRange = New-Object -TypeName Amazon.EC2.Model.IpRange
$IpRange.CidrIp = "5.5.5.5/32"
$IpRange.Description = "SSH from Office"
$IpPermission = New-Object Amazon.EC2.Model.IpPermission
$IpPermission.IpProtocol = "tcp"
$IpPermission.ToPort = 22
$IpPermission.FromPort = 22
$IpPermission.Ipv4Ranges = $IpRange
Grant-EC2SecurityGroupIngress -GroupId sg-1234abcd -IpPermission $IpPermission
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 EC2-VPC의 보안 그룹에 대한 수신 규칙을 정의합니다. 이러한 규칙은 특정 IP 주소에 대해 SSH(포트 22) 및 RDC(포트 3389) 액세스 권한을 부여합니다. 보안 그룹 이름이 아닌 보안 그룹 ID를 사용하여 EC2-VPC의 보안 그룹을 식별해야 한다는 점에 유의하세요. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**예제 2: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip1 = New-Object Amazon.EC2.Model.IpPermission
$ip1.IpProtocol = "tcp"
$ip1.FromPort = 22
$ip1.ToPort = 22
$ip1.IpRanges.Add("203.0.113.25/32")

$ip2 = new-object Amazon.EC2.Model.IpPermission
$ip2.IpProtocol = "tcp"
$ip2.FromPort = 3389
$ip2.ToPort = 3389
$ip2.IpRanges.Add("203.0.113.25/32")

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**예제 3: 이 예제에서는 EC2-Classic의 보안 그룹에 대한 수신 규칙을 정의합니다. 이러한 규칙은 특정 IP 주소에 대해 SSH(포트 22) 및 RDC(포트 3389) 액세스 권한을 부여합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**예제 4: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip1 = New-Object Amazon.EC2.Model.IpPermission
$ip1.IpProtocol = "tcp"
$ip1.FromPort = 22
$ip1.ToPort = 22
$ip1.IpRanges.Add("203.0.113.25/32")

$ip2 = new-object Amazon.EC2.Model.IpPermission
$ip2.IpProtocol = "tcp"
$ip2.FromPort = 3389
$ip2.ToPort = 3389
$ip2.IpRanges.Add("203.0.113.25/32")

Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**예제 5: 이 예제에서는 지정된 소스 보안 그룹(sg-1a2b3c4d)에서 지정된 보안 그룹(sg-12345678)으로의 TCP 포트 8081 액세스 권한을 부여합니다.**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="8081"; ToPort="8081"; UserIdGroupPairs=$ug } )
```
**예제 6: 이 예제에서는 설명이 포함된 TCP 포트 22 트래픽에 대한 보안 그룹 sg-1234abcd의 수신 규칙에 CIDR 5.5.5.5/32를 추가합니다.**  

```
$IpRange = New-Object -TypeName Amazon.EC2.Model.IpRange
$IpRange.CidrIp = "5.5.5.5/32"
$IpRange.Description = "SSH from Office"
$IpPermission = New-Object Amazon.EC2.Model.IpPermission
$IpPermission.IpProtocol = "tcp"
$IpPermission.ToPort = 22
$IpPermission.FromPort = 22
$IpPermission.Ipv4Ranges = $IpRange
Grant-EC2SecurityGroupIngress -GroupId sg-1234abcd -IpPermission $IpPermission
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class SecurityGroupWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions."""

    def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None):
        """
        Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param security_group: The ID of a security group to manage. This is a high-level identifier
                               that represents the security group.
        """
        self.ec2_client = ec2_client
        self.security_group = security_group

    @classmethod
    def from_client(cls) -> "SecurityGroupWrapper":
        """
        Creates a SecurityGroupWrapper instance with a default EC2 client.

        :return: An instance of SecurityGroupWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def authorize_ingress(self, ssh_ingress_ip: str) -> Optional[Dict[str, Any]]:
        """
        Adds a rule to the security group to allow access to SSH.

        :param ssh_ingress_ip: The IP address that is granted inbound access to connect
                               to port 22 over TCP, used for SSH.
        :return: The response to the authorization request. The 'Return' field of the
                 response indicates whether the request succeeded or failed, or None if no security group is set.
        :raise Handles AWS SDK service-level ClientError, with special handling for ResourceAlreadyExists
        """
        if self.security_group is None:
            logger.info("No security group to update.")
            return None

        try:
            ip_permissions = [
                {
                    # SSH ingress open to only the specified IP address.
                    "IpProtocol": "tcp",
                    "FromPort": 22,
                    "ToPort": 22,
                    "IpRanges": [{"CidrIp": f"{ssh_ingress_ip}/32"}],
                }
            ]
            response = self.ec2_client.authorize_security_group_ingress(
                GroupId=self.security_group, IpPermissions=ip_permissions
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidPermission.Duplicate":
                logger.error(
                    f"The SSH ingress rule for IP {ssh_ingress_ip} already exists"
                    f"in security group '{self.security_group}'."
                )
            raise
        else:
            return response
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/AuthorizeSecurityGroupIngress)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// Add an ingress rule to a security group explicitly allowing IPv4 address
    /// as {ip}/32 over TCP port 22.
    pub async fn authorize_security_group_ssh_ingress(
        &self,
        group_id: &str,
        ingress_ips: Vec<Ipv4Addr>,
    ) -> Result<(), EC2Error> {
        tracing::info!("Authorizing ingress for security group {group_id}");
        self.client
            .authorize_security_group_ingress()
            .group_id(group_id)
            .set_ip_permissions(Some(
                ingress_ips
                    .into_iter()
                    .map(|ip| {
                        IpPermission::builder()
                            .ip_protocol("tcp")
                            .from_port(22)
                            .to_port(22)
                            .ip_ranges(IpRange::builder().cidr_ip(format!("{ip}/32")).build())
                            .build()
                    })
                    .collect(),
            ))
            .send()
            .await?;
        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [AuthorizeSecurityGroupIngress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.authorize_security_group_ingress)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    " Create IP permissions for SSH access (port 22)
    " iv_cidr_ip = '192.0.2.0/24'
    DATA lt_ip_permissions TYPE /aws1/cl_ec2ippermission=>tt_ippermissionlist.
    DATA(lo_ip_permission) = NEW /aws1/cl_ec2ippermission(
      iv_ipprotocol = 'tcp'
      iv_fromport = 22
      iv_toport = 22
      it_ipranges = VALUE /aws1/cl_ec2iprange=>tt_iprangelist(
        ( NEW /aws1/cl_ec2iprange( iv_cidrip = iv_cidr_ip ) )
      )
    ).
    APPEND lo_ip_permission TO lt_ip_permissions.

    TRY.
        oo_result = lo_ec2->authsecuritygroupingress(             " oo_result is returned for testing purposes. "
          iv_groupid = iv_group_id
          it_ippermissions = lt_ip_permissions ).
        MESSAGE 'Authorized ingress rule for security group.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 SDK for SAP ABAP API 참조의 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요. *AWS * 

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Authorize ingress of connections for the security group.
    /// 
    /// - Parameters:
    ///   - groupId: The group ID of the security group to authorize access for.
    ///   - ipAddress: The IP address of the device to grant access to.
    ///
    /// - Returns: `true` if access is successfully granted; otherwise `false`.
    func authorizeSecurityGroupIngress(groupId: String, ipAddress: String) async -> Bool {
        let ipRange = EC2ClientTypes.IpRange(cidrIp: "\(ipAddress)/0")
        let httpPermission = EC2ClientTypes.IpPermission(
            fromPort: 80,
            ipProtocol: "tcp",
            ipRanges: [ipRange],
            toPort: 80
        )

        let sshPermission = EC2ClientTypes.IpPermission(
            fromPort: 22,
            ipProtocol: "tcp",
            ipRanges: [ipRange],
            toPort: 22
        )

        do {
            _ = try await ec2Client.authorizeSecurityGroupIngress(
                input: AuthorizeSecurityGroupIngressInput(
                    groupId: groupId,
                    ipPermissions: [httpPermission, sshPermission]
                )
            )

            return true
        } catch {
            print("*** Error authorizing ingress for the security group: \(error.localizedDescription)")
            return false
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [AuthorizeSecurityGroupIngress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/authorizesecuritygroupingress(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CancelCapacityReservation` 사용
<a name="example_ec2_CancelCapacityReservation_section"></a>

다음 코드 예시는 `CancelCapacityReservation`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**용량 예약 취소**  
다음 `cancel-capacity-reservation` 예시에서는 지정된 용량 예약을 취소합니다.  

```
aws ec2 cancel-capacity-reservation \
    --capacity-reservation-id cr-1234abcd56EXAMPLE
```
출력:  

```
{
    "Return": true
}
```
자세한 내용은 [Amazon EC2 사용 설명서](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-release.html)의 *용량 예약 취소*를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CancelCapacityReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-capacity-reservation.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 용량 예약 cr-0c1f2345db6f7cdba를 취소합니다.**  

```
Remove-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2CapacityReservation (CancelCapacityReservation)" on target "cr-0c1f2345db6f7cdba".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CancelCapacityReservation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 용량 예약 cr-0c1f2345db6f7cdba를 취소합니다.**  

```
Remove-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2CapacityReservation (CancelCapacityReservation)" on target "cr-0c1f2345db6f7cdba".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CancelCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CancelImportTask` 사용
<a name="example_ec2_CancelImportTask_section"></a>

다음 코드 예시는 `CancelImportTask`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**가져오기 태스크 취소**  
다음 `cancel-import-task` 예시에서는 지정된 이미지 가져오기 태스크를 취소합니다.  

```
aws ec2 cancel-import-task \
    --import-task-id import-ami-1234567890abcdef0
```
출력:  

```
{
    "ImportTaskId": "import-ami-1234567890abcdef0",
    "PreviousState": "active",
    "State": "deleting"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CancelImportTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-import-task.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 가져오기 작업(스냅샷 또는 이미지 가져오기)을 취소합니다. 필요한 경우 `-CancelReason` 파라미터를 사용하여 이유를 제공할 수 있습니다.**  

```
Stop-EC2ImportTask -ImportTaskId import-ami-abcdefgh
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CancelImportTask](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 가져오기 작업(스냅샷 또는 이미지 가져오기)을 취소합니다. 필요한 경우 `-CancelReason` 파라미터를 사용하여 이유를 제공할 수 있습니다.**  

```
Stop-EC2ImportTask -ImportTaskId import-ami-abcdefgh
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CancelImportTask](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CancelSpotFleetRequests` 사용
<a name="example_ec2_CancelSpotFleetRequests_section"></a>

다음 코드 예시는 `CancelSpotFleetRequests`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 스팟 플릿 요청을 취소하고 연결된 인스턴스 종료**  
다음 `cancel-spot-fleet-requests` 예시에서는 스팟 플릿 요청을 취소하고 관련된 온디맨드 인스턴스 및 스팟 인스턴스를 종료합니다  

```
aws ec2 cancel-spot-fleet-requests \
    --spot-fleet-request-ids sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE \
    --terminate-instances
```
출력:  

```
{
    "SuccessfulFleetRequests": [
        {
            "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
            "CurrentSpotFleetRequestState": "cancelled_terminating",
            "PreviousSpotFleetRequestState": "active"
        }
    ],
    "UnsuccessfulFleetRequests": []
}
```
**예시 2: 관련 인스턴스를 종료하지 않고 스팟 플릿 요청 취소**  
다음 `cancel-spot-fleet-requests` 예시에서는 연결된 온디맨드 인스턴스 및 스팟 인스턴스를 종료하지 않고 스팟 플릿 요청을 취소합니다.  

```
aws ec2 cancel-spot-fleet-requests \
    --spot-fleet-request-ids sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE \
    --no-terminate-instances
```
출력:  

```
{
    "SuccessfulFleetRequests": [
        {
            "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
            "CurrentSpotFleetRequestState": "cancelled_running",
            "PreviousSpotFleetRequestState": "active"
        }
    ],
    "UnsuccessfulFleetRequests": []
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [스팟 플릿 요청 취소](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/cancel-spot-fleet.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CancelSpotFleetRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-spot-fleet-requests.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 스팟 플릿 요청을 취소하고 연결된 스팟 인스턴스를 종료합니다.**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $true
```
**예제 2: 이 예제에서는 연결된 스팟 인스턴스를 종료하지 않고 지정된 스팟 플릿 요청을 취소합니다.**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CancelSpotFleetRequests](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 스팟 플릿 요청을 취소하고 연결된 스팟 인스턴스를 종료합니다.**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $true
```
**예제 2: 이 예제에서는 연결된 스팟 인스턴스를 종료하지 않고 지정된 스팟 플릿 요청을 취소합니다.**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CancelSpotFleetRequests](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CancelSpotInstanceRequests` 사용
<a name="example_ec2_CancelSpotInstanceRequests_section"></a>

다음 코드 예시는 `CancelSpotInstanceRequests`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스팟 인스턴스 요청 취소**  
이 예시에서는 스팟 인스턴스 요청을 취소합니다.  
명령:  

```
aws ec2 cancel-spot-instance-requests --spot-instance-request-ids sir-08b93456
```
출력:  

```
{
    "CancelledSpotInstanceRequests": [
        {
            "State": "cancelled",
            "SpotInstanceRequestId": "sir-08b93456"
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CancelSpotInstanceRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-spot-instance-requests.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스팟 인스턴스 요청을 취소합니다.**  

```
Stop-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**출력:**  

```
SpotInstanceRequestId    State
---------------------    -----
sir-12345678             cancelled
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CancelSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스팟 인스턴스 요청을 취소합니다.**  

```
Stop-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**출력:**  

```
SpotInstanceRequestId    State
---------------------    -----
sir-12345678             cancelled
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CancelSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ConfirmProductInstance` 사용
<a name="example_ec2_ConfirmProductInstance_section"></a>

다음 코드 예시는 `ConfirmProductInstance`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**제품 인스턴스 확인**  
이 예시에서는 지정된 제품 코드가 지정된 인스턴스와 연관되어 있는지 여부를 확인합니다.  
명령:  

```
aws ec2 confirm-product-instance --product-code 774F4FF8 --instance-id i-1234567890abcdef0
```
출력:  

```
{
  "OwnerId": "123456789012"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ConfirmProductInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/confirm-product-instance.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 제품 코드가 지정된 인스턴스와 연관되어 있는지 여부를 확인합니다.**  

```
Confirm-EC2ProductInstance -ProductCode 774F4FF8 -InstanceId i-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ConfirmProductInstance](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 제품 코드가 지정된 인스턴스와 연관되어 있는지 여부를 확인합니다.**  

```
Confirm-EC2ProductInstance -ProductCode 774F4FF8 -InstanceId i-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ConfirmProductInstance](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CopyImage` 사용
<a name="example_ec2_CopyImage_section"></a>

다음 코드 예시는 `CopyImage`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 다른 리전에 AMI 복사**  
다음 `copy-image` 명령은 지정된 AMI를 `us-west-2` 리전에서 `us-east-1` 리전으로 복사하고 간단한 설명을 추가합니다.  

```
aws ec2 copy-image \
    --region us-east-1 \
    --name ami-name \
    --source-region us-west-2 \
    --source-image-id ami-066877671789bd71b \
    --description "This is my copied image."
```
출력:  

```
{
    "ImageId": "ami-0123456789abcdefg"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [AMI 복사](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html)를 참조하세요.  
**예시 2: 다른 리전에 AMI 복사 및 백업 스냅샷 암호화**  
다음 `copy-image` 명령은 `us-west-2` 리전에서 현재 리전으로 지정한 AMI를 복사하고 지정한 KMS 키를 사용하여 백업 스냅샷을 암호화합니다.  

```
aws ec2 copy-image \
    --source-region us-west-2 \
    --name ami-name \
    --source-image-id ami-066877671789bd71b \
    --encrypted \
    --kms-key-id alias/my-kms-key
```
출력:  

```
{
    "ImageId": "ami-0123456789abcdefg"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [AMI 복사](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html)를 참조하세요.  
**예시 3: AMI를 복사할 때 사용자 정의 AMI 태그 포함**  
다음 `copy-image` 명령은 AMI를 복사할 때 `--copy-image-tags` 파라미터를 사용하여 사용자 정의 AMI 태그를 복사합니다.  

```
aws ec2 copy-image \
    --region us-east-1 \
    --name ami-name \
    --source-region us-west-2 \
    --source-image-id ami-066877671789bd71b \
    --description "This is my copied image."
    --copy-image-tags
```
출력:  

```
{
    "ImageId": "ami-0123456789abcdefg"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [AMI 복사](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CopyImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/copy-image.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 'EU(아일랜드)' 리전의 지정된 AMI를 '미국 서부(오리건)' 리전에 복사합니다. -Region을 지정하지 않으면 현재 기본 리전이 대상 리전으로 사용됩니다.**  

```
Copy-EC2Image -SourceRegion eu-west-1 -SourceImageId ami-12345678 -Region us-west-2 -Name "Copy of ami-12345678"
```
**출력:**  

```
ami-87654321
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CopyImage](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 'EU(아일랜드)' 리전의 지정된 AMI를 '미국 서부(오리건)' 리전에 복사합니다. -Region을 지정하지 않으면 현재 기본 리전이 대상 리전으로 사용됩니다.**  

```
Copy-EC2Image -SourceRegion eu-west-1 -SourceImageId ami-12345678 -Region us-west-2 -Name "Copy of ami-12345678"
```
**출력:**  

```
ami-87654321
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CopyImage](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CopySnapshot` 사용
<a name="example_ec2_CopySnapshot_section"></a>

다음 코드 예시는 `CopySnapshot`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 다른 리전에 스냅샷 복사**  
다음 `copy-snapshot` 예시 명령은 `us-west-2` 리전에서 `us-east-1` 리전으로 지정된 스냅샷을 복사하고 간단한 설명을 추가합니다.  

```
aws ec2 copy-snapshot \
    --region us-east-1 \
    --source-region us-west-2 \
    --source-snapshot-id snap-066877671789bd71b \
    --description 'This is my copied snapshot.'
```
출력:  

```
{
    "SnapshotId": "snap-066877671789bd71b"
}
```
**예시 2: 암호화되지 않은 스냅샷 복사 및 새 스냅샷 암호화**  
다음 `copy-snapshot` 명령은 지정된 암호화되지 않은 스냅샷을 `us-west-2` 리전에서 현재 리전으로 복사하고 지정된 KMS 키를 사용하여 새 스냅샷을 암호화합니다.  

```
aws ec2 copy-snapshot \
    --source-region us-west-2 \
    --source-snapshot-id snap-066877671789bd71b \
    --encrypted \
    --kms-key-id alias/my-kms-key
```
출력:  

```
{
    "SnapshotId": "snap-066877671789bd71b"
}
```
자세한 내용은 *Amazon EBS 사용 설명서*의 [Amazon EBS 스냅샷 복사](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-copy-snapshot.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CopySnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/copy-snapshot.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스냅샷을 EU(아일랜드) 리전에서 미국 서부(오리건) 리전으로 복사합니다.**  

```
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678 -Region us-west-2
```
**예제 2: 기본 리전을 설정하고 Region 파라미터를 생략하면 기본 대상 리전이 기본 리전이 됩니다.**  

```
Set-DefaultAWSRegion us-west-2
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CopySnapshot](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스냅샷을 EU(아일랜드) 리전에서 미국 서부(오리건) 리전으로 복사합니다.**  

```
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678 -Region us-west-2
```
**예제 2: 기본 리전을 설정하고 Region 파라미터를 생략하면 기본 대상 리전이 기본 리전이 됩니다.**  

```
Set-DefaultAWSRegion us-west-2
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CopySnapshot](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateCapacityReservation` 사용
<a name="example_ec2_CreateCapacityReservation_section"></a>

다음 코드 예시는 `CreateCapacityReservation`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 용량 예약 생성**  
다음 `create-capacity-reservation` 예시에서는 `eu-west-1a` 가용 영역에 용량 예약을 생성하여 Linux/Unix 운영 체제를 실행하는 `t2.medium` 인스턴스 3개를 시작할 수 있습니다. 기본적으로 용량 예약은 오픈 인스턴스 매칭 기준으로 생성되며 임시 스토리지는 지원되지 않으며, 수동으로 취소할 때까지 활성 상태로 유지됩니다.  

```
aws ec2 create-capacity-reservation \
    --availability-zone eu-west-1a \
    --instance-type t2.medium \
    --instance-platform Linux/UNIX \
    --instance-count 3
```
출력:  

```
{
    "CapacityReservation": {
        "CapacityReservationId": "cr-1234abcd56EXAMPLE ",
        "EndDateType": "unlimited",
        "AvailabilityZone": "eu-west-1a",
        "InstanceMatchCriteria": "open",
        "EphemeralStorage": false,
        "CreateDate": "2019-08-16T09:27:35.000Z",
        "AvailableInstanceCount": 3,
        "InstancePlatform": "Linux/UNIX",
        "TotalInstanceCount": 3,
        "State": "active",
        "Tenancy": "default",
        "EbsOptimized": false,
        "InstanceType": "t2.medium"
    }
}
```
**예시 2: 지정된 날짜/시간에 자동으로 종료되는 용량 예약 생성**  
다음 `create-capacity-reservation` 예시에서는 `eu-west-1a` 가용 영역에 용량 예약을 생성하여 Linux/Unix 운영 체제를 실행하는 `m5.large` 인스턴스 3개를 시작할 수 있습니다. 이 용량 예약은 2019/8/31 23:59:59에 자동으로 종료됩니다.  

```
aws ec2 create-capacity-reservation \
    --availability-zone eu-west-1a \
    --instance-type m5.large \
    --instance-platform Linux/UNIX \
    --instance-count 3 \
    --end-date-type limited \
    --end-date 2019-08-31T23:59:59Z
```
출력:  

```
{
    "CapacityReservation": {
        "CapacityReservationId": "cr-1234abcd56EXAMPLE ",
        "EndDateType": "limited",
        "AvailabilityZone": "eu-west-1a",
        "EndDate": "2019-08-31T23:59:59.000Z",
        "InstanceMatchCriteria": "open",
        "EphemeralStorage": false,
        "CreateDate": "2019-08-16T10:15:53.000Z",
        "AvailableInstanceCount": 3,
        "InstancePlatform": "Linux/UNIX",
        "TotalInstanceCount": 3,
        "State": "active",
        "Tenancy": "default",
        "EbsOptimized": false,
        "InstanceType": "m5.large"
    }
}
```
**예시 3: 대상 인스턴스 시작만 허용하는 용량 예약 생성**  
다음 `create-capacity-reservation` 예시에서는 대상 인스턴스 시작만 허용하는 용량 예약을 생성합니다.  

```
aws ec2 create-capacity-reservation \
    --availability-zone eu-west-1a \
    --instance-type m5.large \
    --instance-platform Linux/UNIX \
    --instance-count 3 \
    --instance-match-criteria targeted
```
출력:  

```
{
    "CapacityReservation": {
        "CapacityReservationId": "cr-1234abcd56EXAMPLE ",
        "EndDateType": "unlimited",
        "AvailabilityZone": "eu-west-1a",
        "InstanceMatchCriteria": "targeted",
        "EphemeralStorage": false,
        "CreateDate": "2019-08-16T10:21:57.000Z",
        "AvailableInstanceCount": 3,
        "InstancePlatform": "Linux/UNIX",
        "TotalInstanceCount": 3,
        "State": "active",
        "Tenancy": "default",
        "EbsOptimized": false,
        "InstanceType": "m5.large"
    }
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [용량 예약 생성](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateCapacityReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-capacity-reservation.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 속성을 사용하여 새 용량 예약을 생성합니다.**  

```
Add-EC2CapacityReservation -InstanceType m4.xlarge -InstanceCount 2 -AvailabilityZone eu-west-1b -EbsOptimized True -InstancePlatform Windows
```
**출력:**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateCapacityReservation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 속성을 사용하여 새 용량 예약을 생성합니다.**  

```
Add-EC2CapacityReservation -InstanceType m4.xlarge -InstanceCount 2 -AvailabilityZone eu-west-1b -EbsOptimized True -InstancePlatform Windows
```
**출력:**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateCustomerGateway` 사용
<a name="example_ec2_CreateCustomerGateway_section"></a>

다음 코드 예시는 `CreateCustomerGateway`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**고객 게이트웨이 생성**  
이 예시에서는 외부 인터페이스에 대해 지정된 IP 주소를 사용하여 고객 게이트웨이를 생성합니다.  
명령:  

```
aws ec2 create-customer-gateway --type ipsec.1 --public-ip 12.1.2.3 --bgp-asn 65534
```
출력:  

```
{
    "CustomerGateway": {
        "CustomerGatewayId": "cgw-0e11f167",
        "IpAddress": "12.1.2.3",
        "State": "available",
        "Type": "ipsec.1",
        "BgpAsn": "65534"
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateCustomerGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-customer-gateway.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 고객 게이트웨이를 생성합니다.**  

```
New-EC2CustomerGateway -Type ipsec.1 -PublicIp 203.0.113.12 -BgpAsn 65534
```
**출력:**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateCustomerGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 고객 게이트웨이를 생성합니다.**  

```
New-EC2CustomerGateway -Type ipsec.1 -PublicIp 203.0.113.12 -BgpAsn 65534
```
**출력:**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateCustomerGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateDhcpOptions` 사용
<a name="example_ec2_CreateDhcpOptions_section"></a>

다음 코드 예시는 `CreateDhcpOptions`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**DHCP 옵션 세트 생성**  
다음 `create-dhcp-options` 예시에서는 도메인 이름, 도메인 이름 서버 및 NetBIOS 노드 유형을 지정하는 DHCP 옵션 세트를 생성합니다.  

```
aws ec2 create-dhcp-options \
    --dhcp-configuration \
        "Key=domain-name-servers,Values=10.2.5.1,10.2.5.2" \
        "Key=domain-name,Values=example.com" \
        "Key=netbios-node-type,Values=2"
```
출력:  

```
{
    "DhcpOptions": {
        "DhcpConfigurations": [
            {
                "Key": "domain-name",
                "Values": [
                    {
                        "Value": "example.com"
                    }
                ]
            },
            {
                "Key": "domain-name-servers",
                "Values": [
                    {
                        "Value": "10.2.5.1"
                    },
                    {
                        "Value": "10.2.5.2"
                    }
                ]
            },
            {
                "Key": "netbios-node-type",
                "Values": [
                    {
                        "Value": "2"
                    }
                ]
            }
        ],
        "DhcpOptionsId": "dopt-06d52773eff4c55f3"
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateDhcpOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-dhcp-options.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 DHCP 옵션 세트를 생성합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$options = @( @{Key="domain-name";Values=@("abc.local")}, @{Key="domain-name-servers";Values=@("10.0.0.101","10.0.0.102")})
New-EC2DhcpOption -DhcpConfiguration $options
```
**출력:**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
```
**예제 2: PowerShell 버전 2에서 각 DHCP 옵션을 만들려면 New-Object를 사용해야 합니다.**  

```
$option1 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option1.Key = "domain-name"
$option1.Values = "abc.local"

$option2 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option2.Key = "domain-name-servers"
$option2.Values = @("10.0.0.101","10.0.0.102")

New-EC2DhcpOption -DhcpConfiguration @($option1, $option2)
```
**출력:**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateDhcpOptions](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 DHCP 옵션 세트를 생성합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$options = @( @{Key="domain-name";Values=@("abc.local")}, @{Key="domain-name-servers";Values=@("10.0.0.101","10.0.0.102")})
New-EC2DhcpOption -DhcpConfiguration $options
```
**출력:**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
```
**예제 2: PowerShell 버전 2에서 각 DHCP 옵션을 만들려면 New-Object를 사용해야 합니다.**  

```
$option1 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option1.Key = "domain-name"
$option1.Values = "abc.local"

$option2 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option2.Key = "domain-name-servers"
$option2.Values = @("10.0.0.101","10.0.0.102")

New-EC2DhcpOption -DhcpConfiguration @($option1, $option2)
```
**출력:**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateFlowLogs` 사용
<a name="example_ec2_CreateFlowLogs_section"></a>

다음 코드 예시는 `CreateFlowLogs`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 흐름 로그 생성**  
다음 `create-flow-logs` 예시에서는 지정된 네트워크 인터페이스에 대해 거부된 모든 트래픽을 캡처하는 흐름 로그를 생성합니다. 흐름 로그는 지정된 IAM 역할의 권한을 사용하여 CloudWatch Logs의 로그 그룹에 전달됩니다.  

```
aws ec2 create-flow-logs \
    --resource-type NetworkInterface \
    --resource-ids eni-11223344556677889 \
    --traffic-type REJECT \
    --log-group-name my-flow-logs \
    --deliver-logs-permission-arn arn:aws:iam::123456789101:role/publishFlowLogs
```
출력:  

```
{
    "ClientToken": "so0eNA2uSHUNlHI0S2cJ305GuIX1CezaRdGtexample",
    "FlowLogIds": [
        "fl-12345678901234567"
    ],
    "Unsuccessful": []
}
```
자세한 내용은 *Amazon VPC 사용 설명서*의 [VPC 흐름 로그](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html)를 참조하세요.  
**예시 2: 사용자 지정 형식으로 흐름 로그 생성**  
다음 `create-flow-logs` 예시에서는 지정된 VPC의 모든 트래픽을 캡처하고 Amazon S3 버킷에 흐름 로그를 전송하는 흐름 로그를 생성합니다. `--log-format` 파라미터는 흐름 로그 레코드의 사용자 지정 형식을 지정합니다. Windows에서 이 명령을 실행하려면 작은따옴표(')를 큰따옴표(")로 변경하세요.  

```
aws ec2 create-flow-logs \
    --resource-type VPC \
    --resource-ids vpc-00112233344556677 \
    --traffic-type ALL \
    --log-destination-type s3 \
    --log-destination arn:aws:s3:::flow-log-bucket/my-custom-flow-logs/ \
    --log-format '${version} ${vpc-id} ${subnet-id} ${instance-id} ${srcaddr} ${dstaddr} ${srcport} ${dstport} ${protocol} ${tcp-flags} ${type} ${pkt-srcaddr} ${pkt-dstaddr}'
```
자세한 내용은 *Amazon VPC 사용 설명서*의 [VPC 흐름 로그](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html)를 참조하세요.  
**예시 3: 최대 집계 간격이 1분인 흐름 로그 생성**  
다음 `create-flow-logs` 예시에서는 지정된 VPC의 모든 트래픽을 캡처하고 Amazon S3 버킷에 흐름 로그를 전송하는 흐름 로그를 생성합니다. `--max-aggregation-interval` 파라미터는 최대 60초(1분)의 집계 간격을 지정합니다.  

```
aws ec2 create-flow-logs \
    --resource-type VPC \
    --resource-ids vpc-00112233344556677 \
    --traffic-type ALL \
    --log-destination-type s3 \
    --log-destination arn:aws:s3:::flow-log-bucket/my-custom-flow-logs/ \
    --max-aggregation-interval 60
```
자세한 내용은 *Amazon VPC 사용 설명서*의 [VPC 흐름 로그](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateFlowLogs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-flow-logs.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 'Admin' 역할의 권한을 사용하여 모든 'REJECT' 트래픽에 대해 'subnet1-log'라는 cloud-watch-log에 subnet-1d234567 서브넷에 대한 EC2 플로우로그를 생성합니다.**  

```
New-EC2FlowLog -ResourceId "subnet-1d234567" -LogDestinationType cloud-watch-logs -LogGroupName subnet1-log -TrafficType "REJECT" -ResourceType Subnet -DeliverLogsPermissionArn "arn:aws:iam::98765432109:role/Admin"
```
**출력:**  

```
ClientToken                                  FlowLogIds             Unsuccessful
-----------                                  ----------             ------------
m1VN2cxP3iB4qo//VUKl5EU6cF7gQLOxcqNefvjeTGw= {fl-012fc34eed5678c9d} {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateFlowLogs](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 'Admin' 역할의 권한을 사용하여 모든 'REJECT' 트래픽에 대해 'subnet1-log'라는 cloud-watch-log에 subnet-1d234567 서브넷에 대한 EC2 플로우로그를 생성합니다.**  

```
New-EC2FlowLog -ResourceId "subnet-1d234567" -LogDestinationType cloud-watch-logs -LogGroupName subnet1-log -TrafficType "REJECT" -ResourceType Subnet -DeliverLogsPermissionArn "arn:aws:iam::98765432109:role/Admin"
```
**출력:**  

```
ClientToken                                  FlowLogIds             Unsuccessful
-----------                                  ----------             ------------
m1VN2cxP3iB4qo//VUKl5EU6cF7gQLOxcqNefvjeTGw= {fl-012fc34eed5678c9d} {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateImage` 사용
<a name="example_ec2_CreateImage_section"></a>

다음 코드 예시는 `CreateImage`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: Amazon EBS 지원 인스턴스에서 AMI 생성**  
다음 `create-image` 예시에서는 지정된 인스턴스에서 AMI를 생성합니다.  

```
aws ec2 create-image \
    --instance-id i-1234567890abcdef0 \
    --name "My server" \
    --description "An AMI for my server"
```
출력:  

```
{
    "ImageId": "ami-abcdef01234567890"
}
```
AMI에 대한 블록 디바이스 매핑을 지정하는 방법에 대한 자세한 내용은 *Amazon EC2 사용 설명서*의 [AMI에 대한 블록 디바이스 매핑 지정](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#create-ami-bdm)을 참조하세요.  
**예시 2: 재부팅 없이 Amazon EBS 지원 인스턴스에서 AMI 생성**  
다음 `create-image` 예시에서는 이미지가 생성되기 전에 인스턴스가 재부팅되지 않도록 AMI를 생성하고 --no-reboot 파라미터를 설정합니다.  

```
aws ec2 create-image \
    --instance-id i-1234567890abcdef0 \
    --name "My server" \
    --no-reboot
```
출력:  

```
{
    "ImageId": "ami-abcdef01234567890"
}
```
AMI에 대한 블록 디바이스 매핑을 지정하는 방법에 대한 자세한 내용은 *Amazon EC2 사용 설명서*의 [AMI에 대한 블록 디바이스 매핑 지정](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#create-ami-bdm)을 참조하세요.  
**예시 3: 생성 시 AMI 및 스냅샷에 태그 지정**  
다음 `create-image` 예시에서는 AMI를 생성하고, AMI와 스냅샷에 동일한 태그로 `cost-center=cc123` 태그를 지정합니다.  

```
aws ec2 create-image \
    --instance-id i-1234567890abcdef0 \
    --name "My server" \
    --tag-specifications "ResourceType=image,Tags=[{Key=cost-center,Value=cc123}]" "ResourceType=snapshot,Tags=[{Key=cost-center,Value=cc123}]"
```
출력:  

```
{
    "ImageId": "ami-abcdef01234567890"
}
```
생성 시 리소스에 태그를 지정하는 방법에 대한 자세한 내용은 *Amazon EC2 사용 설명서*의 [리소스 생성에 태그 추가](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-on-create-examples)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-image.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스에서 지정된 이름 및 설명으로 AMI를 생성합니다. Amazon EC2는 이미지를 생성하기 전에 인스턴스를 완전히 종료하려고 시도하고 완료 시 인스턴스를 다시 시작합니다.**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI"
```
**예제 2: 이 예제에서는 지정된 인스턴스에서 지정된 이름 및 설명으로 AMI를 생성합니다. Amazon EC2는 인스턴스를 종료했다가 다시 시작하지 않고 이미지를 생성합니다. 따라서 생성된 이미지의 파일 시스템 무결성을 보장할 수 없습니다.**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -NoReboot $true
```
**예제 3: 이 예제에서는 볼륨이 3개인 AMI를 생성합니다. 첫 번째 볼륨은 Amazon EBS 스냅샷을 기반으로 합니다. 두 번째 볼륨은 빈 100GiB Amazon EBS 볼륨입니다. 세 번째 볼륨은 인스턴스 저장소 볼륨입니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ebsBlock1 = @{SnapshotId="snap-1a2b3c4d"}
$ebsBlock2 = @{VolumeSize=100}

New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -BlockDeviceMapping @( @{DeviceName="/dev/sdf";Ebs=$ebsBlock1}, @{DeviceName="/dev/sdg";Ebs=$ebsBlock2}, @{DeviceName="/dev/sdc";VirtualName="ephemeral0"})
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateImage](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스에서 지정된 이름 및 설명으로 AMI를 생성합니다. Amazon EC2는 이미지를 생성하기 전에 인스턴스를 완전히 종료하려고 시도하고 완료 시 인스턴스를 다시 시작합니다.**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI"
```
**예제 2: 이 예제에서는 지정된 인스턴스에서 지정된 이름 및 설명으로 AMI를 생성합니다. Amazon EC2는 인스턴스를 종료했다가 다시 시작하지 않고 이미지를 생성합니다. 따라서 생성된 이미지의 파일 시스템 무결성을 보장할 수 없습니다.**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -NoReboot $true
```
**예제 3: 이 예제에서는 볼륨이 3개인 AMI를 생성합니다. 첫 번째 볼륨은 Amazon EBS 스냅샷을 기반으로 합니다. 두 번째 볼륨은 빈 100GiB Amazon EBS 볼륨입니다. 세 번째 볼륨은 인스턴스 저장소 볼륨입니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ebsBlock1 = @{SnapshotId="snap-1a2b3c4d"}
$ebsBlock2 = @{VolumeSize=100}

New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -BlockDeviceMapping @( @{DeviceName="/dev/sdf";Ebs=$ebsBlock1}, @{DeviceName="/dev/sdg";Ebs=$ebsBlock2}, @{DeviceName="/dev/sdc";VirtualName="ephemeral0"})
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateImage](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateInstanceExportTask` 사용
<a name="example_ec2_CreateInstanceExportTask_section"></a>

다음 코드 예시는 `CreateInstanceExportTask`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스 내보내기**  
이 예시에서는 인스턴스 i-1234567890abcdef0을 Amazon S3 버킷 myexportbucket으로 내보내는 태스크를 생성합니다.  
명령:  

```
aws ec2 create-instance-export-task --description "RHEL5 instance" --instance-id i-1234567890abcdef0 --target-environment vmware --export-to-s3-task DiskImageFormat=vmdk,ContainerFormat=ova,S3Bucket=myexportbucket,S3Prefix=RHEL5
```
출력:  

```
{
    "ExportTask": {
        "State": "active",
        "InstanceExportDetails": {
            "InstanceId": "i-1234567890abcdef0",
            "TargetEnvironment": "vmware"
        },
        "ExportToS3Task": {
            "S3Bucket": "myexportbucket",
            "S3Key": "RHEL5export-i-fh8sjjsq.ova",
            "DiskImageFormat": "vmdk",
            "ContainerFormat": "ova"
        },
        "Description": "RHEL5 instance",
        "ExportTaskId": "export-i-fh8sjjsq"
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateInstanceExportTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-instance-export-task.html) 섹션 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 중지된 인스턴스인 `i-0800b00a00EXAMPLE`을 가상 하드 디스크(VHD) 형태로 내보내 S3 버킷 `testbucket-export-instances-2019`에 저장합니다. 대상 환경은 이고`Microsoft`, 인스턴스가 리전에 `us-east-1` 있는 반면 사용자의 기본 리전은 us-east-1이 아니기 때문에 AWS 리전 파라미터가 추가됩니다. 내보내기 작업의 상태를 가져오려면 이 명령의 결과에서 `ExportTaskId` 값을 복사한 다음 `Get-EC2ExportTask -ExportTaskId export_task_ID_from_results.`를 실행합니다.**  

```
New-EC2InstanceExportTask -InstanceId i-0800b00a00EXAMPLE -ExportToS3Task_DiskImageFormat VHD -ExportToS3Task_S3Bucket "amzn-s3-demo-bucket" -TargetEnvironment Microsoft -Region us-east-1
```
**출력:**  

```
Description           : 
ExportTaskId          : export-i-077c73108aEXAMPLE
ExportToS3Task        : Amazon.EC2.Model.ExportToS3Task
InstanceExportDetails : Amazon.EC2.Model.InstanceExportDetails
State                 : active
StatusMessage         :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateInstanceExportTask](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 중지된 인스턴스인 `i-0800b00a00EXAMPLE`을 가상 하드 디스크(VHD) 형태로 내보내 S3 버킷 `testbucket-export-instances-2019`에 저장합니다. 대상 환경은 이고`Microsoft`, 인스턴스가 리전에 `us-east-1` 있는 반면 사용자의 기본 리전은 us-east-1이 아니기 때문에 AWS 리전 파라미터가 추가됩니다. 내보내기 작업의 상태를 가져오려면 이 명령의 결과에서 `ExportTaskId` 값을 복사한 다음 `Get-EC2ExportTask -ExportTaskId export_task_ID_from_results.`를 실행합니다.**  

```
New-EC2InstanceExportTask -InstanceId i-0800b00a00EXAMPLE -ExportToS3Task_DiskImageFormat VHD -ExportToS3Task_S3Bucket "amzn-s3-demo-bucket" -TargetEnvironment Microsoft -Region us-east-1
```
**출력:**  

```
Description           : 
ExportTaskId          : export-i-077c73108aEXAMPLE
ExportToS3Task        : Amazon.EC2.Model.ExportToS3Task
InstanceExportDetails : Amazon.EC2.Model.InstanceExportDetails
State                 : active
StatusMessage         :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateInstanceExportTask](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateInternetGateway` 사용
<a name="example_ec2_CreateInternetGateway_section"></a>

다음 코드 예시는 `CreateInternetGateway`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**인터넷 게이트웨이 생성**  
다음 `create-internet-gateway` 예시에서는 태그가 `Name=my-igw`인 인터넷 게이트웨이를 생성합니다.  

```
aws ec2 create-internet-gateway \
    --tag-specifications ResourceType=internet-gateway,Tags=[{Key=Name,Value=my-igw}]
```
출력:  

```
{
    "InternetGateway": {
        "Attachments": [],
        "InternetGatewayId": "igw-0d0fb496b3994d755",
        "OwnerId": "123456789012",
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-igw"
            }
        ]
    }
}
```
자세한 내용은 *Amazon VPC 사용 설명서*의 [인터넷 게이트웨이](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-internet-gateway.html) 섹션 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인터넷 게이트웨이를 생성합니다.**  

```
New-EC2InternetGateway
```
**출력:**  

```
Attachments    InternetGatewayId    Tags
-----------    -----------------    ----
{}             igw-1a2b3c4d         {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateInternetGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인터넷 게이트웨이를 생성합니다.**  

```
New-EC2InternetGateway
```
**출력:**  

```
Attachments    InternetGatewayId    Tags
-----------    -----------------    ----
{}             igw-1a2b3c4d         {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `CreateKeyPair` 함께 사용
<a name="example_ec2_CreateKeyPair_section"></a>

다음 코드 예시는 `CreateKeyPair`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Create an Amazon EC2 key pair with a specified name.
    /// </summary>
    /// <param name="keyPairName">The name for the new key pair.</param>
    /// <returns>The Amazon EC2 key pair created.</returns>
    public async Task<KeyPair?> CreateKeyPair(string keyPairName)
    {
        try
        {
            var request = new CreateKeyPairRequest { KeyName = keyPairName, };

            var response = await _amazonEC2.CreateKeyPairAsync(request);

            var kp = response.KeyPair;
            // Return the key pair so it can be saved if needed.

            // Wait until the key pair exists.
            int retries = 5;
            while (retries-- > 0)
            {
                Console.WriteLine($"Checking for new KeyPair {keyPairName}...");
                var keyPairs = await DescribeKeyPairs(keyPairName);
                if (keyPairs.Any())
                {
                    return kp;
                }

                Thread.Sleep(5000);
                retries--;
            }
            _logger.LogError($"Unable to find newly created KeyPair {keyPairName}.");
            throw new DoesNotExistException("KeyPair not found");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidKeyPair.Duplicate")
            {
                _logger.LogError(
                    $"A key pair called {keyPairName} already exists.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while creating the key pair.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Save KeyPair information to a temporary file.
    /// </summary>
    /// <param name="keyPair">The name of the key pair.</param>
    /// <returns>The full path to the temporary file.</returns>
    public string SaveKeyPair(KeyPair keyPair)
    {
        var tempPath = Path.GetTempPath();
        var tempFileName = $"{tempPath}\\{Path.GetRandomFileName()}";
        var pemFileName = Path.ChangeExtension(tempFileName, "pem");

        // Save the key pair to a file in a temporary folder.
        using var stream = new FileStream(pemFileName, FileMode.Create);
        using var writer = new StreamWriter(stream);
        writer.WriteLine(keyPair.KeyMaterial);

        return pemFileName;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [CreateKeyPair](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateKeyPair)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_create_keypair
#
# This function creates an Amazon Elastic Compute Cloud (Amazon EC2) ED25519 or 2048-bit RSA key pair
# and writes it to a file.
#
# Parameters:
#       -n key_pair_name - A key pair name.
#       -f file_path - File to store the key pair.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_create_keypair() {
  local key_pair_name file_path response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_create_keypair"
    echo "Creates an Amazon Elastic Compute Cloud (Amazon EC2) ED25519 or 2048-bit RSA key pair"
    echo " and writes it to a file."
    echo "  -n key_pair_name - A key pair name."
    echo "  -f file_path - File to store the key pair."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:f:h" option; do
    case "${option}" in
      n) key_pair_name="${OPTARG}" ;;
      f) file_path="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$key_pair_name" ]]; then
    errecho "ERROR: You must provide a key name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$file_path" ]]; then
    errecho "ERROR: You must provide a file path with the -f parameter."
    usage
    return 1
  fi

  response=$(aws ec2 create-key-pair \
    --key-name "$key_pair_name" \
    --query 'KeyMaterial' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports create-access-key operation failed.$response"
    return 1
  }

  if [[ -n "$file_path" ]]; then
    echo "$response" >"$file_path"
  fi

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateKeyPair](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateKeyPair)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Create an Amazon Elastic Compute Cloud (Amazon EC2) instance key pair.
/*!
  \param keyPairName: A name for a key pair.
  \param keyFilePath: File path where the credentials are stored. Ignored if it is an empty string;
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::createKeyPair(const Aws::String &keyPairName, const Aws::String &keyFilePath,
                                const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
        }

    }

    return outcome.IsSuccess();

}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [CreateKeyPair](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/CreateKeyPair)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**키 페어를 생성하는 방법**  
이 예제에서는 이름이 `MyKeyPair`인 키 페어를 생성합니다.  
명령:  

```
aws ec2 create-key-pair --key-name MyKeyPair
```
출력은 프라이빗 키 및 키 지문의 ASCII 버전입니다. 키는 파일에 저장해야 합니다.  
자세한 내용은 *AWS Command Line Interface 사용 설명서*의 키 페어 사용을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [CreateKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-key-pair.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Creates a new key pair asynchronously.
     *
     * @param keyName the name of the key pair to create
     * @param fileName the name of the file to write the key material to
     * @return a {@link CompletableFuture} that represents the asynchronous operation
     *         of creating the key pair and writing the key material to a file
     */
    public CompletableFuture<CreateKeyPairResponse> createKeyPairAsync(String keyName, String fileName) {
        CreateKeyPairRequest request = CreateKeyPairRequest.builder()
            .keyName(keyName)
            .build();

        CompletableFuture<CreateKeyPairResponse> responseFuture = getAsyncClient().createKeyPair(request);
        responseFuture.whenComplete((response, exception) -> {
            if (response != null) {
                try {
                    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
                    writer.write(response.keyMaterial());
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException("Failed to write key material to file: " + e.getMessage(), e);
                }
            } else {
                throw new RuntimeException("Failed to create key pair: " + exception.getMessage(), exception);
            }
        });

        return responseFuture;
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [CreateKeyPair](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateKeyPair)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { CreateKeyPairCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Creates an ED25519 or 2048-bit RSA key pair with the specified name and in the specified PEM or PPK format.
 * Amazon EC2 stores the public key and displays the private key for you to save to a file.
 * @param {{ keyName: string }} options
 */
export const main = async ({ keyName }) => {
  const client = new EC2Client({});
  const command = new CreateKeyPairCommand({
    KeyName: keyName,
  });

  try {
    const { KeyMaterial, KeyName } = await client.send(command);
    console.log(KeyName);
    console.log(KeyMaterial);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidKeyPair.Duplicate") {
      console.warn(`${caught.message}. Try another key name.`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateKeyPair](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateKeyPairCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun createEC2KeyPair(keyNameVal: String) {
    val request =
        CreateKeyPairRequest {
            keyName = keyNameVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.createKeyPair(request)
        println("The key ID is ${response.keyPairId}")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [CreateKeyPair](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 키 페어를 생성하고 지정된 이름의 파일에 PEM 인코딩 RSA 프라이빗 키를 캡처합니다. PowerShell을 사용하는 경우 유효한 키를 생성하려면 인코딩을 ascii로 설정해야 합니다. 자세한 내용은 AWS 명령줄 인터페이스 사용 설명서의 Amazon EC2 키 페어 생성, 표시 및 삭제(https://docs.aws.amazon.com/cli/latest/userguide/cli-services-ec2-keypairs.html)를 참조하세요.**  

```
(New-EC2KeyPair -KeyName "my-key-pair").KeyMaterial | Out-File -Encoding ascii -FilePath C:\path\my-key-pair.pem
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateKeyPair](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 키 페어를 생성하고 지정된 이름의 파일에 PEM 인코딩 RSA 프라이빗 키를 캡처합니다. PowerShell을 사용하는 경우 유효한 키를 생성하려면 인코딩을 ascii로 설정해야 합니다. 자세한 내용은 AWS 명령줄 인터페이스 사용 설명서의 Amazon EC2 키 페어 생성, 표시 및 삭제(https://docs.aws.amazon.com/cli/latest/userguide/cli-services-ec2-keypairs.html)를 참조하세요.**  

```
(New-EC2KeyPair -KeyName "my-key-pair").KeyMaterial | Out-File -Encoding ascii -FilePath C:\path\my-key-pair.pem
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class KeyPairWrapper:
    """
    Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.
    This class provides methods to create, list, and delete EC2 key pairs.
    """

    def __init__(
        self,
        ec2_client: boto3.client,
        key_file_dir: Union[tempfile.TemporaryDirectory, str],
        key_pair: Optional[dict] = None,
    ):
        """
        Initializes the KeyPairWrapper with the specified EC2 client, key file directory,
        and an optional key pair.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param key_file_dir: The folder where the private key information is stored.
                             This should be a secure folder.
        :param key_pair: A dictionary representing the Boto3 KeyPair object.
                         This is a high-level object that wraps key pair actions. Optional.
        """
        self.ec2_client = ec2_client
        self.key_pair = key_pair
        self.key_file_path: Optional[str] = None
        self.key_file_dir = key_file_dir

    @classmethod
    def from_client(cls) -> "KeyPairWrapper":
        """
        Class method to create an instance of KeyPairWrapper using a new EC2 client
        and a temporary directory for storing key files.

        :return: An instance of KeyPairWrapper.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client, tempfile.TemporaryDirectory())


    def create(self, key_name: str) -> dict:
        """
        Creates a key pair that can be used to securely connect to an EC2 instance.
        The returned key pair contains private key information that cannot be retrieved
        again. The private key data is stored as a .pem file.

        :param key_name: The name of the key pair to create.
        :return: A dictionary representing the Boto3 KeyPair object that represents the newly created key pair.
        :raises ClientError: If there is an error in creating the key pair, for example, if a key pair with the same name already exists.
        """
        try:
            response = self.ec2_client.create_key_pair(KeyName=key_name)
            self.key_pair = response
            self.key_file_path = os.path.join(
                self.key_file_dir.name, f"{self.key_pair['KeyName']}.pem"
            )
            with open(self.key_file_path, "w") as key_file:
                key_file.write(self.key_pair["KeyMaterial"])
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidKeyPair.Duplicate":
                logger.error(
                    f"A key pair called {key_name} already exists. "
                    "Please choose a different name for your key pair "
                    "or delete the existing key pair before creating."
                )
            raise
        else:
            return self.key_pair
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateKeyPair](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateKeyPair)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
# This code example does the following:
# 1. Creates a key pair in Amazon Elastic Compute Cloud (Amazon EC2).
# 2. Displays information about available key pairs.
# 3. Deletes the key pair.

require 'aws-sdk-ec2'

# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param key_pair_name [String] The name for the key pair and private
#   key file.
# @return [Boolean] true if the key pair and private key file were
#   created; otherwise, false.
# @example
#   exit 1 unless key_pair_created?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'my-key-pair'
#   )
def key_pair_created?(ec2_client, key_pair_name)
  key_pair = ec2_client.create_key_pair(key_name: key_pair_name)
  puts "Created key pair '#{key_pair.key_name}' with fingerprint " \
    "'#{key_pair.key_fingerprint}' and ID '#{key_pair.key_pair_id}'."
  filename = File.join(Dir.home, "#{key_pair_name}.pem")
  File.open(filename, 'w') { |file| file.write(key_pair.key_material) }
  puts "Private key file saved locally as '#{filename}'."
  true
rescue Aws::EC2::Errors::InvalidKeyPairDuplicate
  puts "Error creating key pair: a key pair named '#{key_pair_name}' " \
    'already exists.'
  false
rescue StandardError => e
  puts "Error creating key pair or saving private key file: #{e.message}"
  false
end

# Displays information about available key pairs in
# Amazon Elastic Compute Cloud (Amazon EC2).
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @example
#   describe_key_pairs(Aws::EC2::Client.new(region: 'us-west-2'))
def describe_key_pairs(ec2_client)
  result = ec2_client.describe_key_pairs
  if result.key_pairs.count.zero?
    puts 'No key pairs found.'
  else
    puts 'Key pair names:'
    result.key_pairs.each do |key_pair|
      puts key_pair.key_name
    end
  end
rescue StandardError => e
  puts "Error getting information about key pairs: #{e.message}"
end

# Deletes a key pair in Amazon Elastic Compute Cloud (Amazon EC2).
#
# Prerequisites:
#
# - The key pair to delete.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param key_pair_name [String] The name of the key pair to delete.
# @return [Boolean] true if the key pair was deleted; otherwise, false.
# @example
#   exit 1 unless key_pair_deleted?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'my-key-pair'
#   )
def key_pair_deleted?(ec2_client, key_pair_name)
  ec2_client.delete_key_pair(key_name: key_pair_name)
  true
rescue StandardError => e
  puts "Error deleting key pair: #{e.message}"
  false
end

# Example usage:
def run_me
  key_pair_name = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-key-pairs.rb KEY_PAIR_NAME REGION'
    puts 'Example: ruby ec2-ruby-example-key-pairs.rb my-key-pair us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    key_pair_name = 'my-key-pair'
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    key_pair_name = ARGV[0]
    region = ARGV[1]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts 'Displaying existing key pair names before creating this key pair...'
  describe_key_pairs(ec2_client)

  puts '-' * 10
  puts 'Creating key pair...'
  unless key_pair_created?(ec2_client, key_pair_name)
    puts 'Stopping program.'
    exit 1
  end

  puts '-' * 10
  puts 'Displaying existing key pair names after creating this key pair...'
  describe_key_pairs(ec2_client)

  puts '-' * 10
  puts 'Deleting key pair...'
  unless key_pair_deleted?(ec2_client, key_pair_name)
    puts 'Stopping program. You must delete the key pair yourself.'
    exit 1
  end
  puts 'Key pair deleted.'

  puts '-' * 10
  puts 'Now that the key pair is deleted, ' \
    'also deleting the related private key pair file...'
  filename = File.join(Dir.home, "#{key_pair_name}.pem")
  File.delete(filename)
  if File.exist?(filename)
    puts "Could not delete file at '#{filename}'. You must delete it yourself."
  else
    puts 'File deleted.'
  end

  puts '-' * 10
  puts 'Displaying existing key pair names after deleting this key pair...'
  describe_key_pairs(ec2_client)
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateKeyPair](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateKeyPair)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
EC2 클라이언트의 create\$1key\$1pair를 직접적으로 호출하고 반환된 값을 추출하는 Rust 구현입니다.  

```
    pub async fn create_key_pair(&self, name: String) -> Result<(KeyPairInfo, String), EC2Error> {
        tracing::info!("Creating key pair {name}");
        let output = self.client.create_key_pair().key_name(name).send().await?;
        let info = KeyPairInfo::builder()
            .set_key_name(output.key_name)
            .set_key_fingerprint(output.key_fingerprint)
            .set_key_pair_id(output.key_pair_id)
            .build();
        let material = output
            .key_material
            .ok_or_else(|| EC2Error::new("Create Key Pair has no key material"))?;
        Ok((info, material))
    }
```
create\$1key impl을 직접적으로 호출하고 PEM 프라이빗 키를 안전하게 저장하는 함수입니다.  

```
    /// Creates a key pair that can be used to securely connect to an EC2 instance.
    /// The returned key pair contains private key information that cannot be retrieved
    /// again. The private key data is stored as a .pem file.
    ///
    /// :param key_name: The name of the key pair to create.
    pub async fn create(
        &mut self,
        ec2: &EC2,
        util: &Util,
        key_name: String,
    ) -> Result<KeyPairInfo, EC2Error> {
        let (key_pair, material) = ec2.create_key_pair(key_name.clone()).await.map_err(|e| {
            self.key_pair = KeyPairInfo::builder().key_name(key_name.clone()).build();
            e.add_message(format!("Couldn't create key {key_name}"))
        })?;

        let path = self.key_file_dir.join(format!("{key_name}.pem"));

        // Save the key_pair information immediately, so it can get cleaned up if write_secure fails.
        self.key_file_path = Some(path.clone());
        self.key_pair = key_pair.clone();

        util.write_secure(&key_name, &path, material)?;

        Ok(key_pair)
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateKeyPair](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.create_key_pair)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->createkeypair( iv_keyname = iv_key_name ).                            " oo_result is returned for testing purposes. "
        MESSAGE 'Amazon EC2 key pair created.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateKeyPair](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Create a new RSA key pair and save the private key to a randomly-named
    /// file in the temporary directory.
    ///
    /// - Parameter name: The name of the key pair to create.
    ///
    /// - Returns: The URL of the newly created `.pem` file or `nil` if unable
    ///   to create the key pair.
    func createKeyPair(name: String) async -> URL? {
        do {
            let output = try await ec2Client.createKeyPair(
                input: CreateKeyPairInput(
                    keyName: name
                )
            )

            guard let keyMaterial = output.keyMaterial else {
                return nil
            }

            // Build the URL of the temporary private key file.

            let fileURL = URL.temporaryDirectory
                                  .appendingPathComponent(name)
                                  .appendingPathExtension("pem")

            do {
                try keyMaterial.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
                return fileURL
            } catch {
                print("*** Failed to write the private key.")
                return nil
            }
        } catch {
            print("*** Unable to create the key pair.")
            return nil
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [CreateKeyPair](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/createkeypair(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `CreateLaunchTemplate` 함께 사용
<a name="example_ec2_CreateLaunchTemplate_section"></a>

다음 코드 예시는 `CreateLaunchTemplate`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](example_cross_ResilientService_section.md) 
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling.
    /// The launch template specifies a Bash script in its user data field that runs after
    /// the instance is started. This script installs the Python packages and starts a Python
    /// web server on the instance.
    /// </summary>
    /// <param name="startupScriptPath">The path to a Bash script file that is run.</param>
    /// <param name="instancePolicyPath">The path to a permissions policy to create and attach to the profile.</param>
    /// <returns>The template object.</returns>
    public async Task<Amazon.EC2.Model.LaunchTemplate> CreateTemplate(string startupScriptPath, string instancePolicyPath)
    {
        try
        {
            await CreateKeyPair(_keyPairName);
            await CreateInstanceProfileWithName(_instancePolicyName, _instanceRoleName,
                _instanceProfileName, instancePolicyPath);

            var startServerText = await File.ReadAllTextAsync(startupScriptPath);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(startServerText);

            var amiLatest = await _amazonSsm.GetParameterAsync(
                new GetParameterRequest() { Name = _amiParam });
            var amiId = amiLatest.Parameter.Value;
            var launchTemplateResponse = await _amazonEc2.CreateLaunchTemplateAsync(
                new CreateLaunchTemplateRequest()
                {
                    LaunchTemplateName = _launchTemplateName,
                    LaunchTemplateData = new RequestLaunchTemplateData()
                    {
                        InstanceType = _instanceType,
                        ImageId = amiId,
                        IamInstanceProfile =
                            new
                                LaunchTemplateIamInstanceProfileSpecificationRequest()
                            {
                                Name = _instanceProfileName
                            },
                        KeyName = _keyPairName,
                        UserData = System.Convert.ToBase64String(plainTextBytes)
                    }
                });
            return launchTemplateResponse.LaunchTemplate;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.AlreadyExistsException")
            {
                _logger.LogError($"Could not create the template, the name {_launchTemplateName} already exists. " +
                                 $"Please try again with a unique name.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 **AWS SDK for .NET API 참조의 [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateLaunchTemplate)을 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예 1: 시작 템플릿을 생성하는 방법**  
다음 `create-launch-template` 예제에서는 인스턴스를 시작하고 인스턴스에 퍼블릭 IP 주소 및 IPv6 주소를 할당하며 인스턴스에 대한 태그를 생성할 서브넷을 지정하는 시작 템플릿을 생성합니다.  

```
aws ec2 create-launch-template \
    --launch-template-name TemplateForWebServer \
    --version-description WebVersion1 \
    --launch-template-data '{"NetworkInterfaces":[{"AssociatePublicIpAddress":true,"DeviceIndex":0,"Ipv6AddressCount":1,"SubnetId":"subnet-7b16de0c"}],"ImageId":"ami-8c1be5f6","InstanceType":"t2.small","TagSpecifications":[{"ResourceType":"instance","Tags":[{"Key":"purpose","Value":"webserver"}]}]}'
```
출력:  

```
{
    "LaunchTemplate": {
        "LatestVersionNumber": 1,
        "LaunchTemplateId": "lt-01238c059e3466abc",
        "LaunchTemplateName": "TemplateForWebServer",
        "DefaultVersionNumber": 1,
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "CreateTime": "2019-01-27T09:13:24.000Z"
    }
}
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*의 시작 템플릿에서 인스턴스 시작을 참조하세요. JSON 형식 파라미터에서 따옴표 사용에 대한 자세한 내용은 *AWS Command Line Interface 사용 설명서*의 문자열에 따옴표 사용을 참조하세요.  
**예제 2: Amazon EC2 Auto Scaling에 대한 시작 템플릿을 생성하는 방법**  
다음 `create-launch-template` 예제에서는 인스턴스를 시작할 때 추가 EBS 볼륨을 지정하도록 여러 태그 및 블록 디바이스 매핑을 사용하는 시작 템플릿을 생성합니다. Auto Scaling 그룹이 인스턴스를 시작하는 VPC의 보안 그룹에 해당하는 `Groups`에 대한 값을 지정합니다. Auto Scaling 그룹의 속성으로 VPC 및 서브넷을 지정합니다.  

```
aws ec2 create-launch-template \
    --launch-template-name TemplateForAutoScaling \
    --version-description AutoScalingVersion1 \
    --launch-template-data '{"NetworkInterfaces":[{"DeviceIndex":0,"AssociatePublicIpAddress":true,"Groups":["sg-7c227019,sg-903004f8"],"DeleteOnTermination":true}],"ImageId":"ami-b42209de","InstanceType":"m4.large","TagSpecifications":[{"ResourceType":"instance","Tags":[{"Key":"environment","Value":"production"},{"Key":"purpose","Value":"webserver"}]},{"ResourceType":"volume","Tags":[{"Key":"environment","Value":"production"},{"Key":"cost-center","Value":"cc123"}]}],"BlockDeviceMappings":[{"DeviceName":"/dev/sda1","Ebs":{"VolumeSize":100}}]}' --region us-east-1
```
출력:  

```
{
    "LaunchTemplate": {
        "LatestVersionNumber": 1,
        "LaunchTemplateId": "lt-0123c79c33a54e0abc",
        "LaunchTemplateName": "TemplateForAutoScaling",
        "DefaultVersionNumber": 1,
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "CreateTime": "2019-04-30T18:16:06.000Z"
    }
}
```
자세한 내용은 *Amazon EC2 Auto Scaling 사용 설명서*의 Auto Scaling 그룹에 대한 시작 템플릿 생성을 참조하세요. JSON 형식 파라미터에서 따옴표 사용에 대한 자세한 내용은 *AWS Command Line Interface 사용 설명서*의 문자열에 따옴표 사용을 참조하세요.  
**예제 3: EBS 볼륨의 암호화를 지정하는 시작 템플릿을 생성하는 방법**  
다음 `create-launch-template` 예제에서는 암호화되지 않은 스냅샷에서 생성된 암호화된 EBS 볼륨을 포함하는 시작 템플릿을 생성합니다. 또한 생성 중에 볼륨에 태그도 지정합니다. 기본적으로 암호화가 비활성화된 경우 다음 예제에 표시된 대로 `"Encrypted"` 옵션을 지정해야 합니다. `"KmsKeyId"` 옵션을 사용하여 고객 관리형 CMK를 지정하는 경우 기본적으로 암호화가 활성화되어 있더라도 `"Encrypted"` 옵션도 지정해야 합니다.  

```
aws ec2 create-launch-template \
  --launch-template-name TemplateForEncryption \
  --launch-template-data file://config.json
```
`config.json`의 콘텐츠:  

```
{
    "BlockDeviceMappings":[
        {
            "DeviceName":"/dev/sda1",
            "Ebs":{
                "VolumeType":"gp2",
                "DeleteOnTermination":true,
                "SnapshotId":"snap-066877671789bd71b",
                "Encrypted":true,
                "KmsKeyId":"arn:aws:kms:us-east-1:012345678910:key/abcd1234-a123-456a-a12b-a123b4cd56ef"
            }
        }
    ],
    "ImageId":"ami-00068cd7555f543d5",
    "InstanceType":"c5.large",
    "TagSpecifications":[
        {
            "ResourceType":"volume",
            "Tags":[
                {
                    "Key":"encrypted",
                    "Value":"yes"
                }
            ]
        }
    ]
}
```
출력:  

```
{
    "LaunchTemplate": {
        "LatestVersionNumber": 1,
        "LaunchTemplateId": "lt-0d5bd51bcf8530abc",
        "LaunchTemplateName": "TemplateForEncryption",
        "DefaultVersionNumber": 1,
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "CreateTime": "2020-01-07T19:08:36.000Z"
    }
}
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*의 스냅샷에서 Amazon EBS 볼륨 복원 및 암호화 기본 제공을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [CreateLaunchTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html)을 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    const ssmClient = new SSMClient({});
    const { Parameter } = await ssmClient.send(
      new GetParameterCommand({
        Name: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
      }),
    );
    const ec2Client = new EC2Client({});
    await ec2Client.send(
      new CreateLaunchTemplateCommand({
        LaunchTemplateName: NAMES.launchTemplateName,
        LaunchTemplateData: {
          InstanceType: "t3.micro",
          ImageId: Parameter.Value,
          IamInstanceProfile: { Name: NAMES.instanceProfileName },
          UserData: readFileSync(
            join(RESOURCES_PATH, "server_startup_script.sh"),
          ).toString("base64"),
          KeyName: NAMES.keyPairName,
        },
      }),
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [CreateLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateLaunchTemplateCommand)을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예제에서는 인스턴스에 특정 권한을 부여하는 인스턴스 프로파일과 인스턴스가 시작된 후 인스턴스에서 실행되는 사용자 데이터 Bash 스크립트가 포함된 시작 템플릿을 생성합니다.  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def create_template(
        self, server_startup_script_file: str, instance_policy_file: str
    ) -> Dict[str, Any]:
        """
        Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling. The
        launch template specifies a Bash script in its user data field that runs after
        the instance is started. This script installs Python packages and starts a
        Python web server on the instance.

        :param server_startup_script_file: The path to a Bash script file that is run
                                           when an instance starts.
        :param instance_policy_file: The path to a file that defines a permissions policy
                                     to create and attach to the instance profile.
        :return: Information about the newly created template.
        """
        template = {}
        try:
            # Create key pair and instance profile
            self.create_key_pair(self.key_pair_name)
            self.create_instance_profile(
                instance_policy_file,
                self.instance_policy_name,
                self.instance_role_name,
                self.instance_profile_name,
            )

            # Read the startup script
            with open(server_startup_script_file) as file:
                start_server_script = file.read()

            # Get the latest AMI ID
            ami_latest = self.ssm_client.get_parameter(Name=self.ami_param)
            ami_id = ami_latest["Parameter"]["Value"]

            # Create the launch template
            lt_response = self.ec2_client.create_launch_template(
                LaunchTemplateName=self.launch_template_name,
                LaunchTemplateData={
                    "InstanceType": self.inst_type,
                    "ImageId": ami_id,
                    "IamInstanceProfile": {"Name": self.instance_profile_name},
                    "UserData": base64.b64encode(
                        start_server_script.encode(encoding="utf-8")
                    ).decode(encoding="utf-8"),
                    "KeyName": self.key_pair_name,
                },
            )
            template = lt_response["LaunchTemplate"]
            log.info(
                f"Created launch template {self.launch_template_name} for AMI {ami_id} on {self.inst_type}."
            )
        except ClientError as err:
            log.error(f"Failed to create launch template {self.launch_template_name}.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidLaunchTemplateName.AlreadyExistsException":
                log.info(
                    f"Launch template {self.launch_template_name} already exists, nothing to do."
                )
            log.error(f"Full error:\n\t{err}")
        return template
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateLaunchTemplate)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateNetworkAcl` 사용
<a name="example_ec2_CreateNetworkAcl_section"></a>

다음 코드 예시는 `CreateNetworkAcl`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 ACL 생성**  
이 예시에서는 지정된 VPC에 대한 네트워크 ACL을 만듭니다.  
명령:  

```
aws ec2 create-network-acl --vpc-id vpc-a01106c2
```
출력:  

```
{
    "NetworkAcl": {
        "Associations": [],
        "NetworkAclId": "acl-5fb85d36",
        "VpcId": "vpc-a01106c2",
        "Tags": [],
        "Entries": [
            {
                "CidrBlock": "0.0.0.0/0",
                "RuleNumber": 32767,
                "Protocol": "-1",
                "Egress": true,
                "RuleAction": "deny"
            },
            {
                "CidrBlock": "0.0.0.0/0",
                "RuleNumber": 32767,
                "Protocol": "-1",
                "Egress": false,
                "RuleAction": "deny"
            }
        ],
        "IsDefault": false
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateNetworkAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-acl.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPC에 대한 네트워크 ACL을 만듭니다.**  

```
New-EC2NetworkAcl -VpcId vpc-12345678
```
**출력:**  

```
Associations : {}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {}
VpcId        : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateNetworkAcl](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPC에 대한 네트워크 ACL을 만듭니다.**  

```
New-EC2NetworkAcl -VpcId vpc-12345678
```
**출력:**  

```
Associations : {}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {}
VpcId        : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateNetworkAcl](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateNetworkAclEntry` 사용
<a name="example_ec2_CreateNetworkAclEntry_section"></a>

다음 코드 예시는 `CreateNetworkAclEntry`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 ACL 항목 생성**  
이 예시에서는 지정된 네트워크 ACL에 대한 항목을 만듭니다. 이 규칙은 UDP 포트 53(DNS)의 모든 IPv4 주소(0.0.0.0/0)에서 연결된 모든 서브넷으로 유입되는 트래픽을 허용합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 create-network-acl-entry --network-acl-id acl-5fb85d36 --ingress --rule-number 100 --protocol udp --port-range From=53,To=53 --cidr-block 0.0.0.0/0 --rule-action allow
```
이 예시에서는 TCP 포트 80(HTTP)의 모든 IPv6 주소(::/0)에서 들어오는 트래픽을 허용하는 지정된 네트워크 ACL에 대한 규칙을 만듭니다.  
명령:  

```
aws ec2 create-network-acl-entry --network-acl-id acl-5fb85d36 --ingress --rule-number 120 --protocol tcp --port-range From=80,To=80 --ipv6-cidr-block ::/0 --rule-action allow
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateNetworkAclEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-acl-entry.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL에 대한 항목을 만듭니다. 이 규칙은 UDP 포트 53(DNS)을 통해 모든 곳(0.0.0.0/0)에서 연결된 모든 서브넷으로 유입되는 트래픽을 허용합니다.**  

```
New-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 0.0.0.0/0 -RuleAction allow
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateNetworkAclEntry](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL에 대한 항목을 만듭니다. 이 규칙은 UDP 포트 53(DNS)을 통해 모든 곳(0.0.0.0/0)에서 연결된 모든 서브넷으로 유입되는 트래픽을 허용합니다.**  

```
New-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 0.0.0.0/0 -RuleAction allow
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateNetworkInterface` 사용
<a name="example_ec2_CreateNetworkInterface_section"></a>

다음 코드 예시는 `CreateNetworkInterface`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 네트워크 인터페이스의 IPv4 주소 지정**  
다음 `create-network-interface` 예시에서는 지정된 기본 IPv4 주소로 지정된 서브넷에 대한 네트워크 인터페이스를 생성합니다.  

```
aws ec2 create-network-interface \
    --subnet-id subnet-00a24d0d67acf6333 \
    --description "my network interface" \
    --groups sg-09dfba7ed20cda78b \
    --private-ip-address 10.0.8.17
```
출력:  

```
{
    "NetworkInterface": {
        "AvailabilityZone": "us-west-2a",
        "Description": "my network interface",
        "Groups": [
            {
                "GroupName": "my-security-group",
                "GroupId": "sg-09dfba7ed20cda78b"
            }
        ],
        "InterfaceType": "interface",
        "Ipv6Addresses": [],
        "MacAddress": "06:6a:0f:9a:49:37",
        "NetworkInterfaceId": "eni-0492b355f0cf3b3f8",
        "OwnerId": "123456789012",
        "PrivateDnsName": "ip-10-0-8-18.us-west-2.compute.internal",
        "PrivateIpAddress": "10.0.8.17",
        "PrivateIpAddresses": [
            {
                "Primary": true,
                "PrivateDnsName": "ip-10-0-8-17.us-west-2.compute.internal",
                "PrivateIpAddress": "10.0.8.17"
            }
        ],
        "RequesterId": "AIDA4Z3Y7GSXTMEXAMPLE",
        "RequesterManaged": false,
        "SourceDestCheck": true,
        "Status": "pending",
        "SubnetId": "subnet-00a24d0d67acf6333",
        "TagSet": [],
        "VpcId": "vpc-02723a0feeeb9d57b"
    }
}
```
**예시 2: IPv4 주소와 IPv6 주소로 네트워크 인터페이스 생성**  
다음 `create-network-interface` 예시에서는 Amazon EC2에서 선택한 IPv4 주소와 IPv6 주소로 지정된 서브넷에 대한 네트워크 인터페이스를 생성합니다.  

```
aws ec2 create-network-interface \
    --subnet-id subnet-00a24d0d67acf6333 \
    --description "my dual stack network interface" \
    --ipv6-address-count 1 \
    --groups sg-09dfba7ed20cda78b
```
출력:  

```
{
    "NetworkInterface": {
        "AvailabilityZone": "us-west-2a",
        "Description": "my dual stack network interface",
        "Groups": [
            {
                "GroupName": "my-security-group",
                "GroupId": "sg-09dfba7ed20cda78b"
            }
        ],
        "InterfaceType": "interface",
        "Ipv6Addresses": [
            {
                "Ipv6Address": "2600:1f13:cfe:3650:a1dc:237c:393a:4ba7",
                "IsPrimaryIpv6": false
            }
        ],
        "MacAddress": "06:b8:68:d2:b2:2d",
        "NetworkInterfaceId": "eni-05da417453f9a84bf",
        "OwnerId": "123456789012",
        "PrivateDnsName": "ip-10-0-8-18.us-west-2.compute.internal",
        "PrivateIpAddress": "10.0.8.18",
        "PrivateIpAddresses": [
            {
                "Primary": true,
                "PrivateDnsName": "ip-10-0-8-18.us-west-2.compute.internal",
                "PrivateIpAddress": "10.0.8.18"
            }
        ],
        "RequesterId": "AIDA4Z3Y7GSXTMEXAMPLE",
        "RequesterManaged": false,
        "SourceDestCheck": true,
        "Status": "pending",
        "SubnetId": "subnet-00a24d0d67acf6333",
        "TagSet": [],
        "VpcId": "vpc-02723a0feeeb9d57b",
        "Ipv6Address": "2600:1f13:cfe:3650:a1dc:237c:393a:4ba7"
    }
}
```
**예시 3: 연결 추적 구성 옵션을 사용하여 네트워크 인터페이스 생성**  
다음 `create-network-interface` 예시에서는 네트워크 인터페이스를 생성하고 유휴 연결 추적 제한 시간을 구성합니다.  

```
aws ec2 create-network-interface \
    --subnet-id subnet-00a24d0d67acf6333 \
    --groups sg-02e57dbcfe0331c1b \
    --connection-tracking-specification TcpEstablishedTimeout=86400,UdpTimeout=60
```
출력:  

```
{
    "NetworkInterface": {
        "AvailabilityZone": "us-west-2a",
        "ConnectionTrackingConfiguration": {
            "TcpEstablishedTimeout": 86400,
            "UdpTimeout": 60
        },
        "Description": "",
        "Groups": [
            {
                "GroupName": "my-security-group",
                "GroupId": "sg-02e57dbcfe0331c1b"
            }
        ],
        "InterfaceType": "interface",
        "Ipv6Addresses": [],
        "MacAddress": "06:4c:53:de:6d:91",
        "NetworkInterfaceId": "eni-0c133586e08903d0b",
        "OwnerId": "123456789012",
        "PrivateDnsName": "ip-10-0-8-94.us-west-2.compute.internal",
        "PrivateIpAddress": "10.0.8.94",
        "PrivateIpAddresses": [
            {
                "Primary": true,
                "PrivateDnsName": "ip-10-0-8-94.us-west-2.compute.internal",
                "PrivateIpAddress": "10.0.8.94"
            }
        ],
        "RequesterId": "AIDA4Z3Y7GSXTMEXAMPLE",
        "RequesterManaged": false,
        "SourceDestCheck": true,
        "Status": "pending",
        "SubnetId": "subnet-00a24d0d67acf6333",
        "TagSet": [],
        "VpcId": "vpc-02723a0feeeb9d57b"
    }
}
```
**예시 4: 탄력적 패브릭 어댑터 생성**  
다음 `create-network-interface` 예시에서는 EFA를 생성합니다.  

```
aws ec2 create-network-interface \
    --interface-type efa \
    --subnet-id subnet-00a24d0d67acf6333 \
    --description "my efa" \
    --groups sg-02e57dbcfe0331c1b
```
출력:  

```
{
    "NetworkInterface": {
        "AvailabilityZone": "us-west-2a",
        "Description": "my efa",
        "Groups": [
            {
                "GroupName": "my-efa-sg",
                "GroupId": "sg-02e57dbcfe0331c1b"
            }
        ],
        "InterfaceType": "efa",
        "Ipv6Addresses": [],
        "MacAddress": "06:d7:a4:f7:4d:57",
        "NetworkInterfaceId": "eni-034acc2885e862b65",
        "OwnerId": "123456789012",
        "PrivateDnsName": "ip-10-0-8-180.us-west-2.compute.internal",
        "PrivateIpAddress": "10.0.8.180",
        "PrivateIpAddresses": [
            {
                "Primary": true,
                "PrivateDnsName": "ip-10-0-8-180.us-west-2.compute.internal",
                "PrivateIpAddress": "10.0.8.180"
            }
        ],
        "RequesterId": "AIDA4Z3Y7GSXTMEXAMPLE",
        "RequesterManaged": false,
        "SourceDestCheck": true,
        "Status": "pending",
        "SubnetId": "subnet-00a24d0d67acf6333",
        "TagSet": [],
        "VpcId": "vpc-02723a0feeeb9d57b"
    }
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [탄력적 네트워크 인터페이스](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateNetworkInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-interface.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스를 생성합니다.**  

```
New-EC2NetworkInterface -SubnetId subnet-1a2b3c4d -Description "my network interface" -Group sg-12345678 -PrivateIpAddress 10.0.0.17
```
**출력:**  

```
Association        :
Attachment         :
AvailabilityZone   : us-west-2c
Description        : my network interface
Groups             : {my-security-group}
MacAddress         : 0a:72:bc:1a:cd:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-17.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.17
PrivateIpAddresses : {}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : pending
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateNetworkInterface](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스를 생성합니다.**  

```
New-EC2NetworkInterface -SubnetId subnet-1a2b3c4d -Description "my network interface" -Group sg-12345678 -PrivateIpAddress 10.0.0.17
```
**출력:**  

```
Association        :
Attachment         :
AvailabilityZone   : us-west-2c
Description        : my network interface
Groups             : {my-security-group}
MacAddress         : 0a:72:bc:1a:cd:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-17.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.17
PrivateIpAddresses : {}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : pending
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreatePlacementGroup` 사용
<a name="example_ec2_CreatePlacementGroup_section"></a>

다음 코드 예시는 `CreatePlacementGroup`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**배치 그룹 생성**  
이 예시에서는 지정된 이름으로 배치 그룹을 생성합니다.  
명령:  

```
aws ec2 create-placement-group --group-name my-cluster --strategy cluster
```
**파티션 배치 그룹 생성**  
이 예시에서는 5개의 파티션이 있는 `HDFS-Group-A` 파티션 배치 그룹을 만듭니다.  
명령:  

```
aws ec2 create-placement-group --group-name HDFS-Group-A --strategy partition --partition-count 5
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreatePlacementGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-placement-group.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 이름으로 배치 그룹을 생성합니다.**  

```
New-EC2PlacementGroup -GroupName my-placement-group -Strategy cluster
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreatePlacementGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 이름으로 배치 그룹을 생성합니다.**  

```
New-EC2PlacementGroup -GroupName my-placement-group -Strategy cluster
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreatePlacementGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateRoute` 사용
<a name="example_ec2_CreateRoute_section"></a>

다음 코드 예시는 `CreateRoute`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 
+  [Transit Gateway 시작하기](example_vpc_TransitGatewayGettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**라우팅 생성**  
이 예시에서는 지정된 라우팅 테이블에 대한 경로를 생성합니다. 이 경로는 모든 IPv4 트래픽(`0.0.0.0/0`)을 일치시켜 지정된 인터넷 게이트웨이로 라우팅합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 create-route --route-table-id rtb-22574640 --destination-cidr-block 0.0.0.0/0 --gateway-id igw-c0a643a9
```
이 예시에서는 라우팅 테이블 rtb-g8ff4ea2에 경로를 만듭니다. 이 경로는 IPv4 CIDR 블록 10.0.0.0/16에 대한 트래픽을 일치시키고 이를 VPC 피어링 연결인 pcx-111aaa22로 라우팅합니다. 이 라우팅을 사용하면 VPC 피어링 연결에서 트래픽을 피어 VPC로 보낼 수 있습니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 create-route --route-table-id rtb-g8ff4ea2 --destination-cidr-block 10.0.0.0/16 --vpc-peering-connection-id pcx-1a2b3c4d
```
이 예시에서는 지정된 라우팅 테이블에 모든 IPv6 트래픽(`::/0`)과 일치하는 경로를 생성하여 지정된 외부 전용 인터넷 게이트웨이로 라우팅합니다.  
명령:  

```
aws ec2 create-route --route-table-id rtb-dce620b8 --destination-ipv6-cidr-block ::/0 --egress-only-internet-gateway-id eigw-01eadbd45ecd7943f
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-route.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블에 대한 지정된 경로를 생성합니다. 이 경로는 모든 트래픽을 일치시켜 지정된 인터넷 게이트웨이로 보냅니다.**  

```
New-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0 -GatewayId igw-1a2b3c4d
```
**출력:**  

```
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateRoute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블에 대한 지정된 경로를 생성합니다. 이 경로는 모든 트래픽을 일치시켜 지정된 인터넷 게이트웨이로 보냅니다.**  

```
New-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0 -GatewayId igw-1a2b3c4d
```
**출력:**  

```
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateRoute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `CreateRouteTable` 함께 사용
<a name="example_ec2_CreateRouteTable_section"></a>

다음 코드 예시는 `CreateRouteTable`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**라우팅 테이블을 생성하는 방법**  
이 예제에서는 지정된 VPC에 대한 라우팅 테이블을 생성합니다.  
명령:  

```
aws ec2 create-route-table --vpc-id vpc-a01106c2
```
출력:  

```
{
    "RouteTable": {
        "Associations": [],
        "RouteTableId": "rtb-22574640",
        "VpcId": "vpc-a01106c2",
        "PropagatingVgws": [],
        "Tags": [],
        "Routes": [
            {
                "GatewayId": "local",
                "DestinationCidrBlock": "10.0.0.0/16",
                "State": "active"
            }
        ]
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [CreateRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-route-table.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPC에 대한 라우팅 테이블을 생성합니다.**  

```
New-EC2RouteTable -VpcId vpc-12345678
```
**출력:**  

```
Associations    : {}
PropagatingVgws : {}
Routes          : {}
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateRouteTable](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPC에 대한 라우팅 테이블을 생성합니다.**  

```
New-EC2RouteTable -VpcId vpc-12345678
```
**출력:**  

```
Associations    : {}
PropagatingVgws : {}
Routes          : {}
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'aws-sdk-ec2'

# Prerequisites:
#
# - A VPC in Amazon VPC.
# - A subnet in that VPC.
# - A gateway attached to that subnet.
#
# @param ec2_resource [Aws::EC2::Resource] An initialized
#   Amazon Elastic Compute Cloud (Amazon EC2) resource object.
# @param vpc_id [String] The ID of the VPC for the route table.
# @param subnet_id [String] The ID of the subnet for the route table.
# @param gateway_id [String] The ID of the gateway for the route.
# @param destination_cidr_block [String] The destination CIDR block
#   for the route.
# @param tag_key [String] The key portion of the tag for the route table.
# @param tag_value [String] The value portion of the tag for the route table.
# @return [Boolean] true if the route table was created and associated;
#   otherwise, false.
# @example
#   exit 1 unless route_table_created_and_associated?(
#     Aws::EC2::Resource.new(region: 'us-west-2'),
#     'vpc-0b6f769731EXAMPLE',
#     'subnet-03d9303b57EXAMPLE',
#     'igw-06ca90c011EXAMPLE',
#     '0.0.0.0/0',
#     'my-key',
#     'my-value'
#   )
def route_table_created_and_associated?(
  ec2_resource,
  vpc_id,
  subnet_id,
  gateway_id,
  destination_cidr_block,
  tag_key,
  tag_value
)
  route_table = ec2_resource.create_route_table(vpc_id: vpc_id)
  puts "Created route table with ID '#{route_table.id}'."
  route_table.create_tags(
    tags: [
      {
        key: tag_key,
        value: tag_value
      }
    ]
  )
  puts 'Added tags to route table.'
  route_table.create_route(
    destination_cidr_block: destination_cidr_block,
    gateway_id: gateway_id
  )
  puts 'Created route with destination CIDR block ' \
    "'#{destination_cidr_block}' and associated with gateway " \
    "with ID '#{gateway_id}'."
  route_table.associate_with_subnet(subnet_id: subnet_id)
  puts "Associated route table with subnet with ID '#{subnet_id}'."
  true
rescue StandardError => e
  puts "Error creating or associating route table: #{e.message}"
  puts 'If the route table was created but not associated, you should ' \
    'clean up by deleting the route table.'
  false
end

# Example usage:
def run_me
  vpc_id = ''
  subnet_id = ''
  gateway_id = ''
  destination_cidr_block = ''
  tag_key = ''
  tag_value = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage: ruby ec2-ruby-example-create-route-table.rb ' \
      'VPC_ID SUBNET_ID GATEWAY_ID DESTINATION_CIDR_BLOCK ' \
      'TAG_KEY TAG_VALUE REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-create-route-table.rb ' \
      'vpc-0b6f769731EXAMPLE subnet-03d9303b57EXAMPLE igw-06ca90c011EXAMPLE ' \
      "'0.0.0.0/0' my-key my-value us-west-2"
    exit 1
  # If no values are specified at the command prompt, use these default values.
  elsif ARGV.count.zero?
    vpc_id = 'vpc-0b6f769731EXAMPLE'
    subnet_id = 'subnet-03d9303b57EXAMPLE'
    gateway_id = 'igw-06ca90c011EXAMPLE'
    destination_cidr_block = '0.0.0.0/0'
    tag_key = 'my-key'
    tag_value = 'my-value'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    vpc_id = ARGV[0]
    subnet_id = ARGV[1]
    gateway_id = ARGV[2]
    destination_cidr_block = ARGV[3]
    tag_key = ARGV[4]
    tag_value = ARGV[5]
    region = ARGV[6]
  end

  ec2_resource = Aws::EC2::Resource.new(region: region)

  if route_table_created_and_associated?(
    ec2_resource,
    vpc_id,
    subnet_id,
    gateway_id,
    destination_cidr_block,
    tag_key,
    tag_value
  )
    puts 'Route table created and associated.'
  else
    puts 'Route table not created or not associated.'
  end
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateRouteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateRouteTable)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `CreateSecurityGroup` 함께 사용
<a name="example_ec2_CreateSecurityGroup_section"></a>

다음 코드 예시는 `CreateSecurityGroup`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Create an Amazon EC2 security group with a specified name and description.
    /// </summary>
    /// <param name="groupName">The name for the new security group.</param>
    /// <param name="groupDescription">A description of the new security group.</param>
    /// <returns>The group Id of the new security group.</returns>
    public async Task<string> CreateSecurityGroup(string groupName, string groupDescription)
    {
        try
        {
            var response = await _amazonEC2.CreateSecurityGroupAsync(
                new CreateSecurityGroupRequest(groupName, groupDescription));

            // Wait until the security group exists.
            int retries = 5;
            while (retries-- > 0)
            {
                var groups = await DescribeSecurityGroups(response.GroupId);
                if (groups.Any())
                {
                    return response.GroupId;
                }

                Thread.Sleep(5000);
                retries--;
            }
            _logger.LogError($"Unable to find newly created group {groupName}.");
            throw new DoesNotExistException("security group not found");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "ResourceAlreadyExists")
            {
                _logger.LogError(
                    $"A security group with the name {groupName} already exists. {ec2Exception.Message}");
            }
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while creating the security group.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [CreateSecurityGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateSecurityGroup)을 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_create_security_group
#
# This function creates an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Parameters:
#       -n security_group_name - The name of the security group.
#       -d security_group_description - The description of the security group.
#
# Returns:
#       The ID of the created security group, or an error message if the operation fails.
# And:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_create_security_group() {
  local security_group_name security_group_description response

  # Function to display usage information
  function usage() {
    echo "function ec2_create_security_group"
    echo "Creates an Amazon Elastic Compute Cloud (Amazon EC2) security group."
    echo "  -n security_group_name - The name of the security group."
    echo "  -d security_group_description - The description of the security group."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "n:d:h" option; do
    case "${option}" in
      n) security_group_name="${OPTARG}" ;;
      d) security_group_description="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$security_group_name" ]]; then
    errecho "ERROR: You must provide a security group name with the -n parameter."
    return 1
  fi

  if [[ -z "$security_group_description" ]]; then
    errecho "ERROR: You must provide a security group description with the -d parameter."
    return 1
  fi

  # Create the security group
  response=$(aws ec2 create-security-group \
    --group-name "$security_group_name" \
    --description "$security_group_description" \
    --query "GroupId" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports create-security-group operation failed."
    errecho "$response"
    return 1
  }

  echo "$response"
  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateSecurityGroup)을 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Create a security group.
/*!
  \param groupName: A security group name.
  \param description: A description.
  \param vpcID: A virtual private cloud (VPC) ID.
  \param[out] groupIDResult: A string to receive the group ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::createSecurityGroup(const Aws::String &groupName,
                                      const Aws::String &description,
                                      const Aws::String &vpcID,
                                      Aws::String &groupIDResult,
                                      const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;


    groupIDResult = outcome.GetResult().GetGroupId();

    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [CreateSecurityGroup](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/CreateSecurityGroup)을 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**EC2-Classic에 대한 보안 그룹을 생성하는 방법**  
이 예제에서는 이름이 `MySecurityGroup`인 보안 그룹을 생성합니다.  
명령:  

```
aws ec2 create-security-group --group-name MySecurityGroup --description "My security group"
```
출력:  

```
{
    "GroupId": "sg-903004f8"
}
```
**EC2-VPC에 대한 보안 그룹을 생성하는 방법**  
이 예제에서는 지정된 VPC에 대해 이름이 `MySecurityGroup`인 보안 그룹을 생성합니다.  
명령:  

```
aws ec2 create-security-group --group-name MySecurityGroup --description "My security group" --vpc-id vpc-1a2b3c4d
```
출력:  

```
{
    "GroupId": "sg-903004f8"
}
```
자세한 내용은 *AWS Command Line Interface 사용 설명서*의 보안 그룹 사용을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [CreateSecurityGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-security-group.html)을 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Creates a new security group asynchronously with the specified group name, description, and VPC ID. It also
     * authorizes inbound traffic on ports 80 and 22 from the specified IP address.
     *
     * @param groupName    the name of the security group to create
     * @param groupDesc    the description of the security group
     * @param vpcId        the ID of the VPC in which to create the security group
     * @param myIpAddress  the IP address from which to allow inbound traffic (e.g., "192.168.1.1/0" to allow traffic from
     *                     any IP address in the 192.168.1.0/24 subnet)
     * @return a CompletableFuture that, when completed, returns the ID of the created security group
     * @throws RuntimeException if there was a failure creating the security group or authorizing the inbound traffic
     */
    public CompletableFuture<String> createSecurityGroupAsync(String groupName, String groupDesc, String vpcId, String myIpAddress) {
        CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder()
            .groupName(groupName)
            .description(groupDesc)
            .vpcId(vpcId)
            .build();

        return getAsyncClient().createSecurityGroup(createRequest)
            .thenCompose(createResponse -> {
                String groupId = createResponse.groupId();
                IpRange ipRange = IpRange.builder()
                    .cidrIp(myIpAddress + "/32")
                    .build();

                IpPermission ipPerm = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(80)
                    .fromPort(80)
                    .ipRanges(ipRange)
                    .build();

                IpPermission ipPerm2 = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(22)
                    .fromPort(22)
                    .ipRanges(ipRange)
                    .build();

                AuthorizeSecurityGroupIngressRequest authRequest = AuthorizeSecurityGroupIngressRequest.builder()
                    .groupName(groupName)
                    .ipPermissions(ipPerm, ipPerm2)
                    .build();

                return getAsyncClient().authorizeSecurityGroupIngress(authRequest)
                    .thenApply(authResponse -> groupId);
            })
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    if (exception instanceof CompletionException && exception.getCause() instanceof Ec2Exception) {
                        throw (Ec2Exception) exception.getCause();
                    } else {
                        throw new RuntimeException("Failed to create security group: " + exception.getMessage(), exception);
                    }
                }
            });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [CreateSecurityGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateSecurityGroup)을 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { CreateSecurityGroupCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Creates a security group.
 * @param {{ groupName: string, description: string }} options
 */
export const main = async ({ groupName, description }) => {
  const client = new EC2Client({});
  const command = new CreateSecurityGroupCommand({
    // Up to 255 characters in length. Cannot start with sg-.
    GroupName: groupName,
    // Up to 255 characters in length.
    Description: description,
  });

  try {
    const { GroupId } = await client.send(command);
    console.log(GroupId);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}.`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateAccountAlias](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateSecurityGroupCommand)을 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun createEC2SecurityGroup(
    groupNameVal: String?,
    groupDescVal: String?,
    vpcIdVal: String?,
): String? {
    val request =
        CreateSecurityGroupRequest {
            groupName = groupNameVal
            description = groupDescVal
            vpcId = vpcIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val resp = ec2.createSecurityGroup(request)
        val ipRange =
            IpRange {
                cidrIp = "0.0.0.0/0"
            }

        val ipPerm =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 80
                fromPort = 80
                ipRanges = listOf(ipRange)
            }

        val ipPerm2 =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 22
                fromPort = 22
                ipRanges = listOf(ipRange)
            }

        val authRequest =
            AuthorizeSecurityGroupIngressRequest {
                groupName = groupNameVal
                ipPermissions = listOf(ipPerm, ipPerm2)
            }
        ec2.authorizeSecurityGroupIngress(authRequest)
        println("Successfully added ingress policy to Security Group $groupNameVal")
        return resp.groupId
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [CreateSecurityGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPC에 대한 보안 그룹을 생성합니다.**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group" -VpcId vpc-12345678
```
**출력:**  

```
sg-12345678
```
**예제 2: 이 예제에서는 EC2-Classic에 대한 보안 그룹을 생성합니다.**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group"
```
**출력:**  

```
sg-45678901
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateSecurityGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPC에 대한 보안 그룹을 생성합니다.**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group" -VpcId vpc-12345678
```
**출력:**  

```
sg-12345678
```
**예제 2: 이 예제에서는 EC2-Classic에 대한 보안 그룹을 생성합니다.**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group"
```
**출력:**  

```
sg-45678901
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateSecurityGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class SecurityGroupWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions."""

    def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None):
        """
        Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param security_group: The ID of a security group to manage. This is a high-level identifier
                               that represents the security group.
        """
        self.ec2_client = ec2_client
        self.security_group = security_group

    @classmethod
    def from_client(cls) -> "SecurityGroupWrapper":
        """
        Creates a SecurityGroupWrapper instance with a default EC2 client.

        :return: An instance of SecurityGroupWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create(self, group_name: str, group_description: str) -> str:
        """
        Creates a security group in the default virtual private cloud (VPC) of the current account.

        :param group_name: The name of the security group to create.
        :param group_description: The description of the security group to create.
        :return: The ID of the newly created security group.
        :raise Handles AWS SDK service-level ClientError, with special handling for ResourceAlreadyExists
        """
        try:
            response = self.ec2_client.create_security_group(
                GroupName=group_name, Description=group_description
            )
            self.security_group = response["GroupId"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExists":
                logger.error(
                    f"Security group '{group_name}' already exists. Please choose a different name."
                )
            raise
        else:
            return self.security_group
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateSecurityGroup](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateSecurityGroup)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
# This code example does the following:
# 1. Creates an Amazon Elastic Compute Cloud (Amazon EC2) security group.
# 2. Adds inbound rules to the security group.
# 3. Displays information about available security groups.
# 4. Deletes the security group.

require 'aws-sdk-ec2'

# Creates an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Prerequisites:
#
# - A VPC in Amazon Virtual Private Cloud (Amazon VPC).
#
# @param ec2_client [Aws::EC2::Client] An initialized
#   Amazon EC2 client.
# @param group_name [String] A name for the security group.
# @param description [String] A description for the security group.
# @param vpc_id [String] The ID of the VPC for the security group.
# @return [String] The ID of security group that was created.
# @example
#   puts create_security_group(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'my-security-group',
#     'This is my security group.',
#     'vpc-6713dfEX'
#   )
def create_security_group(ec2_client, group_name, description, vpc_id)
  security_group = ec2_client.create_security_group(
    group_name: group_name,
    description: description,
    vpc_id: vpc_id
  )
  puts "Created security group '#{group_name}' with ID " \
    "'#{security_group.group_id}' in VPC with ID '#{vpc_id}'."
  security_group.group_id
rescue StandardError => e
  puts "Error creating security group: #{e.message}"
  'Error'
end

# Adds an inbound rule to an Amazon Elastic Compute Cloud (Amazon EC2)
# security group.
#
# Prerequisites:
#
# - The security group.
#
# @param ec2_client [Aws::EC2::Client] An initialized Amazon EC2 client.
# @param security_group_id [String] The ID of the security group.
# @param ip_protocol [String] The network protocol for the inbound rule.
# @param from_port [String] The originating port for the inbound rule.
# @param to_port [String] The destination port for the inbound rule.
# @param cidr_ip_range [String] The CIDR IP range for the inbound rule.
# @return
# @example
#   exit 1 unless security_group_ingress_authorized?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'sg-030a858e078f1b9EX',
#     'tcp',
#     '80',
#     '80',
#     '0.0.0.0/0'
#   )
def security_group_ingress_authorized?(
  ec2_client, security_group_id, ip_protocol, from_port, to_port, cidr_ip_range
)
  ec2_client.authorize_security_group_ingress(
    group_id: security_group_id,
    ip_permissions: [
      {
        ip_protocol: ip_protocol,
        from_port: from_port,
        to_port: to_port,
        ip_ranges: [
          {
            cidr_ip: cidr_ip_range
          }
        ]
      }
    ]
  )
  puts "Added inbound rule to security group '#{security_group_id}' for protocol " \
    "'#{ip_protocol}' from port '#{from_port}' to port '#{to_port}' " \
    "with CIDR IP range '#{cidr_ip_range}'."
  true
rescue StandardError => e
  puts "Error adding inbound rule to security group: #{e.message}"
  false
end

# Refactored method to simplify complexity for describing security group permissions
def format_port_information(perm)
  from_port_str = perm.from_port == '-1' || perm.from_port == -1 ? 'All' : perm.from_port.to_s
  to_port_str = perm.to_port == '-1' || perm.to_port == -1 ? 'All' : perm.to_port.to_s
  { from_port: from_port_str, to_port: to_port_str }
end

# Displays information about a security group's IP permissions set in
# Amazon Elastic Compute Cloud (Amazon EC2).
def describe_security_group_permissions(perm)
  ports = format_port_information(perm)

  print "  Protocol: #{perm.ip_protocol == '-1' ? 'All' : perm.ip_protocol}"
  print ", From: #{ports[:from_port]}, To: #{ports[:to_port]}"

  print ", CIDR IPv6: #{perm.ipv_6_ranges[0].cidr_ipv_6}" if perm.key?(:ipv_6_ranges) && perm.ipv_6_ranges.count.positive?

  print ", CIDR IPv4: #{perm.ip_ranges[0].cidr_ip}" if perm.key?(:ip_ranges) && perm.ip_ranges.count.positive?
  print "\n"
end

# Displays information about available security groups in
# Amazon Elastic Compute Cloud (Amazon EC2).
def describe_security_groups(ec2_client)
  response = ec2_client.describe_security_groups

  if response.security_groups.count.positive?
    response.security_groups.each do |sg|
      display_group_details(sg)
    end
  else
    puts 'No security groups found.'
  end
rescue StandardError => e
  puts "Error getting information about security groups: #{e.message}"
end

# Helper method to display the details of security groups
def display_group_details(sg)
  puts '-' * (sg.group_name.length + 13)
  puts "Name:        #{sg.group_name}"
  puts "Description: #{sg.description}"
  puts "Group ID:    #{sg.group_id}"
  puts "Owner ID:    #{sg.owner_id}"
  puts "VPC ID:      #{sg.vpc_id}"

  display_group_tags(sg.tags) if sg.tags.count.positive?
  display_group_permissions(sg)
end

def display_group_tags(tags)
  puts 'Tags:'
  tags.each do |tag|
    puts "  Key: #{tag.key}, Value: #{tag.value}"
  end
end

def display_group_permissions(sg)
  if sg.ip_permissions.count.positive?
    puts 'Inbound rules:'
    sg.ip_permissions.each do |p|
      describe_security_group_permissions(p)
    end
  end

  return if sg.ip_permissions_egress.empty?

  puts 'Outbound rules:'
  sg.ip_permissions_egress.each do |p|
    describe_security_group_permissions(p)
  end
end

# Deletes an Amazon Elastic Compute Cloud (Amazon EC2)
# security group.
def security_group_deleted?(ec2_client, security_group_id)
  ec2_client.delete_security_group(group_id: security_group_id)
  puts "Deleted security group '#{security_group_id}'."
  true
rescue StandardError => e
  puts "Error deleting security group: #{e.message}"
  false
end

# Example usage with refactored run_me to reduce complexity
def run_me
  group_name, description, vpc_id, ip_protocol_http, from_port_http, to_port_http, \
  cidr_ip_range_http, ip_protocol_ssh, from_port_ssh, to_port_ssh, \
  cidr_ip_range_ssh, region = process_arguments
  ec2_client = Aws::EC2::Client.new(region: region)

  security_group_id = attempt_create_security_group(ec2_client, group_name, description, vpc_id)
  security_group_exists = security_group_id != 'Error'

  if security_group_exists
    add_inbound_rules(ec2_client, security_group_id, ip_protocol_http, from_port_http, to_port_http, cidr_ip_range_http)
    add_inbound_rules(ec2_client, security_group_id, ip_protocol_ssh, from_port_ssh, to_port_ssh, cidr_ip_range_ssh)
  end

  describe_security_groups(ec2_client)
  attempt_delete_security_group(ec2_client, security_group_id) if security_group_exists
end

def process_arguments
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    display_help
    exit 1
  elsif ARGV.count.zero?
    default_values
  else
    ARGV
  end
end

def attempt_create_security_group(ec2_client, group_name, description, vpc_id)
  puts 'Attempting to create security group...'
  security_group_id = create_security_group(ec2_client, group_name, description, vpc_id)
  puts 'Could not create security group. Skipping this step.' if security_group_id == 'Error'
  security_group_id
end

def add_inbound_rules(ec2_client, security_group_id, ip_protocol, from_port, to_port, cidr_ip_range)
  puts 'Attempting to add inbound rules to security group...'
  return if security_group_ingress_authorized?(ec2_client, security_group_id, ip_protocol, from_port, to_port,
                                               cidr_ip_range)

  puts 'Could not add inbound rule to security group. Skipping this step.'
end

def attempt_delete_security_group(ec2_client, security_group_id)
  puts "\nAttempting to delete security group..."
  return if security_group_deleted?(ec2_client, security_group_id)

  puts 'Could not delete security group. You must delete it yourself.'
end

def display_help
  puts 'Usage:   ruby ec2-ruby-example-security-group.rb ' \
    'GROUP_NAME DESCRIPTION VPC_ID IP_PROTOCOL_1 FROM_PORT_1 TO_PORT_1 ' \
    'CIDR_IP_RANGE_1 IP_PROTOCOL_2 FROM_PORT_2 TO_PORT_2 ' \
    'CIDR_IP_RANGE_2 REGION'
  puts 'Example: ruby ec2-ruby-example-security-group.rb ' \
    "my-security-group 'This is my security group.' vpc-6713dfEX " \
    "tcp 80 80 '0.0.0.0/0' tcp 22 22 '0.0.0.0/0' us-west-2"
end

def default_values
  [
    'my-security-group', 'This is my security group.', 'vpc-6713dfEX', 'tcp', '80', '80',
    '0.0.0.0/0', 'tcp', '22', '22', '0.0.0.0/0', 'us-west-2'
  ]
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateSecurityGroup](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateSecurityGroup)을 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn create_security_group(
        &self,
        name: &str,
        description: &str,
    ) -> Result<SecurityGroup, EC2Error> {
        tracing::info!("Creating security group {name}");
        let create_output = self
            .client
            .create_security_group()
            .group_name(name)
            .description(description)
            .send()
            .await
            .map_err(EC2Error::from)?;

        let group_id = create_output
            .group_id
            .ok_or_else(|| EC2Error::new("Missing security group id after creation"))?;

        let group = self
            .describe_security_group(&group_id)
            .await?
            .ok_or_else(|| {
                EC2Error::new(format!("Could not find security group with id {group_id}"))
            })?;

        tracing::info!("Created security group {name} as {group_id}");

        Ok(group)
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateSecurityGroup](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.create_security_group)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->createsecuritygroup(                 " oo_result is returned for testing purposes. "
          iv_description = 'Security group example'
          iv_groupname = iv_security_group_name
          iv_vpcid = iv_vpc_id ).
        MESSAGE 'Security group created.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateSecurityGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Create a new security group.
    /// 
    /// - Parameters:
    ///   - groupName: The name of the group to create.
    ///   - groupDescription: A description of the new security group.
    ///
    /// - Returns: The ID string of the new security group.
    func createSecurityGroup(name groupName: String, description groupDescription: String) async -> String? {
        do {
            let output = try await ec2Client.createSecurityGroup(
                input: CreateSecurityGroupInput(
                    description: groupDescription,
                    groupName: groupName
                )
            )

            return output.groupId
        } catch {
            print("*** Error creating the security group: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [CreateSecurityGroup](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/createsecuritygroup(input:))을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateSnapshot` 사용
<a name="example_ec2_CreateSnapshot_section"></a>

다음 코드 예시는 `CreateSnapshot`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스냅샷 생성**  
이 예시에서는 볼륨 ID가 `vol-1234567890abcdef0`의 볼륨 스냅샷과 스냅샷을 식별할 수 있는 간단한 설명을 생성합니다.  
명령:  

```
aws ec2 create-snapshot --volume-id vol-1234567890abcdef0 --description "This is my root volume snapshot"
```
출력:  

```
{
    "Description": "This is my root volume snapshot",
    "Tags": [],
    "Encrypted": false,
    "VolumeId": "vol-1234567890abcdef0",
    "State": "pending",
    "VolumeSize": 8,
    "StartTime": "2018-02-28T21:06:01.000Z",
    "Progress": "",
    "OwnerId": "012345678910",
    "SnapshotId": "snap-066877671789bd71b"
}
```
**태그를 사용하여 스냅샷 생성**  
이 예시에서는 스냅샷을 생성하고 purpose=prod 및 costcenter=123이라는 두 개의 태그를 적용합니다.  
명령:  

```
aws ec2 create-snapshot --volume-id vol-1234567890abcdef0 --description 'Prod backup' --tag-specifications 'ResourceType=snapshot,Tags=[{Key=purpose,Value=prod},{Key=costcenter,Value=123}]'
```
출력:  

```
{
    "Description": "Prod backup",
    "Tags": [
        {
            "Value": "prod",
            "Key": "purpose"
        },
        {
            "Value": "123",
            "Key": "costcenter"
        }
     ],
     "Encrypted": false,
     "VolumeId": "vol-1234567890abcdef0",
     "State": "pending",
     "VolumeSize": 8,
     "StartTime": "2018-02-28T21:06:06.000Z",
     "Progress": "",
     "OwnerId": "012345678910",
     "SnapshotId": "snap-09ed24a70bc19bbe4"
 }
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-snapshot.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 볼륨의 스냅샷을 생성합니다.**  

```
New-EC2Snapshot -VolumeId vol-12345678 -Description "This is a test"
```
**출력:**  

```
DataEncryptionKeyId :
Description         : This is a test
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            :
SnapshotId          : snap-12345678
StartTime           : 12/22/2015 1:28:42 AM
State               : pending
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 20
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateSnapshot](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 볼륨의 스냅샷을 생성합니다.**  

```
New-EC2Snapshot -VolumeId vol-12345678 -Description "This is a test"
```
**출력:**  

```
DataEncryptionKeyId :
Description         : This is a test
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            :
SnapshotId          : snap-12345678
StartTime           : 12/22/2015 1:28:42 AM
State               : pending
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 20
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateSpotDatafeedSubscription` 사용
<a name="example_ec2_CreateSpotDatafeedSubscription_section"></a>

다음 코드 예시는 `CreateSpotDatafeedSubscription`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스팟 인스턴스 데이터 피드 생성**  
다음 `create-spot-datafeed-subscription` 예시에서는 스팟 인스턴스 데이터 피드를 생성합니다.  

```
aws ec2 create-spot-datafeed-subscription \
    --bucket amzn-s3-demo-bucket \
    --prefix spot-data-feed
```
출력:  

```
{
    "SpotDatafeedSubscription": {
        "Bucket": "amzn-s3-demo-bucket",
        "OwnerId": "123456789012",
        "Prefix": "spot-data-feed",
        "State": "Active"
    }
}
```
데이터 피드는 지정한 Amazon S3 버킷에 저장됩니다. 이 데이터 피드의 파일 이름은 다음과 같은 형식을 따릅니다.  

```
amzn-s3-demo-bucket.s3.amazonaws.com/spot-data-feed/123456789012.YYYY-MM-DD-HH.n.abcd1234.gz
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [스팟 인스턴스 데이터 피드](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateSpotDatafeedSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-spot-datafeed-subscription.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 스팟 인스턴스 데이터 피드를 생성합니다.**  

```
New-EC2SpotDatafeedSubscription -Bucket amzn-s3-demo-bucket -Prefix spotdata
```
**출력:**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 스팟 인스턴스 데이터 피드를 생성합니다.**  

```
New-EC2SpotDatafeedSubscription -Bucket amzn-s3-demo-bucket -Prefix spotdata
```
**출력:**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `CreateSubnet` 함께 사용
<a name="example_ec2_CreateSubnet_section"></a>

다음 코드 예시는 `CreateSubnet`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 
+  [Transit Gateway 시작하기](example_vpc_TransitGatewayGettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**예제 1: IPv4 CIDR 블록만 사용하여 서브넷을 생성하는 방법**  
다음 `create-subnet` 예제에서는 지정된 IPv4 CIDR 블록을 사용하여 지정된 VPC에서 서브넷을 생성합니다.  

```
aws ec2 create-subnet \
    --vpc-id vpc-081ec835f3EXAMPLE \
    --cidr-block 10.0.0.0/24 \
    --tag-specifications ResourceType=subnet,Tags=[{Key=Name,Value=my-ipv4-only-subnet}]
```
출력:  

```
{
    "Subnet": {
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az2",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.0.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0e99b93155EXAMPLE",
        "VpcId": "vpc-081ec835f3EXAMPLE",
        "OwnerId": "123456789012",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-ipv4-only-subnet"
            }
        ],
        "SubnetArn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0e99b93155EXAMPLE"
    }
}
```
**예제 2: IPv4 및 IPv6 CIDR 블록을 모두 사용하여 서브넷을 생성하는 방법**  
다음 `create-subnet` 예제에서는 지정된 IPv4 및 IPv6 CIDR 블록을 사용하여 지정된 VPC에서 서브넷을 생성합니다.  

```
aws ec2 create-subnet \
    --vpc-id vpc-081ec835f3EXAMPLE \
    --cidr-block 10.0.0.0/24 \
    --ipv6-cidr-block 2600:1f16:cfe:3660::/64 \
    --tag-specifications ResourceType=subnet,Tags=[{Key=Name,Value=my-ipv4-ipv6-subnet}]
```
출력:  

```
{
    "Subnet": {
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az2",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.0.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0736441d38EXAMPLE",
        "VpcId": "vpc-081ec835f3EXAMPLE",
        "OwnerId": "123456789012",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [
            {
                "AssociationId": "subnet-cidr-assoc-06c5f904499fcc623",
                "Ipv6CidrBlock": "2600:1f13:cfe:3660::/64",
                "Ipv6CidrBlockState": {
                    "State": "associating"
                }
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-ipv4-ipv6-subnet"
            }
        ],
        "SubnetArn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0736441d38EXAMPLE"
    }
}
```
**예제 3: IPv6 CIDR 블록만 사용하여 서브넷을 생성하는 방법**  
다음 `create-subnet` 예제에서는 지정된 IPv6 CIDR 블록을 사용하여 지정된 VPC에서 서브넷을 생성합니다.  

```
aws ec2 create-subnet \
    --vpc-id vpc-081ec835f3EXAMPLE \
    --ipv6-native \
    --ipv6-cidr-block 2600:1f16:115:200::/64 \
    --tag-specifications ResourceType=subnet,Tags=[{Key=Name,Value=my-ipv6-only-subnet}]
```
출력:  

```
{
    "Subnet": {
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az2",
        "AvailableIpAddressCount": 0,
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-03f720e7deEXAMPLE",
        "VpcId": "vpc-081ec835f3EXAMPLE",
        "OwnerId": "123456789012",
        "AssignIpv6AddressOnCreation": true,
        "Ipv6CidrBlockAssociationSet": [
            {
                "AssociationId": "subnet-cidr-assoc-01ef639edde556709",
                "Ipv6CidrBlock": "2600:1f13:cfe:3660::/64",
                "Ipv6CidrBlockState": {
                    "State": "associating"
                }
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-ipv6-only-subnet"
            }
        ],
        "SubnetArn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-03f720e7deEXAMPLE"
    }
}
```
자세한 내용은 *Amazon VPC 사용 설명서*의 [VPC 및 서브넷](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [CreateSubnet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-subnet.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 CIDR로 서브넷을 생성합니다.**  

```
New-EC2Subnet -VpcId vpc-12345678 -CidrBlock 10.0.0.0/24
```
**출력:**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : pending
SubnetId                : subnet-1a2b3c4d
Tag                     : {}
VpcId                   : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateSubnet](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 CIDR로 서브넷을 생성합니다.**  

```
New-EC2Subnet -VpcId vpc-12345678 -CidrBlock 10.0.0.0/24
```
**출력:**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : pending
SubnetId                : subnet-1a2b3c4d
Tag                     : {}
VpcId                   : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateSubnet](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'aws-sdk-ec2'

# Creates a subnet within a virtual private cloud (VPC) in
# Amazon Virtual Private Cloud (Amazon VPC) and then tags
# the subnet.
#
# Prerequisites:
#
# - A VPC in Amazon VPC.
#
# @param ec2_resource [Aws::EC2::Resource] An initialized
#   Amazon Elastic Compute Cloud (Amazon EC2) resource object.
# @param vpc_id [String] The ID of the VPC for the subnet.
# @param cidr_block [String] The IPv4 CIDR block for the subnet.
# @param availability_zone [String] The ID of the Availability Zone
#   for the subnet.
# @param tag_key [String] The key portion of the tag for the subnet.
# @param tag_vlue [String] The value portion of the tag for the subnet.
# @return [Boolean] true if the subnet was created and tagged;
#   otherwise, false.
# @example
#   exit 1 unless subnet_created_and_tagged?(
#     Aws::EC2::Resource.new(region: 'us-west-2'),
#     'vpc-6713dfEX',
#     '10.0.0.0/24',
#     'us-west-2a',
#     'my-key',
#     'my-value'
#   )
def subnet_created_and_tagged?(
  ec2_resource,
  vpc_id,
  cidr_block,
  availability_zone,
  tag_key,
  tag_value
)
  subnet = ec2_resource.create_subnet(
    vpc_id: vpc_id,
    cidr_block: cidr_block,
    availability_zone: availability_zone
  )
  subnet.create_tags(
    tags: [
      {
        key: tag_key,
        value: tag_value
      }
    ]
  )
  puts "Subnet created with ID '#{subnet.id}' in VPC with ID '#{vpc_id}' " \
    "and CIDR block '#{cidr_block}' in availability zone " \
    "'#{availability_zone}' and tagged with key '#{tag_key}' and " \
    "value '#{tag_value}'."
  true
rescue StandardError => e
  puts "Error creating or tagging subnet: #{e.message}"
  false
end

# Example usage:
def run_me
  vpc_id = ''
  cidr_block = ''
  availability_zone = ''
  tag_key = ''
  tag_value = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-create-subnet.rb ' \
      'VPC_ID CIDR_BLOCK AVAILABILITY_ZONE TAG_KEY TAG_VALUE REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-create-subnet.rb ' \
      'vpc-6713dfEX 10.0.0.0/24 us-west-2a my-key my-value us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  elsif ARGV.count.zero?
    vpc_id = 'vpc-6713dfEX'
    cidr_block = '10.0.0.0/24'
    availability_zone = 'us-west-2a'
    tag_key = 'my-key'
    tag_value = 'my-value'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    vpc_id = ARGV[0]
    cidr_block = ARGV[1]
    availability_zone = ARGV[2]
    tag_key = ARGV[3]
    tag_value = ARGV[4]
    region = ARGV[5]
  end

  ec2_resource = Aws::EC2::Resource.new(region: region)

  if subnet_created_and_tagged?(
    ec2_resource,
    vpc_id,
    cidr_block,
    availability_zone,
    tag_key,
    tag_value
  )
    puts 'Subnet created and tagged.'
  else
    puts 'Subnet not created or not tagged.'
  end
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateSubnet](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateSubnet)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `CreateTags` 함께 사용
<a name="example_ec2_CreateTags_section"></a>

다음 코드 예시는 `CreateTags`의 사용 방법을 보여 줍니다.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Add or overwrite only the specified tags for the specified Amazon Elastic Compute Cloud (Amazon EC2) resource or resources.
/*!
  \param resources: The resources for the tags.
  \param tags: Vector of tags.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::createTags(const Aws::Vector<Aws::String> &resources,
                             const Aws::Vector<Aws::EC2::Model::Tag> &tags,
                             const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::CreateTagsRequest createTagsRequest;
    createTagsRequest.SetResources(resources);
    createTagsRequest.SetTags(tags);

    Aws::EC2::Model::CreateTagsOutcome outcome = ec2Client.CreateTags(createTagsRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully created tags for resources" << std::endl;
    } else {
        std::cerr << "Failed to create tags for resources, " << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [CreateTags](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/CreateTags)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 리소스에 태그 추가**  
다음 `create-tags` 예제에서는 지정된 이미지에 `Stack=production` 태그를 추가하거나 태그 키가 `Stack`인 AMI의 기존 태그를 덮어씁니다.  

```
aws ec2 create-tags \
    --resources ami-1234567890abcdef0 \
    --tags Key=Stack,Value=production
```
이 명령은 출력을 생성하지 않습니다.  
**예시 2: 여러 리소스에 태그 추가**  
다음 `create-tags` 예제에서는 AMI와 인스턴스에 대해 두 개의 태그를 추가하거나 덮어씁니다. 태그 중 하나에서 키(`webserver`)는 있지만 값이 없습니다(값이 빈 문자열로 설정됨). 다른 태그에는 키(`stack`)와 값(`Production`)이 있습니다.  

```
aws ec2 create-tags \
    --resources ami-1a2b3c4d i-1234567890abcdef0 \
    --tags Key=webserver,Value=   Key=stack,Value=Production
```
이 명령은 출력을 생성하지 않습니다.  
**예시 3: 특수 문자가 포함된 태그 추가**  
다음 `create-tags` 예제에서는 인스턴스에 `[Group]=test` 태그를 추가합니다. 대괄호([ 및 ])는 이스케이프해야 하는 특수 문자입니다. 다음 예제에서는 각 환경에 적합한 줄 연속 문자도 사용합니다.  
Windows를 사용하는 경우 다음과 같이 특수 문자가 있는 요소를 큰따옴표(")로 묶은 다음, 각 큰따옴표 문자 앞에 백슬래시(\$1)를 붙입니다.  

```
aws ec2 create-tags ^
    --resources i-1234567890abcdef0 ^
    --tags Key=\"[Group]\",Value=test
```
Windows PowerShell을 사용하는 경우 다음과 같이 특수 문자가 있는 값을 큰따옴표(")로 묶고 각 큰따옴표 문자 앞에 백슬래시(\$1)를 붙인 다음, 전체 키 및 값 구조를 작은따옴표(')로 묶습니다.  

```
aws ec2 create-tags `
    --resources i-1234567890abcdef0 `
    --tags 'Key=\"[Group]\",Value=test'
```
Linux 또는 OS X를 사용하는 경우 다음과 같이 특수 문자가 있는 요소를 큰따옴표(")로 묶은 다음, 전체 키 및 값 구조를 작은따옴표(')로 묶습니다.  

```
aws ec2 create-tags \
    --resources i-1234567890abcdef0 \
    --tags 'Key="[Group]",Value=test'
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [Amazon EC2 리소스에 태그 지정](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-tags.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 리소스에 단일 태그를 추가합니다. 태그 키는 'myTag '이고 태그 값은 'myTagValue'입니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
New-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag"; Value="myTagValue" }
```
**예제 2: 이 예제에서는 지정된 리소스에 대해 지정된 태그를 업데이트하거나 추가합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
New-EC2Tag -Resource i-12345678 -Tag @( @{ Key="myTag"; Value="newTagValue" }, @{ Key="test"; Value="anotherTagValue" } )
```
**예제 3: PowerShell 버전 2에서 Tag 파라미터에 대해 태그를 생성하려면 New-Object를 사용해야 합니다.**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

New-EC2Tag -Resource i-12345678 -Tag $tag
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateTags](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 리소스에 단일 태그를 추가합니다. 태그 키는 'myTag '이고 태그 값은 'myTagValue'입니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
New-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag"; Value="myTagValue" }
```
**예제 2: 이 예제에서는 지정된 리소스에 대해 지정된 태그를 업데이트하거나 추가합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
New-EC2Tag -Resource i-12345678 -Tag @( @{ Key="myTag"; Value="newTagValue" }, @{ Key="test"; Value="anotherTagValue" } )
```
**예제 3: PowerShell 버전 2에서 Tag 파라미터에 대해 태그를 생성하려면 New-Object를 사용해야 합니다.**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

New-EC2Tag -Resource i-12345678 -Tag $tag
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예제에서는 인스턴스를 만든 후 이름 태그를 적용합니다.  

```
    pub async fn create_instance<'a>(
        &self,
        image_id: &'a str,
        instance_type: InstanceType,
        key_pair: &'a KeyPairInfo,
        security_groups: Vec<&'a SecurityGroup>,
    ) -> Result<String, EC2Error> {
        let run_instances = self
            .client
            .run_instances()
            .image_id(image_id)
            .instance_type(instance_type)
            .key_name(
                key_pair
                    .key_name()
                    .ok_or_else(|| EC2Error::new("Missing key name when launching instance"))?,
            )
            .set_security_group_ids(Some(
                security_groups
                    .iter()
                    .filter_map(|sg| sg.group_id.clone())
                    .collect(),
            ))
            .min_count(1)
            .max_count(1)
            .send()
            .await?;

        if run_instances.instances().is_empty() {
            return Err(EC2Error::new("Failed to create instance"));
        }

        let instance_id = run_instances.instances()[0].instance_id().unwrap();
        let response = self
            .client
            .create_tags()
            .resources(instance_id)
            .tags(
                Tag::builder()
                    .key("Name")
                    .value("From SDK Examples")
                    .build(),
            )
            .send()
            .await;

        match response {
            Ok(_) => tracing::info!("Created {instance_id} and applied tags."),
            Err(err) => {
                tracing::info!("Error applying tags to {instance_id}: {err:?}");
                return Err(err.into());
            }
        }

        tracing::info!("Instance is created.");

        Ok(instance_id.to_string())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateTags](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.create_tags)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateVolume` 사용
<a name="example_ec2_CreateVolume_section"></a>

다음 코드 예시는 `CreateVolume`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**비어 있는 범용 SSD(gp2) 볼륨 생성**  
다음 `create-volume` 지정된 가용 영역에 80GiB 범용 SSD(gp2) 볼륨을 생성합니다. 현재 리전은 반드시 `us-east-1`이거나 `--region` 파라미터를 추가하여 명령의 리전을 지정할 수 있습니다.  

```
aws ec2 create-volume \
    --volume-type gp2 \
    --size 80 \
    --availability-zone us-east-1a
```
출력:  

```
{
    "AvailabilityZone": "us-east-1a",
    "Tags": [],
    "Encrypted": false,
    "VolumeType": "gp2",
    "VolumeId": "vol-1234567890abcdef0",
    "State": "creating",
    "Iops": 240,
    "SnapshotId": "",
    "CreateTime": "YYYY-MM-DDTHH:MM:SS.000Z",
    "Size": 80
}
```
볼륨 유형을 지정하지 않으면 기본 볼륨 유형은 `gp2`입니다.  

```
aws ec2 create-volume \
    --size 80 \
    --availability-zone us-east-1a
```
**예시 2: 스냅샷에서 프로비저닝된 IOPS SSD(io1) 볼륨 생성**  
다음 `create-volume` 예시에서는 지정된 스냅샷을 사용하여 지정된 가용 영역에 1000개의 프로비저닝된 IOPS를 가진 프로비저닝된 IOPS SSD(io1) 볼륨을 생성합니다.  

```
aws ec2 create-volume \
    --volume-type io1 \
    --iops 1000 \
    --snapshot-id snap-066877671789bd71b \
    --availability-zone us-east-1a
```
출력:  

```
{
    "AvailabilityZone": "us-east-1a",
    "Tags": [],
    "Encrypted": false,
    "VolumeType": "io1",
    "VolumeId": "vol-1234567890abcdef0",
    "State": "creating",
    "Iops": 1000,
    "SnapshotId": "snap-066877671789bd71b",
    "CreateTime": "YYYY-MM-DDTHH:MM:SS.000Z",
    "Size": 500
}
```
**예시 3: 암호화된 볼륨 생성**  
다음 `create-volume` 예시에서는 EBS 암호화를 위한 기본 CMK를 사용하여 암호화된 볼륨을 생성합니다. 기본적으로 암호화가 비활성화되어 있는 경우 다음과 같이 `--encrypted` 파라미터를 지정해야 합니다.  

```
aws ec2 create-volume \
    --size 80 \
    --encrypted \
    --availability-zone us-east-1a
```
출력:  

```
{
    "AvailabilityZone": "us-east-1a",
    "Tags": [],
    "Encrypted": true,
    "VolumeType": "gp2",
    "VolumeId": "vol-1234567890abcdef0",
    "State": "creating",
    "Iops": 240,
    "SnapshotId": "",
    "CreateTime": "YYYY-MM-DDTHH:MM:SS.000Z",
    "Size": 80
}
```
기본적으로 암호화가 활성화된 경우 다음 예시에서는 `--encrypted` 파라미터가 없어도 암호화된 볼륨을 생성합니다.  

```
aws ec2 create-volume \
    --size 80 \
    --availability-zone us-east-1a
```
`--kms-key-id` 파라미터를 사용하여 고객 관리형 CMK를 지정하는 경우 기본적으로 암호화가 활성화되어 있더라도 `--encrypted` 파라미터도 지정해야 합니다.  

```
aws ec2 create-volume \
    --volume-type gp2 \
    --size 80 \
    --encrypted \
    --kms-key-id 0ea3fef3-80a7-4778-9d8c-1c0c6EXAMPLE \
    --availability-zone us-east-1a
```
**예시 4: 태그를 사용하여 볼륨 생성**  
다음 `create-volume` 예시에서는 볼륨을 만들고 두 개의 태그를 추가합니다.  

```
aws ec2 create-volume \
    --availability-zone us-east-1a \
    --volume-type gp2 \
    --size 80 \
    --tag-specifications 'ResourceType=volume,Tags=[{Key=purpose,Value=production},{Key=cost-center,Value=cc123}]'
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateVolume](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-volume.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 볼륨을 생성합니다.**  

```
New-EC2Volume -Size 50 -AvailabilityZone us-west-2a -VolumeType gp2
```
**출력:**  

```
Attachments      : {}
AvailabilityZone : us-west-2a
CreateTime       : 12/22/2015 1:42:07 AM
Encrypted        : False
Iops             : 150
KmsKeyId         :
Size             : 50
SnapshotId       :
State            : creating
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
```
**예제 2: 이 예제 요청에서는 볼륨을 생성하고 키가 stack이고 값이 production인 태그를 적용합니다.**  

```
$tag = @{ Key="stack"; Value="production" }

$tagspec = new-object Amazon.EC2.Model.TagSpecification
$tagspec.ResourceType = "volume"
$tagspec.Tags.Add($tag)

New-EC2Volume -Size 80 -AvailabilityZone "us-west-2a" -TagSpecification $tagspec
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateVolume](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 볼륨을 생성합니다.**  

```
New-EC2Volume -Size 50 -AvailabilityZone us-west-2a -VolumeType gp2
```
**출력:**  

```
Attachments      : {}
AvailabilityZone : us-west-2a
CreateTime       : 12/22/2015 1:42:07 AM
Encrypted        : False
Iops             : 150
KmsKeyId         :
Size             : 50
SnapshotId       :
State            : creating
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
```
**예제 2: 이 예제 요청에서는 볼륨을 생성하고 키가 stack이고 값이 production인 태그를 적용합니다.**  

```
$tag = @{ Key="stack"; Value="production" }

$tagspec = new-object Amazon.EC2.Model.TagSpecification
$tagspec.ResourceType = "volume"
$tagspec.Tags.Add($tag)

New-EC2Volume -Size 80 -AvailabilityZone "us-west-2a" -TagSpecification $tagspec
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateVolume](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `CreateVpc` 함께 사용
<a name="example_ec2_CreateVpc_section"></a>

다음 코드 예시는 `CreateVpc`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 
+  [Transit Gateway 시작하기](example_vpc_TransitGatewayGettingStarted_section.md) 
+  [VPC IPAM 시작하기](example_vpc_GettingStartedIpam_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**예제 1: VPC를 생성하는 방법**  
다음 `create-vpc` 예제에서는 지정된 IPv4 CIDR 블록과 이름 태그를 사용하여 VPC를 생성합니다.  

```
aws ec2 create-vpc \
    --cidr-block 10.0.0.0/16 \
    --tag-specifications ResourceType=vpc,Tags=[{Key=Name,Value=MyVpc}]
```
출력:  

```
{
    "Vpc": {
        "CidrBlock": "10.0.0.0/16",
        "DhcpOptionsId": "dopt-5EXAMPLE",
        "State": "pending",
        "VpcId": "vpc-0a60eb65b4EXAMPLE",
        "OwnerId": "123456789012",
        "InstanceTenancy": "default",
        "Ipv6CidrBlockAssociationSet": [],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-07501b79ecEXAMPLE",
                "CidrBlock": "10.0.0.0/16",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false,
        "Tags": [
            {
                "Key": "Name",
                "Value": MyVpc"
            }
        ]
    }
}
```
**예제 2: 전용 테넌시를 사용하여 VPC를 생성하는 방법**  
다음 `create-vpc` 예제에서는 지정된 IPv4 CIDR 블록과 전용 테넌시를 사용하여 VPC를 생성합니다.  

```
aws ec2 create-vpc \
    --cidr-block 10.0.0.0/16 \
    --instance-tenancy dedicated
```
출력:  

```
{
    "Vpc": {
        "CidrBlock": "10.0.0.0/16",
        "DhcpOptionsId": "dopt-19edf471",
        "State": "pending",
        "VpcId": "vpc-0a53287fa4EXAMPLE",
        "OwnerId": "111122223333",
        "InstanceTenancy": "dedicated",
        "Ipv6CidrBlockAssociationSet": [],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-00b24cc1c2EXAMPLE",
                "CidrBlock": "10.0.0.0/16",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false
    }
}
```
**예제 3: IPv6 CIDR 블록을 사용하여 VPC를 생성하는 방법**  
다음 `create-vpc` 예제에서는 Amazon에서 제공하는 IPv6 CIDR 블록을 사용하여 VPC를 생성합니다.  

```
aws ec2 create-vpc \
    --cidr-block 10.0.0.0/16 \
    --amazon-provided-ipv6-cidr-block
```
출력:  

```
{
    "Vpc": {
        "CidrBlock": "10.0.0.0/16",
        "DhcpOptionsId": "dopt-dEXAMPLE",
        "State": "pending",
        "VpcId": "vpc-0fc5e3406bEXAMPLE",
        "OwnerId": "123456789012",
        "InstanceTenancy": "default",
        "Ipv6CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-068432c60bEXAMPLE",
                "Ipv6CidrBlock": "",
                "Ipv6CidrBlockState": {
                    "State": "associating"
                },
                "Ipv6Pool": "Amazon",
                "NetworkBorderGroup": "us-west-2"
            }
        ],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-0669f8f9f5EXAMPLE",
                "CidrBlock": "10.0.0.0/16",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false
    }
}
```
**예제 4: IPAM 풀에서 CIDR을 사용하여 VPC를 생성하는 방법**  
다음 `create-vpc` 예제에서는 Amazon VPC IP Address Manager(IPAM) 풀에서 CIDR을 사용하여 VPC를 생성합니다.  
Linux 및 macOS:  

```
aws ec2 create-vpc \
    --ipv4-ipam-pool-id ipam-pool-0533048da7d823723 \
    --tag-specifications ResourceType=vpc,Tags='[{Key=Environment,Value="Preprod"},{Key=Owner,Value="Build Team"}]'
```
Windows:  

```
aws ec2 create-vpc ^
    --ipv4-ipam-pool-id ipam-pool-0533048da7d823723 ^
    --tag-specifications ResourceType=vpc,Tags=[{Key=Environment,Value="Preprod"},{Key=Owner,Value="Build Team"}]
```
출력:  

```
{
    "Vpc": {
        "CidrBlock": "10.0.1.0/24",
        "DhcpOptionsId": "dopt-2afccf50",
        "State": "pending",
        "VpcId": "vpc-010e1791024eb0af9",
        "OwnerId": "123456789012",
        "InstanceTenancy": "default",
        "Ipv6CidrBlockAssociationSet": [],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-0a77de1d803226d4b",
                "CidrBlock": "10.0.1.0/24",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false,
        "Tags": [
            {
                "Key": "Environment",
                "Value": "Preprod"
            },
            {
                "Key": "Owner",
                "Value": "Build Team"
            }
        ]
    }
}
```
자세한 내용은 *Amazon VPC IPAM 사용 설명서*에서 [IPAM 풀 CIDR을 사용하는 VPC 생성](https://docs.aws.amazon.com/vpc/latest/ipam/create-vpc-ipam.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [CreateVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpc.html)를 참조하세요.

------
#### [ PHP ]

**SDK for PHP**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * @param string $cidr
     * @return array
     */
    public function createVpc(string $cidr): array
    {
        try {
            $result = $this->ec2Client->createVpc([
                "CidrBlock" => $cidr,
            ]);
            return $result['Vpc'];
        }catch(Ec2Exception $caught){
            echo "There was a problem creating the VPC: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [CreateVpc](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/CreateVpc)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 CIDR로 VPC를 생성합니다. Amazon VPC는 또한 VPC에 대해 기본 DHCP 옵션 세트, 기본 라우팅 테이블, 기본 네트워크 ACL을 생성합니다.**  

```
New-EC2VPC -CidrBlock 10.0.0.0/16
```
**출력:**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : pending
Tags            : {}
VpcId           : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateVpc](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 CIDR로 VPC를 생성합니다. Amazon VPC는 또한 VPC에 대해 기본 DHCP 옵션 세트, 기본 라우팅 테이블, 기본 네트워크 ACL을 생성합니다.**  

```
New-EC2VPC -CidrBlock 10.0.0.0/16
```
**출력:**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : pending
Tags            : {}
VpcId           : vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateVpc](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create(self, cidr_block: str) -> str:
        """
        Creates a new Amazon VPC with the specified CIDR block.

        :param cidr_block: The CIDR block for the new VPC, such as '10.0.0.0/16'.
        :return: The ID of the new VPC.
        """
        try:
            response = self.ec2_client.create_vpc(CidrBlock=cidr_block)
            vpc_id = response["Vpc"]["VpcId"]

            waiter = self.ec2_client.get_waiter("vpc_available")
            waiter.wait(VpcIds=[vpc_id])
            return vpc_id
        except ClientError as client_error:
            logging.error(
                "Couldn't create the vpc. Here's why: %s",
                client_error.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateVpc](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateVpc)를 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'aws-sdk-ec2'

# Creates a virtual private cloud (VPC) in
# Amazon Virtual Private Cloud (Amazon VPC) and then tags
# the VPC.
#
# @param ec2_resource [Aws::EC2::Resource] An initialized
#   Amazon Elastic Compute Cloud (Amazon EC2) resource object.
# @param cidr_block [String] The IPv4 CIDR block for the subnet.
# @param tag_key [String] The key portion of the tag for the VPC.
# @param tag_value [String] The value portion of the tag for the VPC.
# @return [Boolean] true if the VPC was created and tagged;
#   otherwise, false.
# @example
#   exit 1 unless vpc_created_and_tagged?(
#     Aws::EC2::Resource.new(region: 'us-west-2'),
#     '10.0.0.0/24',
#     'my-key',
#     'my-value'
#   )
def vpc_created_and_tagged?(
  ec2_resource,
  cidr_block,
  tag_key,
  tag_value
)
  vpc = ec2_resource.create_vpc(cidr_block: cidr_block)

  # Create a public DNS by enabling DNS support and DNS hostnames.
  vpc.modify_attribute(enable_dns_support: { value: true })
  vpc.modify_attribute(enable_dns_hostnames: { value: true })

  vpc.create_tags(tags: [{ key: tag_key, value: tag_value }])

  puts "Created VPC with ID '#{vpc.id}' and tagged with key " \
    "'#{tag_key}' and value '#{tag_value}'."
  true
rescue StandardError => e
  puts e.message
  false
end

# Example usage:
def run_me
  cidr_block = ''
  tag_key = ''
  tag_value = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-create-vpc.rb ' \
      'CIDR_BLOCK TAG_KEY TAG_VALUE REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-create-vpc.rb ' \
      '10.0.0.0/24 my-key my-value us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  elsif ARGV.count.zero?
    cidr_block = '10.0.0.0/24'
    tag_key = 'my-key'
    tag_value = 'my-value'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    cidr_block = ARGV[0]
    tag_key = ARGV[1]
    tag_value = ARGV[2]
    region = ARGV[3]
  end

  ec2_resource = Aws::EC2::Resource.new(region: region)

  if vpc_created_and_tagged?(
    ec2_resource,
    cidr_block,
    tag_key,
    tag_value
  )
    puts 'VPC created and tagged.'
  else
    puts 'VPC not created or not tagged.'
  end
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateVpc](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateVpc)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    " iv_cidr_block = '10.0.0.0/16'
    TRY.
        oo_result = lo_ec2->createvpc( iv_cidrblock = iv_cidr_block ).             " oo_result is returned for testing purposes. "
        DATA(lv_vpc_id) = oo_result->get_vpc( )->get_vpcid( ).
        MESSAGE 'Created VPC.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateVpc](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `CreateVpcEndpoint` 함께 사용
<a name="example_ec2_CreateVpcEndpoint_section"></a>

다음 코드 예시는 `CreateVpcEndpoint`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 게이트웨이 엔드포인트 생성**  
다음 `create-vpc-endpoint` 예시에서는 VPC `vpc-1a2b3c4d`와 `us-east-1` 리전의 Amazon S3 사이에 게이트웨이 VPC 엔드포인트를 생성하고 라우팅 테이블 `rtb-11aa22bb`를 엔드포인트와 연결합니다.  

```
aws ec2 create-vpc-endpoint \
    --vpc-id vpc-1a2b3c4d \
    --service-name com.amazonaws.us-east-1.s3 \
    --route-table-ids rtb-11aa22bb
```
출력:  

```
{
    "VpcEndpoint": {
        "PolicyDocument": "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":\"\*\",\"Action\":\"\*\",\"Resource\":\"\*\"}]}",
        "VpcId": "vpc-1a2b3c4d",
        "State": "available",
        "ServiceName": "com.amazonaws.us-east-1.s3",
        "RouteTableIds": [
            "rtb-11aa22bb"
        ],
        "VpcEndpointId": "vpc-1a2b3c4d",
        "CreationTimestamp": "2015-05-15T09:40:50Z"
    }
}
```
자세한 내용은 *AWS PrivateLink 설명서*의 [게이트웨이 엔드포인트 생성](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-s3.html#create-gateway-endpoint-s3)을 참조하세요.  
**예시 2: 인터페이스 엔드포인트 생성**  
다음 `create-vpc-endpoint` 예시에서는 `us-east-1` 리전의 VPC `vpc-1a2b3c4d`와 Amazon S3 사이에 인터페이스 VPC 엔드포인트를 생성합니다. 이 명령은 `subnet-1a2b3c4d` 서브넷에 엔드포인트를 만들고 `sg-1a2b3c4d` 보안 그룹에 연결한 다음 키가 'Service'이고 값이 'S3'인 태그를 추가합니다.  

```
aws ec2 create-vpc-endpoint \
    --vpc-id vpc-1a2b3c4d \
    --vpc-endpoint-type Interface \
    --service-name com.amazonaws.us-east-1.s3 \
    --subnet-ids subnet-7b16de0c \
    --security-group-id sg-1a2b3c4d \
    --tag-specifications ResourceType=vpc-endpoint,Tags=[{Key=service,Value=S3}]
```
출력:  

```
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-1a2b3c4d5e6f1a2b3",
        "VpcEndpointType": "Interface",
        "VpcId": "vpc-1a2b3c4d",
        "ServiceName": "com.amazonaws.us-east-1.s3",
        "State": "pending",
        "RouteTableIds": [],
        "SubnetIds": [
            "subnet-1a2b3c4d"
        ],
        "Groups": [
            {
                "GroupId": "sg-1a2b3c4d",
                "GroupName": "default"
            }
        ],
        "PrivateDnsEnabled": false,
        "RequesterManaged": false,
        "NetworkInterfaceIds": [
            "eni-0b16f0581c8ac6877"
        ],
        "DnsEntries": [
            {
                "DnsName": "*.vpce-1a2b3c4d5e6f1a2b3-9hnenorg.s3.us-east-1.vpce.amazonaws.com",
                "HostedZoneId": "Z7HUB22UULQXV"
            },
            {
                "DnsName": "*.vpce-1a2b3c4d5e6f1a2b3-9hnenorg-us-east-1c.s3.us-east-1.vpce.amazonaws.com",
                "HostedZoneId": "Z7HUB22UULQXV"
            }
        ],
        "CreationTimestamp": "2021-03-05T14:46:16.030000+00:00",
        "Tags": [
            {
                "Key": "service",
                "Value": "S3"
            }
        ],
        "OwnerId": "123456789012"
    }
}
```
자세한 내용은 *AWS PrivateLink 사용 설명서*의 [인터페이스 VPC 엔드포인트 생성](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)을 참조하세요.  
**예시 3: Gateway Load Balancer 엔드포인트 생성**  
다음 `create-vpc-endpoint` 예시에서는 VPC `vpc-111122223333aabbc`와 Gateway Load Balancer를 사용하여 구성된 서비스 사이에 Gateway Load Balancer 엔드포인트를 생성합니다.  

```
aws ec2 create-vpc-endpoint \
    --service-name com.amazonaws.vpce.us-east-1.vpce-svc-123123a1c43abc123 \
    --vpc-endpoint-type GatewayLoadBalancer \
    --vpc-id vpc-111122223333aabbc \
    --subnet-ids subnet-0011aabbcc2233445
```
출력:  

```
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-aabbaabbaabbaabba",
        "VpcEndpointType": "GatewayLoadBalancer",
        "VpcId": "vpc-111122223333aabbc",
        "ServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-123123a1c43abc123",
        "State": "pending",
        "SubnetIds": [
            "subnet-0011aabbcc2233445"
        ],
        "RequesterManaged": false,
        "NetworkInterfaceIds": [
            "eni-01010120203030405"
        ],
        "CreationTimestamp": "2020-11-11T08:06:03.522Z",
        "OwnerId": "123456789012"
    }
}
```
자세한 내용은 *AWS PrivateLink 사용 설명서*의 [Gateway Load Balancer 엔드포인트](https://docs.aws.amazon.com/vpc/latest/privatelink/gateway-load-balancer-endpoints.html)를 참조하세요.  
**예제 4: 리소스 엔드포인트 만들기**  
다음 `create-vpc-endpoint` 예제에서는 리소스 엔드포인트를 만듭니다.  

```
aws ec2 create-vpc-endpoint \
    --vpc-endpoint-type Resource \
    --vpc-id vpc-111122223333aabbc \
    --subnet-ids subnet-0011aabbcc2233445 \
    --resource-configuration-arn arn:aws:vpc-lattice-us-east-1:123456789012:resourceconfiguration/rcfg-0123abcde98765432
```
출력:  

```
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-00939a7ed9EXAMPLE",
        "VpcEndpointType": "Resource",
        "VpcId": "vpc-111122223333aabbc",
        "State": "Pending",
        "SubnetIds": [
            "subnet-0011aabbcc2233445"
        ],
        "Groups": [
            {
                "GroupId": "sg-03e2f15fbfc09b000",
                "GroupName": "default"
            }
        ],
        "IpAddressType": "IPV4",
        "PrivateDnsEnabled": false,
        "CreationTimestamp": "2025-02-06T23:38:49.525000+00:00",
        "Tags": [],
        "OwnerId": "123456789012",
        "ResourceConfigurationArn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourceconfiguration/rcfg-0123abcde98765432"
    }
}
```
자세한 내용은 *AWS PrivateLink 사용 설명서*의 [리소스 엔드포인트](https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-access-resources.html)를 참조하시기 바랍니다.  
**예제 5: 서비스 네트워크 엔드포인트 만들기**  
다음 `create-vpc-endpoint` 예제에서는 서비스 네트워크 엔드포인트를 만듭니다.  

```
aws ec2 create-vpc-endpoint \
    --vpc-endpoint-type ServiceNetwork \
    --vpc-id vpc-111122223333aabbc \
    --subnet-ids subnet-0011aabbcc2233445 \
    --service-network-arn arn:aws:vpc-lattice:us-east-1:123456789012:servicenetwork/sn-0101abcd5432abcd0 \
    --security-group-ids sg-0123456789012abcd
```
출력:  

```
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-0f00567fa8EXAMPLE",
        "VpcEndpointType": "ServiceNetwork",
        "VpcId": "vpc-111122223333aabbc",
        "State": "Pending",
        "SubnetIds": [
            "subnet-0011aabbcc2233445"
        ],
        "Groups": [
            {
                "GroupId": "sg-0123456789012abcd",
                "GroupName": "my-security-group"
            }
        ],
        "IpAddressType": "IPV4",
        "PrivateDnsEnabled": false,
        "CreationTimestamp": "2025-02-06T23:44:20.449000+00:00",
        "Tags": [],
        "OwnerId": "123456789012",
        "ServiceNetworkArn": "arn:aws:vpc-lattice:us-east-1:123456789012:servicenetwork/sn-0101abcd5432abcd0"
    }
}
```
자세한 내용은 *AWS PrivateLink 사용 설명서*의 [Service network endpoints](https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-access-service-networks.html)를 참조하시기 바랍니다.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateVpcEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpc-endpoint.html) 섹션을 참조하세요.

------
#### [ PHP ]

**SDK for PHP**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * @param string $serviceName
     * @param string $vpcId
     * @param array $routeTableIds
     * @return array
     */
    public function createVpcEndpoint(string $serviceName, string $vpcId, array $routeTableIds): array
    {
        try {
            $result = $this->ec2Client->createVpcEndpoint([
                'ServiceName' => $serviceName,
                'VpcId' => $vpcId,
                'RouteTableIds' => $routeTableIds,
            ]);

            return $result["VpcEndpoint"];
        } catch(Ec2Exception $caught){
            echo "There was a problem creating the VPC Endpoint: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [CreateVpcEndpoint](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/CreateVpcEndpoint)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 VPC vpc-0fc1ff23f45b678eb의 서비스 com.amazonaws.eu-west-1.s3에 대한 새 VPC 엔드포인트를 생성합니다.**  

```
New-EC2VpcEndpoint -ServiceName com.amazonaws.eu-west-1.s3 -VpcId vpc-0fc1ff23f45b678eb
```
**출력:**  

```
ClientToken VpcEndpoint
----------- -----------
            Amazon.EC2.Model.VpcEndpoint
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateVpcEndpoint](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 VPC vpc-0fc1ff23f45b678eb의 서비스 com.amazonaws.eu-west-1.s3에 대한 새 VPC 엔드포인트를 생성합니다.**  

```
New-EC2VpcEndpoint -ServiceName com.amazonaws.eu-west-1.s3 -VpcId vpc-0fc1ff23f45b678eb
```
**출력:**  

```
ClientToken VpcEndpoint
----------- -----------
            Amazon.EC2.Model.VpcEndpoint
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateVpcEndpoint](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create_vpc_endpoint(
        self, vpc_id: str, service_name: str, route_table_ids: list[str]
    ) -> Dict[str, Any]:
        """
        Creates a new VPC endpoint for the specified service and associates it with the specified route tables.

        :param vpc_id: The ID of the VPC to create the endpoint in.
        :param service_name: The name of the service to create the endpoint for.
        :param route_table_ids: A list of IDs of the route tables to associate with the endpoint.
        :return: A dictionary representing the newly created VPC endpoint.
        """
        try:
            response = self.ec2_client.create_vpc_endpoint(
                VpcId=vpc_id,
                ServiceName=service_name,
                RouteTableIds=route_table_ids,
            )
            return response["VpcEndpoint"]
        except ClientError as err:
            logger.error(
                "Couldn't create VPC endpoint for service %s. Here's why: %s: %s",
                service_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateVpcEndpoint](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateVpcEndpoint)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    " iv_vpc_id = 'vpc-abc123'
    " iv_service_name = 'com.amazonaws.region.service'
    TRY.
        oo_result = lo_ec2->createvpcendpoint(             " oo_result is returned for testing purposes. "
          iv_vpcid = iv_vpc_id
          iv_servicename = iv_service_name
          it_routetableids = it_route_table_ids ).
        DATA(lv_vpc_endpoint_id) = oo_result->get_vpcendpoint( )->get_vpcendpointid( ).
        MESSAGE 'Created VPC endpoint.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 SDK for SAP ABAP API 참조의 [CreateVpcEndpoint](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요. *AWS * 

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateVpnConnection` 사용
<a name="example_ec2_CreateVpnConnection_section"></a>

다음 코드 예시는 `CreateVpnConnection`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 동적 라우팅을 사용하여 VPN 연결 생성**  
다음 `create-vpn-connection` 예시에서는 지정된 가상 프라이빗 게이트웨이와 지정된 고객 게이트웨이 사이에 VPN 연결을 만들고 VPN 연결에 태그를 적용합니다. 출력에는 고객 게이트웨이 디바이스의 구성 정보가 XML 형식으로 포함됩니다.  

```
aws ec2 create-vpn-connection \
    --type ipsec.1 \
    --customer-gateway-id cgw-001122334455aabbc \
    --vpn-gateway-id vgw-1a1a1a1a1a1a2b2b2 \
    --tag-specification 'ResourceType=vpn-connection,Tags=[{Key=Name,Value=BGP-VPN}]'
```
출력:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "...configuration information...",
        "CustomerGatewayId": "cgw-001122334455aabbc",
        "Category": "VPN",
        "State": "pending",
        "VpnConnectionId": "vpn-123123123123abcab",
        "VpnGatewayId": "vgw-1a1a1a1a1a1a2b2b2",
        "Options": {
            "EnableAcceleration": false,
            "StaticRoutesOnly": false,
            "LocalIpv4NetworkCidr": "0.0.0.0/0",
            "RemoteIpv4NetworkCidr": "0.0.0.0/0",
            "TunnelInsideIpVersion": "ipv4",
            "TunnelOptions": [
                {},
                {}
            ]
        },
        "Routes": [],
        "Tags": [
             {
                "Key": "Name",
                "Value": "BGP-VPN"
            }
        ]
    }
}
```
자세한 내용은 Site[AWS Site-to-Site VPN 사용 설명서의 HowSite-to-Site VPN 작동](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html) 방식을 참조하세요. *AWS Site-to-Site *  
**예시 2: 정적 라우팅을 사용하여 VPN 연결 생성**  
다음 `create-vpn-connection` 예시에서는 지정된 가상 프라이빗 게이트웨이와 지정된 고객 게이트웨이 간에 VPN 연결을 생성합니다. 옵션은 정적 라우팅을 지정합니다. 출력에는 고객 게이트웨이 디바이스의 구성 정보가 XML 형식으로 포함됩니다.  

```
aws ec2 create-vpn-connection \
    --type ipsec.1 \
    --customer-gateway-id cgw-001122334455aabbc \
    --vpn-gateway-id vgw-1a1a1a1a1a1a2b2b2 \
    --options "{\"StaticRoutesOnly\":true}"
```
출력:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "..configuration information...",
        "CustomerGatewayId": "cgw-001122334455aabbc",
        "Category": "VPN",
        "State": "pending",
        "VpnConnectionId": "vpn-123123123123abcab",
        "VpnGatewayId": "vgw-1a1a1a1a1a1a2b2b2",
        "Options": {
            "EnableAcceleration": false,
            "StaticRoutesOnly": true,
            "LocalIpv4NetworkCidr": "0.0.0.0/0",
            "RemoteIpv4NetworkCidr": "0.0.0.0/0",
            "TunnelInsideIpVersion": "ipv4",
            "TunnelOptions": [
                {},
                {}
            ]
        },
        "Routes": [],
        "Tags": []
    }
}
```
자세한 내용은 Site[AWS Site-to-Site VPN 사용 설명서의 HowSite-to-Site VPN 작동](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html) 방식을 참조하세요. *AWS Site-to-Site *  
**예시 3: VPN 연결 생성 및 내부 CIDR 및 사전 공유 키 지정**  
다음 `create-vpn-connection` 예시에서는 VPN 연결을 생성하고 각 터널에 대해 내부 IP 주소 CIDR 블록과 사용자 지정 사전 공유 키를 지정합니다. 지정된 값이 `CustomerGatewayConfiguration` 정보에 반환됩니다.  

```
aws ec2 create-vpn-connection \
    --type ipsec.1 \
    --customer-gateway-id cgw-001122334455aabbc \
    --vpn-gateway-id vgw-1a1a1a1a1a1a2b2b2 \
    --options TunnelOptions='[{TunnelInsideCidr=169.254.12.0/30,PreSharedKey=ExamplePreSharedKey1},{TunnelInsideCidr=169.254.13.0/30,PreSharedKey=ExamplePreSharedKey2}]'
```
출력:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "..configuration information...",
        "CustomerGatewayId": "cgw-001122334455aabbc",
        "Category": "VPN",
        "State": "pending",
        "VpnConnectionId": "vpn-123123123123abcab",
        "VpnGatewayId": "vgw-1a1a1a1a1a1a2b2b2",
        "Options": {
            "EnableAcceleration": false,
            "StaticRoutesOnly": false,
            "LocalIpv4NetworkCidr": "0.0.0.0/0",
            "RemoteIpv4NetworkCidr": "0.0.0.0/0",
            "TunnelInsideIpVersion": "ipv4",
            "TunnelOptions": [
                {
                    "OutsideIpAddress": "203.0.113.3",
                    "TunnelInsideCidr": "169.254.12.0/30",
                    "PreSharedKey": "ExamplePreSharedKey1"
                },
                {
                    "OutsideIpAddress": "203.0.113.5",
                    "TunnelInsideCidr": "169.254.13.0/30",
                    "PreSharedKey": "ExamplePreSharedKey2"
                }
            ]
        },
        "Routes": [],
        "Tags": []
    }
}
```
자세한 내용은 Site[AWS Site-to-Site VPN 사용 설명서의 HowSite-to-Site VPN 작동](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html) 방식을 참조하세요. *AWS Site-to-Site *  
**예시 4: IPv6 트래픽을 지원하는 VPN 연결 생성**  
다음 `create-vpn-connection` 예시에서는 지정된 전송 게이트웨이와 지정된 고객 게이트웨이 간에 IPv6 트래픽을 지원하는 VPN 연결을 생성합니다. 두 터널의 터널 옵션은가 IKE 협상을 시작해야 AWS 한다고 지정합니다.  

```
aws ec2 create-vpn-connection \
    --type ipsec.1 \
    --transit-gateway-id tgw-12312312312312312 \
    --customer-gateway-id cgw-001122334455aabbc \
    --options TunnelInsideIpVersion=ipv6,TunnelOptions=[{StartupAction=start},{StartupAction=start}]
```
출력:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "..configuration information...",
        "CustomerGatewayId": "cgw-001122334455aabbc",
        "Category": "VPN",
        "State": "pending",
        "VpnConnectionId": "vpn-11111111122222222",
        "TransitGatewayId": "tgw-12312312312312312",
        "Options": {
            "EnableAcceleration": false,
            "StaticRoutesOnly": false,
            "LocalIpv6NetworkCidr": "::/0",
            "RemoteIpv6NetworkCidr": "::/0",
            "TunnelInsideIpVersion": "ipv6",
            "TunnelOptions": [
                {
                    "OutsideIpAddress": "203.0.113.3",
                    "StartupAction": "start"
                },
                {
                    "OutsideIpAddress": "203.0.113.5",
                    "StartupAction": "start"
                }
            ]
        },
        "Routes": [],
        "Tags": []
    }
}
```
자세한 내용은 Site[AWS Site-to-Site VPN 사용 설명서의 HowSite-to-Site VPN 작동](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html) 방식을 참조하세요. *AWS Site-to-Site *  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateVpnConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpn-connection.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이와 지정된 고객 게이트웨이 간에 VPN 연결을 만듭니다. 출력에는 네트워크 관리자에게 필요한 구성 정보가 XML 형식으로 포함됩니다.**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d
```
**출력:**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      :
Routes                       : {}
State                        : pending
Tags                         : {}
Type                         :
VgwTelemetry                 : {}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**예제 2: 이 예제에서는 VPN 연결을 생성하고 지정된 이름의 파일에 구성을 캡처합니다.**  

```
(New-EC2VpnConnection -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d).CustomerGatewayConfiguration | Out-File C:\path\vpn-configuration.xml
```
**예제 3: 이 예제에서는 지정된 가상 프라이빗 게이트웨이와 지정된 고객 게이트웨이 간에 정적 라우팅을 사용하여 VPN 연결을 만듭니다.**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d -Options_StaticRoutesOnly $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateVpnConnection](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이와 지정된 고객 게이트웨이 간에 VPN 연결을 만듭니다. 출력에는 네트워크 관리자에게 필요한 구성 정보가 XML 형식으로 포함됩니다.**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d
```
**출력:**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      :
Routes                       : {}
State                        : pending
Tags                         : {}
Type                         :
VgwTelemetry                 : {}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**예제 2: 이 예제에서는 VPN 연결을 생성하고 지정된 이름의 파일에 구성을 캡처합니다.**  

```
(New-EC2VpnConnection -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d).CustomerGatewayConfiguration | Out-File C:\path\vpn-configuration.xml
```
**예제 3: 이 예제에서는 지정된 가상 프라이빗 게이트웨이와 지정된 고객 게이트웨이 간에 정적 라우팅을 사용하여 VPN 연결을 만듭니다.**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d -Options_StaticRoutesOnly $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateVpnConnection](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateVpnConnectionRoute` 사용
<a name="example_ec2_CreateVpnConnectionRoute_section"></a>

다음 코드 예시는 `CreateVpnConnectionRoute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPN 연결을 위한 정적 경로 생성**  
이 예시에서는 지정된 VPN 연결에 대한 고정 경로를 생성합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 create-vpn-connection-route --vpn-connection-id vpn-40f41529 --destination-cidr-block 11.12.0.0/16
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateVpnConnectionRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpn-connection-route.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPN 연결에 대해 지정된 정적 경로를 만듭니다.**  

```
New-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPN 연결에 대해 지정된 정적 경로를 만듭니다.**  

```
New-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `CreateVpnGateway` 사용
<a name="example_ec2_CreateVpnGateway_section"></a>

다음 코드 예시는 `CreateVpnGateway`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**가상 프라이빗 게이트웨이 생성**  
이 예시에서는 가상 프라이빗 게이트웨이를 생성합니다.  
명령:  

```
aws ec2 create-vpn-gateway --type ipsec.1
```
출력:  

```
{
    "VpnGateway": {
        "AmazonSideAsn": 64512,
        "State": "available",
        "Type": "ipsec.1",
        "VpnGatewayId": "vgw-9a4cacf3",
        "VpcAttachments": []
    }
}
```
**특정 Amazon 측 ASN을 사용하여 가상 프라이빗 게이트웨이 생성**  
이 예시에서는 가상 프라이빗 게이트웨이를 생성하고 BGP 세션의 Amazon 측에 대한 Autonomous System Number(ASN)를 지정합니다.  
명령:  

```
aws ec2 create-vpn-gateway --type ipsec.1 --amazon-side-asn 65001
```
출력:  

```
{
    "VpnGateway": {
        "AmazonSideAsn": 65001,
        "State": "available",
        "Type": "ipsec.1",
        "VpnGatewayId": "vgw-9a4cacf3",
        "VpcAttachments": []
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateVpnGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpn-gateway.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 생성합니다.**  

```
New-EC2VpnGateway -Type ipsec.1
```
**출력:**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {}
VpnGatewayId     : vgw-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateVpnGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 생성합니다.**  

```
New-EC2VpnGateway -Type ipsec.1
```
**출력:**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {}
VpnGatewayId     : vgw-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteCustomerGateway` 사용
<a name="example_ec2_DeleteCustomerGateway_section"></a>

다음 코드 예시는 `DeleteCustomerGateway`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**고객 게이트웨이 삭제**  
이 예시에서는 지정된 고객 게이트웨이를 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-customer-gateway --customer-gateway-id cgw-0e11f167
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteCustomerGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-customer-gateway.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 고객 게이트웨이를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2CustomerGateway (DeleteCustomerGateway)" on Target "cgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteCustomerGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 고객 게이트웨이를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2CustomerGateway (DeleteCustomerGateway)" on Target "cgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteCustomerGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteDhcpOptions` 사용
<a name="example_ec2_DeleteDhcpOptions_section"></a>

다음 코드 예시는 `DeleteDhcpOptions`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**DHCP 옵션 세트 삭제**  
이 예시에서는 지정된 DHCP 옵션 세트를 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-dhcp-options --dhcp-options-id dopt-d9070ebb
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteDhcpOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-dhcp-options.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 DHCP 옵션 세트를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2DhcpOption (DeleteDhcpOptions)" on Target "dopt-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteDhcpOptions](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 DHCP 옵션 세트를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2DhcpOption (DeleteDhcpOptions)" on Target "dopt-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteFlowLogs` 사용
<a name="example_ec2_DeleteFlowLogs_section"></a>

다음 코드 예시는 `DeleteFlowLogs`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**흐름 로그 삭제**  
다음 `delete-flow-logs` 예시에서는 지정된 흐름 로그를 삭제합니다.  

```
aws ec2 delete-flow-logs --flow-log-id fl-11223344556677889
```
출력:  

```
{
    "Unsuccessful": []
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteFlowLogs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-flow-logs.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 FlowLogId fl-01a2b3456a789c01을 제거합니다.**  

```
Remove-EC2FlowLog -FlowLogId fl-01a2b3456a789c01
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2FlowLog (DeleteFlowLogs)" on target "fl-01a2b3456a789c01".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteFlowLogs](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 FlowLogId fl-01a2b3456a789c01을 제거합니다.**  

```
Remove-EC2FlowLog -FlowLogId fl-01a2b3456a789c01
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2FlowLog (DeleteFlowLogs)" on target "fl-01a2b3456a789c01".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteInternetGateway` 사용
<a name="example_ec2_DeleteInternetGateway_section"></a>

다음 코드 예시는 `DeleteInternetGateway`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**인터넷 게이트웨이 삭제**  
다음 `delete-internet-gateway` 예시에서는 지정된 인터넷 게이트웨이를 삭제합니다.  

```
aws ec2 delete-internet-gateway \
    --internet-gateway-id igw-0d0fb496b3EXAMPLE
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *Amazon VPC 사용 설명서*의 [인터넷 게이트웨이](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-internet-gateway.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인터넷 게이트웨이를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2InternetGateway (DeleteInternetGateway)" on Target "igw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteInternetGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인터넷 게이트웨이를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2InternetGateway (DeleteInternetGateway)" on Target "igw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DeleteKeyPair` 함께 사용
<a name="example_ec2_DeleteKeyPair_section"></a>

다음 코드 예시는 `DeleteKeyPair`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Delete an Amazon EC2 key pair.
    /// </summary>
    /// <param name="keyPairName">The name of the key pair to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteKeyPair(string keyPairName)
    {
        try
        {
            await _amazonEC2.DeleteKeyPairAsync(new DeleteKeyPairRequest(keyPairName)).ConfigureAwait(false);
            return true;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidKeyPair.NotFound")
            {
                _logger.LogError($"KeyPair {keyPairName} does not exist and cannot be deleted. Please verify the key pair name and try again.");
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete the key pair because: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Delete the temporary file where the key pair information was saved.
    /// </summary>
    /// <param name="tempFileName">The path to the temporary file.</param>
    public void DeleteTempFile(string tempFileName)
    {
        if (File.Exists(tempFileName))
        {
            File.Delete(tempFileName);
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeleteKeyPair](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteKeyPair)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_delete_keypair
#
# This function deletes an Amazon EC2 ED25519 or 2048-bit RSA key pair.
#
# Parameters:
#       -n key_pair_name - A key pair name.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_delete_keypair() {
  local key_pair_name response

  local option OPTARG # Required to use getopts command in a function.
  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_delete_keypair"
    echo "Deletes an Amazon EC2 ED25519 or 2048-bit RSA key pair."
    echo "  -n key_pair_name - A key pair name."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) key_pair_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$key_pair_name" ]]; then
    errecho "ERROR: You must provide a key pair name with the -n parameter."
    usage
    return 1
  fi

  response=$(aws ec2 delete-key-pair \
    --key-name "$key_pair_name") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports delete-key-pair operation failed.$response"
    return 1
  }

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteKeyPair](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteKeyPair)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Delete an Amazon Elastic Compute Cloud (Amazon EC2) instance key pair.
/*!
  \param keyPairName: A name for a key pair.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::EC2::deleteKeyPair(const Aws::String &keyPairName,
                                const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DeleteKeyPair](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DeleteKeyPair)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**키 페어 삭제**  
다음 `delete-key-pair` 예시에서는 지정된 키 페어를 삭제합니다.  

```
aws ec2 delete-key-pair \
    --key-name my-key-pair
```
출력:  

```
{
    "Return": true,
    "KeyPairId": "key-03c8d3aceb53b507"
}
```
자세한 내용은 *AWS Command Line Interface 사용 설명서*의 [키 페어 사용 및 삭제](https://docs.aws.amazon.com/cli/latest/userguide/cli-ec2-keypairs.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DeleteKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-key-pair.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Deletes a key pair asynchronously.
     *
     * @param keyPair the name of the key pair to delete
     * @return a {@link CompletableFuture} that represents the result of the asynchronous operation.
     *         The {@link CompletableFuture} will complete with a {@link DeleteKeyPairResponse} object
     *         that provides the result of the key pair deletion operation.
     */
    public CompletableFuture<DeleteKeyPairResponse> deleteKeysAsync(String keyPair) {
        DeleteKeyPairRequest request = DeleteKeyPairRequest.builder()
            .keyName(keyPair)
            .build();

        // Initiate the asynchronous request to delete the key pair.
        CompletableFuture<DeleteKeyPairResponse> response = getAsyncClient().deleteKeyPair(request);
        return response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to delete key pair: " + keyPair, ex);
            } else if (resp == null) {
                throw new RuntimeException("No response received for deleting key pair: " + keyPair);
            }
        });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DeleteKeyPair](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteKeyPair)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { DeleteKeyPairCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Deletes the specified key pair, by removing the public key from Amazon EC2.
 * @param {{ keyName: string }} options
 */
export const main = async ({ keyName }) => {
  const client = new EC2Client({});
  const command = new DeleteKeyPairCommand({
    KeyName: keyName,
  });

  try {
    await client.send(command);
    console.log("Successfully deleted key pair.");
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide the required value?`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteKeyPair](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteKeyPairCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun deleteKeys(keyPair: String?) {
    val request =
        DeleteKeyPairRequest {
            keyName = keyPair
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.deleteKeyPair(request)
        println("Successfully deleted key pair named $keyPair")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DeleteKeyPair](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 키 페어를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2KeyPair -KeyName my-key-pair
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2KeyPair (DeleteKeyPair)" on Target "my-key-pair".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteKeyPair](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 키 페어를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2KeyPair -KeyName my-key-pair
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2KeyPair (DeleteKeyPair)" on Target "my-key-pair".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class KeyPairWrapper:
    """
    Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.
    This class provides methods to create, list, and delete EC2 key pairs.
    """

    def __init__(
        self,
        ec2_client: boto3.client,
        key_file_dir: Union[tempfile.TemporaryDirectory, str],
        key_pair: Optional[dict] = None,
    ):
        """
        Initializes the KeyPairWrapper with the specified EC2 client, key file directory,
        and an optional key pair.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param key_file_dir: The folder where the private key information is stored.
                             This should be a secure folder.
        :param key_pair: A dictionary representing the Boto3 KeyPair object.
                         This is a high-level object that wraps key pair actions. Optional.
        """
        self.ec2_client = ec2_client
        self.key_pair = key_pair
        self.key_file_path: Optional[str] = None
        self.key_file_dir = key_file_dir

    @classmethod
    def from_client(cls) -> "KeyPairWrapper":
        """
        Class method to create an instance of KeyPairWrapper using a new EC2 client
        and a temporary directory for storing key files.

        :return: An instance of KeyPairWrapper.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client, tempfile.TemporaryDirectory())


    def delete(self, key_name: str) -> bool:
        """
        Deletes a key pair by its name.

        :param key_name: The name of the key pair to delete.
        :return: A boolean indicating whether the deletion was successful.
        :raises ClientError: If there is an error in deleting the key pair, for example,
                             if the key pair does not exist.
        """
        try:
            self.ec2_client.delete_key_pair(KeyName=key_name)
            logger.info(f"Successfully deleted key pair: {key_name}")
            self.key_pair = None
            return True
        except self.ec2_client.exceptions.ClientError as err:
            logger.error(f"Deletion failed for key pair: {key_name}")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidKeyPair.NotFound":
                logger.error(
                    f"The key pair '{key_name}' does not exist and cannot be deleted. "
                    "Please verify the key pair name and try again."
                )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteKeyPair](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteKeyPair)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
백업 프라이빗 PEM 키를 함께 제거하는 delete\$1key 주위의 래퍼입니다.  

```
    pub async fn delete(self, ec2: &EC2, util: &Util) -> Result<(), EC2Error> {
        if let Some(key_name) = self.key_pair.key_name() {
            ec2.delete_key_pair(key_name).await?;
            if let Some(key_path) = self.key_file_path() {
                if let Err(err) = util.remove(key_path) {
                    eprintln!("Failed to remove {key_path:?} ({err:?})");
                }
            }
        }
        Ok(())
    }
```

```
    pub async fn delete_key_pair(&self, key_name: &str) -> Result<(), EC2Error> {
        let key_name: String = key_name.into();
        tracing::info!("Deleting key pair {key_name}");
        self.client
            .delete_key_pair()
            .key_name(key_name)
            .send()
            .await?;
        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DeleteKeyPair](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.delete_key_pair)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ec2->deletekeypair( iv_keyname = iv_key_name ).
        MESSAGE 'Amazon EC2 key pair deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeleteKeyPair](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Delete an EC2 key pair.
    /// 
    /// - Parameter keyPair: The name of the key pair to delete.
    /// 
    /// - Returns: `true` if the key pair is deleted successfully; otherwise
    ///   `false`.
    func deleteKeyPair(keyPair: String) async -> Bool {
        do {
            _ = try await ec2Client.deleteKeyPair(
                input: DeleteKeyPairInput(
                    keyName: keyPair
                )
            )

            return true
        } catch {
            print("*** Error deleting the key pair: \(error.localizedDescription)")
            return false
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DeleteKeyPair](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/deletekeypair(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DeleteLaunchTemplate` 함께 사용
<a name="example_ec2_DeleteLaunchTemplate_section"></a>

다음 코드 예시는 `DeleteLaunchTemplate`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](example_cross_ResilientService_section.md) 
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Delete a launch template by name.
    /// </summary>
    /// <param name="templateName">The name of the template to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTemplateByName(string templateName)
    {
        try
        {
            await _amazonEc2.DeleteLaunchTemplateAsync(
                new DeleteLaunchTemplateRequest()
                {
                    LaunchTemplateName = templateName
                });
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.NotFoundException")
            {
                _logger.LogError(
                    $"Could not delete the template, the name {_launchTemplateName} was not found.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while deleting the template.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 **AWS SDK for .NET API 참조의 [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteLaunchTemplate)을 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**시작 템플릿을 삭제하는 방법**  
다음 예제에서는 지정된 시작 템플릿을 삭제합니다.  
명령:  

```
aws ec2 delete-launch-template --launch-template-id lt-0abcd290751193123
```
출력:  

```
{
  "LaunchTemplate": {
      "LatestVersionNumber": 2,
      "LaunchTemplateId": "lt-0abcd290751193123",
      "LaunchTemplateName": "TestTemplate",
      "DefaultVersionNumber": 2,
      "CreatedBy": "arn:aws:iam::123456789012:root",
      "CreateTime": "2017-11-23T16:46:25.000Z"
  }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DeleteLaunchTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-launch-template.html)을 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
      await client.send(
        new DeleteLaunchTemplateCommand({
          LaunchTemplateName: NAMES.launchTemplateName,
        }),
      );
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [DeleteLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteLaunchTemplateCommand)을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def delete_template(self):
        """
        Deletes a launch template.
        """
        try:
            self.ec2_client.delete_launch_template(
                LaunchTemplateName=self.launch_template_name
            )
            self.delete_instance_profile(
                self.instance_profile_name, self.instance_role_name
            )
            log.info("Launch template %s deleted.", self.launch_template_name)
        except ClientError as err:
            if (
                err.response["Error"]["Code"]
                == "InvalidLaunchTemplateName.NotFoundException"
            ):
                log.info(
                    "Launch template %s does not exist, nothing to do.",
                    self.launch_template_name,
                )
            log.error(f"Full error:\n\t{err}")
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteLaunchTemplate)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteNetworkAcl` 사용
<a name="example_ec2_DeleteNetworkAcl_section"></a>

다음 코드 예시는 `DeleteNetworkAcl`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 ACL 삭제**  
이 예시에서는 지정된 네트워크 ACL을 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-network-acl --network-acl-id acl-5fb85d36
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteNetworkAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-acl.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2NetworkAcl -NetworkAclId acl-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAcl (DeleteNetworkAcl)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteNetworkAcl](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2NetworkAcl -NetworkAclId acl-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAcl (DeleteNetworkAcl)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteNetworkAcl](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteNetworkAclEntry` 사용
<a name="example_ec2_DeleteNetworkAclEntry_section"></a>

다음 코드 예시는 `DeleteNetworkAclEntry`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 ACL 항목 삭제**  
이 예시에서는 지정된 네트워크 ACL에서 수신 규칙 번호 100을 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-network-acl-entry --network-acl-id acl-5fb85d36 --ingress --rule-number 100
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteNetworkAclEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-acl-entry.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL에서 지정된 규칙을 제거합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAclEntry (DeleteNetworkAclEntry)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteNetworkAclEntry](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL에서 지정된 규칙을 제거합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAclEntry (DeleteNetworkAclEntry)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteNetworkInterface` 사용
<a name="example_ec2_DeleteNetworkInterface_section"></a>

다음 코드 예시는 `DeleteNetworkInterface`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 인터페이스 삭제**  
이 예시에서는 지정된 네트워크 인터페이스를 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-network-interface --network-interface-id eni-e5aa89a3
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteNetworkInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-interface.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkInterface (DeleteNetworkInterface)" on Target "eni-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteNetworkInterface](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkInterface (DeleteNetworkInterface)" on Target "eni-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeletePlacementGroup` 사용
<a name="example_ec2_DeletePlacementGroup_section"></a>

다음 코드 예시는 `DeletePlacementGroup`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**배치 그룹 삭제**  
이 예시 명령은 지정된 배치 그룹을 삭제합니다.  
명령:  

```
aws ec2 delete-placement-group --group-name my-cluster
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeletePlacementGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-placement-group.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 배치 그룹을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2PlacementGroup -GroupName my-placement-group
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2PlacementGroup (DeletePlacementGroup)" on Target "my-placement-group".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeletePlacementGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 배치 그룹을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2PlacementGroup -GroupName my-placement-group
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2PlacementGroup (DeletePlacementGroup)" on Target "my-placement-group".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeletePlacementGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteRoute` 사용
<a name="example_ec2_DeleteRoute_section"></a>

다음 코드 예시는 `DeleteRoute`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [Transit Gateway 시작하기](example_vpc_TransitGatewayGettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**경로 삭제**  
이 예시에서는 지정된 라우팅 테이블에서 지정된 경로를 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-route --route-table-id rtb-22574640 --destination-cidr-block 0.0.0.0/0
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-route.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블에서 지정된 경로를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Route (DeleteRoute)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteRoute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블에서 지정된 경로를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Route (DeleteRoute)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteRoute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteRouteTable` 사용
<a name="example_ec2_DeleteRouteTable_section"></a>

다음 코드 예시는 `DeleteRouteTable`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**라우팅 테이블 삭제**  
이 예시에서는 지정된 라우팅 테이블을 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-route-table --route-table-id rtb-22574640
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-route-table.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2RouteTable (DeleteRouteTable)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteRouteTable](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2RouteTable (DeleteRouteTable)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DeleteSecurityGroup` 함께 사용
<a name="example_ec2_DeleteSecurityGroup_section"></a>

다음 코드 예시는 `DeleteSecurityGroup`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Delete an Amazon EC2 security group.
    /// </summary>
    /// <param name="groupName">The name of the group to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteSecurityGroup(string groupId)
    {
        try
        {
            var response =
                await _amazonEC2.DeleteSecurityGroupAsync(
                    new DeleteSecurityGroupRequest { GroupId = groupId });
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidGroup.NotFound")
            {
                _logger.LogError(
                    $"Security Group {groupId} does not exist and cannot be deleted. Please verify the ID and try again.");
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete the security group because: {ex.Message}");
            return false;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteSecurityGroup)을 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_delete_security_group
#
# This function deletes an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Parameters:
#       -i security_group_id - The ID of the security group to delete.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_delete_security_group() {
  local security_group_id response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_delete_security_group"
    echo "Deletes an Amazon Elastic Compute Cloud (Amazon EC2) security group."
    echo "  -i security_group_id - The ID of the security group to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) security_group_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$security_group_id" ]]; then
    errecho "ERROR: You must provide a security group ID with the -i parameter."
    usage
    return 1
  fi

  response=$(aws ec2 delete-security-group --group-id "$security_group_id" --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports delete-security-group operation failed.$response"
    return 1
  }

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteSecurityGroup)을 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Delete a security group.
/*!
  \param securityGroupID: A security group ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::deleteSecurityGroup(const Aws::String &securityGroupID,
                                      const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DeleteSecurityGroup)을 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**[EC2-Classic] 보안 그룹을 삭제하는 방법**  
이 예제에서는 이름이 `MySecurityGroup`인 보안 그룹을 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-security-group --group-name MySecurityGroup
```
**[EC2-VPC] 보안 그룹을 삭제하는 방법**  
이 예제에서는 ID가 `sg-903004f8`인 보안 그룹을 삭제합니다. 이름으로 EC2-VPC에 대한 보안 그룹을 참조할 수 없습니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-security-group --group-id sg-903004f8
```
자세한 내용은 *AWS Command Line Interface 사용 설명서*의 보안 그룹 사용을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DeleteSecurityGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-security-group.html)을 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Deletes an EC2 security group asynchronously.
     *
     * @param groupId the ID of the security group to delete
     * @return a CompletableFuture that completes when the security group is deleted
     */
    public CompletableFuture<Void> deleteEC2SecGroupAsync(String groupId) {
        DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder()
            .groupId(groupId)
            .build();

        CompletableFuture<DeleteSecurityGroupResponse> response = getAsyncClient().deleteSecurityGroup(request);
        return response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to delete security group with Id " + groupId, ex);
            } else if (resp == null) {
                throw new RuntimeException("No response received for deleting security group with Id " + groupId);
            }
        }).thenApply(resp -> null);
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteSecurityGroup)을 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { DeleteSecurityGroupCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Deletes a security group.
 * @param {{ groupId: string }} options
 */
export const main = async ({ groupId }) => {
  const client = new EC2Client({});
  const command = new DeleteSecurityGroupCommand({
    GroupId: groupId,
  });

  try {
    await client.send(command);
    console.log("Security group deleted successfully.");
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidGroupId.Malformed") {
      console.warn(`${caught.message}. Please provide a valid GroupId.`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteSecurityGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteSecurityGroupCommand)을 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun deleteEC2SecGroup(groupIdVal: String) {
    val request =
        DeleteSecurityGroupRequest {
            groupId = groupIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.deleteSecurityGroup(request)
        println("Successfully deleted Security Group with id $groupIdVal")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DeleteSecurityGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 EC2-VPC에 지정된 보안 그룹을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2SecurityGroup -GroupId sg-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SecurityGroup (DeleteSecurityGroup)" on Target "sg-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**예제 2: 이 예제에서는 EC2-Classic에 지정된 보안 그룹을 삭제합니다.**  

```
Remove-EC2SecurityGroup -GroupName my-security-group -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteSecurityGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 EC2-VPC에 지정된 보안 그룹을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2SecurityGroup -GroupId sg-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SecurityGroup (DeleteSecurityGroup)" on Target "sg-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**예제 2: 이 예제에서는 EC2-Classic에 지정된 보안 그룹을 삭제합니다.**  

```
Remove-EC2SecurityGroup -GroupName my-security-group -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteSecurityGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class SecurityGroupWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions."""

    def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None):
        """
        Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param security_group: The ID of a security group to manage. This is a high-level identifier
                               that represents the security group.
        """
        self.ec2_client = ec2_client
        self.security_group = security_group

    @classmethod
    def from_client(cls) -> "SecurityGroupWrapper":
        """
        Creates a SecurityGroupWrapper instance with a default EC2 client.

        :return: An instance of SecurityGroupWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def delete(self, security_group_id: str) -> bool:
        """
        Deletes the specified security group.

        :param security_group_id: The ID of the security group to delete. Required.

        :returns: True if the deletion is successful.
        :raises ClientError: If the security group cannot be deleted due to an AWS service error.
        """
        try:
            self.ec2_client.delete_security_group(GroupId=security_group_id)
            logger.info(f"Successfully deleted security group '{security_group_id}'")
            return True
        except ClientError as err:
            logger.error(f"Deletion failed for security group '{security_group_id}'")
            error_code = err.response["Error"]["Code"]

            if error_code == "InvalidGroup.NotFound":
                logger.error(
                    f"Security group '{security_group_id}' cannot be deleted because it does not exist."
                )
            elif error_code == "DependencyViolation":
                logger.error(
                    f"Security group '{security_group_id}' cannot be deleted because it is still in use."
                    " Verify that it is:"
                    "\n\t- Detached from resources"
                    "\n\t- Removed from references in other groups"
                    "\n\t- Removed from VPC's as a default group"
                )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteSecurityGroup)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn delete_security_group(&self, group_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Deleting security group {group_id}");
        self.client
            .delete_security_group()
            .group_id(group_id)
            .send()
            .await?;
        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DeleteSecurityGroup](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.delete_security_group)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ec2->deletesecuritygroup( iv_groupid = iv_security_group_id ).
        MESSAGE 'Security group deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeleteSecurityGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Delete a security group.
    /// 
    /// - Parameter groupId: The ID of the security group to delete.
    /// 
    /// - Returns: `true` on successful deletion; `false` on error.
    func deleteSecurityGroup(groupId: String) async -> Bool {
        do {
            _ = try await ec2Client.deleteSecurityGroup(
                input: DeleteSecurityGroupInput(
                    groupId: groupId
                )
            )

            return true
        } catch {
            print("*** Error deleting the security group: \(error.localizedDescription)")
            return false
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DeleteSecurityGroup](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/deletesecuritygroup(input:))을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DeleteSnapshot` 함께 사용
<a name="example_ec2_DeleteSnapshot_section"></a>

다음 코드 예시는 `DeleteSnapshot`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스냅샷을 삭제하는 방법**  
이 예제 명령은 스냅샷 ID가 `snap-1234567890abcdef0`인 스냅샷을 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-snapshot --snapshot-id snap-1234567890abcdef0
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DeleteSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-snapshot.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스냅샷을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Snapshot -SnapshotId snap-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Snapshot (DeleteSnapshot)" on target "snap-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteSnapshot](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스냅샷을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Snapshot -SnapshotId snap-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Snapshot (DeleteSnapshot)" on target "snap-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ebs#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
async fn delete_snapshot(client: &Client, id: &str) -> Result<(), Error> {
    client.delete_snapshot().snapshot_id(id).send().await?;

    println!("Deleted");

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DeleteSnapshot](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.delete_snapshot)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteSpotDatafeedSubscription` 사용
<a name="example_ec2_DeleteSpotDatafeedSubscription_section"></a>

다음 코드 예시는 `DeleteSpotDatafeedSubscription`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스팟 인스턴스 데이터 피드 구독 취소**  
이 예시에서는 계정에 대한 스팟 데이터 피드 구독을 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-spot-datafeed-subscription
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteSpotDatafeedSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-spot-datafeed-subscription.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 스팟 인스턴스 데이터 피드를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2SpotDatafeedSubscription
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SpotDatafeedSubscription (DeleteSpotDatafeedSubscription)" on Target "".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 스팟 인스턴스 데이터 피드를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2SpotDatafeedSubscription
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SpotDatafeedSubscription (DeleteSpotDatafeedSubscription)" on Target "".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteSubnet` 사용
<a name="example_ec2_DeleteSubnet_section"></a>

다음 코드 예시는 `DeleteSubnet`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**서브넷 삭제**  
이 예시에서는 지정된 서브넷을 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-subnet --subnet-id subnet-9d4a7b6c
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteSubnet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-subnet.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 서브넷을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Subnet (DeleteSubnet)" on Target "subnet-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteSubnet](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 서브넷을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Subnet (DeleteSubnet)" on Target "subnet-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteSubnet](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteTags` 사용
<a name="example_ec2_DeleteTags_section"></a>

다음 코드 예시는 `DeleteTags`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 리소스에서 태그 삭제**  
다음 `delete-tags` 예시에서는 지정된 이미지에서 태그 `Stack=Test`를 삭제합니다. 값과 키 이름을 모두 지정하는 경우 태그의 값이 지정된 값과 일치하는 경우에만 태그가 삭제됩니다.  

```
aws ec2 delete-tags \
    --resources ami-1234567890abcdef0 \
    --tags Key=Stack,Value=Test
```
태그의 값을 지정하는 것은 선택 사항입니다. 다음 `delete-tags` 태그의 태그 값에 관계없이 지정된 인스턴스에서 키 이름이 `purpose`인 태그를 삭제합니다.  

```
aws ec2 delete-tags \
    --resources i-1234567890abcdef0 \
    --tags Key=purpose
```
빈 문자열을 태그 값으로 지정하면 태그의 값이 빈 문자열인 경우에만 태그가 삭제됩니다. 다음 `delete-tags` 예시에서는 삭제할 태그의 태그 값으로 빈 문자열을 지정합니다.  

```
aws ec2 delete-tags \
    --resources i-1234567890abcdef0 \
    --tags Key=Name,Value=
```
**예시 2: 여러 리소스에서 태그 삭제**  
다음 `delete-tags` 예시에서는 인스턴스와 AMI 모두에서 태그``Purpose=Test``를 삭제합니다. 이전 예시에서와 같이 명령에서 태그 값을 생략할 수 있습니다.  

```
aws ec2 delete-tags \
    --resources i-1234567890abcdef0 ami-1234567890abcdef0 \
    --tags Key=Purpose
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-tags.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 태그 값에 관계없이 지정된 리소스에서 지정된 태그를 삭제합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag" } -Force
```
**예제 2: 이 예제에서는 태그 값이 일치하는 경우에만 지정된 리소스에서 지정된 태그를 삭제합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag";Value="myTagValue" } -Force
```
**예제 3: 이 예제에서는 태그 값에 관계없이 지정된 리소스에서 지정된 태그를 삭제합니다.**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
**예제 4: 이 예제에서는 태그 값이 일치하는 경우에만 지정된 리소스에서 지정된 태그를 삭제합니다.**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteTags](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 태그 값에 관계없이 지정된 리소스에서 지정된 태그를 삭제합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag" } -Force
```
**예제 2: 이 예제에서는 태그 값이 일치하는 경우에만 지정된 리소스에서 지정된 태그를 삭제합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag";Value="myTagValue" } -Force
```
**예제 3: 이 예제에서는 태그 값에 관계없이 지정된 리소스에서 지정된 태그를 삭제합니다.**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
**예제 4: 이 예제에서는 태그 값이 일치하는 경우에만 지정된 리소스에서 지정된 태그를 삭제합니다.**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteVolume` 사용
<a name="example_ec2_DeleteVolume_section"></a>

다음 코드 예시는 `DeleteVolume`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**볼륨 삭제**  
이 예시 명령은 볼륨 ID가 `vol-049df61146c4d7901`인 사용 가능한 볼륨을 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-volume --volume-id vol-049df61146c4d7901
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteVolume](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-volume.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 볼륨을 분리합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Volume -VolumeId vol-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Volume (DeleteVolume)" on target "vol-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteVolume](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 볼륨을 분리합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Volume -VolumeId vol-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Volume (DeleteVolume)" on target "vol-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteVolume](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DeleteVpc` 함께 사용
<a name="example_ec2_DeleteVpc_section"></a>

다음 코드 예시는 `DeleteVpc`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 
+  [VPC IPAM 시작하기](example_vpc_GettingStartedIpam_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**VPC를 삭제하는 방법**  
이 예시에서는 지정된 VPC를 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-vpc --vpc-id vpc-a01106c2
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpc.html) 섹션을 참조하세요.

------
#### [ PHP ]

**SDK for PHP**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * @param string $vpcId
     * @return void
     */
    public function deleteVpc(string $vpcId)
    {
        try {
            $this->ec2Client->deleteVpc([
                "VpcId" => $vpcId,
            ]);
        }catch(Ec2Exception $caught){
            echo "There was a problem deleting the VPC: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [DeleteVpc](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/DeleteVpc)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPC를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Vpc -VpcId vpc-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Vpc (DeleteVpc)" on Target "vpc-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteVpc](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPC를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2Vpc -VpcId vpc-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Vpc (DeleteVpc)" on Target "vpc-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteVpc](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def delete(self, vpc_id: str) -> None:
        """
        Deletes the specified VPC.

        :param vpc_id: The ID of the VPC to delete.
        """
        try:
            self.ec2_client.delete_vpc(VpcId=vpc_id)
        except ClientError as err:
            logger.error(
                "Couldn't delete VPC %s. Here's why: %s: %s",
                vpc_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteVpc](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteVpc)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ec2->deletevpc( iv_vpcid = iv_vpc_id ).
        MESSAGE 'Deleted VPC.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeleteVpc](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DeleteVpcEndpoints` 함께 사용
<a name="example_ec2_DeleteVpcEndpoints_section"></a>

다음 코드 예시는 `DeleteVpcEndpoints`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**엔드포인트 삭제**  
이 예시에서는 엔드포인트 vpce-aa22bb33 및 vpce-1a2b3c4d를 삭제합니다. 명령이 부분적으로 성공하거나 실패한 경우 실패한 항목의 목록이 반환됩니다. 명령이 성공하면 반환된 목록은 비어 있습니다.  
명령:  

```
aws ec2 delete-vpc-endpoints --vpc-endpoint-ids vpce-aa22bb33 vpce-1a2b3c4d
```
출력:  

```
{
  "Unsuccessful": []
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteVpcEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpc-endpoints.html) 섹션을 참조하세요.

------
#### [ PHP ]

**SDK for PHP**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * @param string $vpcEndpointId
     * @return void
     */
    public function deleteVpcEndpoint(string $vpcEndpointId)
    {
        try {
            $this->ec2Client->deleteVpcEndpoints([
                "VpcEndpointIds" => [$vpcEndpointId],
            ]);
        }catch (Ec2Exception $caught){
            echo "There was a problem deleting the VPC Endpoint: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [DeleteVpcEndpoints](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/DeleteVpcEndpoints)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def delete_vpc_endpoints(self, vpc_endpoint_ids: list[str]) -> None:
        """
        Deletes the specified VPC endpoints.

        :param vpc_endpoint_ids: A list of IDs of the VPC endpoints to delete.
        """
        try:
            self.ec2_client.delete_vpc_endpoints(VpcEndpointIds=vpc_endpoint_ids)
        except ClientError as err:
            logger.error(
                "Couldn't delete VPC endpoints %s. Here's why: %s: %s",
                vpc_endpoint_ids,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteVpcEndpoints](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteVpcEndpoints)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ec2->deletevpcendpoints( it_vpcendpointids = it_vpc_endpoint_ids ).
        MESSAGE 'Deleted VPC endpoint(s).' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 SDK for SAP ABAP API 참조의 [DeleteVpcEndpoints](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요. *AWS * 

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteVpnConnection` 사용
<a name="example_ec2_DeleteVpnConnection_section"></a>

다음 코드 예시는 `DeleteVpnConnection`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPN 연결 삭제**  
이 예시에서는 지정된 VPN 연결을 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-vpn-connection --vpn-connection-id vpn-40f41529
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteVpnConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpn-connection.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPN 연결을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnection (DeleteVpnConnection)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteVpnConnection](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPN 연결을 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnection (DeleteVpnConnection)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteVpnConnection](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteVpnConnectionRoute` 사용
<a name="example_ec2_DeleteVpnConnectionRoute_section"></a>

다음 코드 예시는 `DeleteVpnConnectionRoute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPN 연결에서 정적 경로 삭제**  
이 예시에서는 지정된 VPN 연결에서 지정된 정적 경로를 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-vpn-connection-route --vpn-connection-id vpn-40f41529 --destination-cidr-block 11.12.0.0/16
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteVpnConnectionRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpn-connection-route.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPN 연결에서 지정된 정적 경로를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnectionRoute (DeleteVpnConnectionRoute)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPN 연결에서 지정된 정적 경로를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnectionRoute (DeleteVpnConnectionRoute)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeleteVpnGateway` 사용
<a name="example_ec2_DeleteVpnGateway_section"></a>

다음 코드 예시는 `DeleteVpnGateway`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**가상 프라이빗 게이트웨이 삭제**  
이 예시에서는 지정된 가상 프라이빗 게이트웨이를 삭제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 delete-vpn-gateway --vpn-gateway-id vgw-9a4cacf3
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteVpnGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpn-gateway.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnGateway (DeleteVpnGateway)" on Target "vgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteVpnGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 삭제합니다. Force 파라미터를 함께 지정하지 않는 한 작업이 진행되기 전에 확인 프롬프트가 표시됩니다.**  

```
Remove-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnGateway (DeleteVpnGateway)" on Target "vgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DeregisterImage` 사용
<a name="example_ec2_DeregisterImage_section"></a>

다음 코드 예시는 `DeregisterImage`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**AMI 등록 해제**  
이 예시에서는 지정된 AMI의 등록을 취소합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 deregister-image --image-id ami-4fa54026
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeregisterImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/deregister-image.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 AMI의 등록을 취소합니다.**  

```
Unregister-EC2Image -ImageId ami-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeregisterImage](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 AMI의 등록을 취소합니다.**  

```
Unregister-EC2Image -ImageId ami-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeregisterImage](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeAccountAttributes` 사용
<a name="example_ec2_DescribeAccountAttributes_section"></a>

다음 코드 예시는 `DescribeAccountAttributes`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
** AWS 계정의 모든 속성을 설명하려면**  
이 예제에서는 AWS 계정의 속성을 설명합니다.  
명령:  

```
aws ec2 describe-account-attributes
```
출력:  

```
{
    "AccountAttributes": [
        {
            "AttributeName": "vpc-max-security-groups-per-interface",
            "AttributeValues": [
                {
                    "AttributeValue": "5"
                }
            ]
        },
        {
            "AttributeName": "max-instances",
            "AttributeValues": [
                {
                    "AttributeValue": "20"
                }
            ]
        },
        {
            "AttributeName": "supported-platforms",
            "AttributeValues": [
                {
                    "AttributeValue": "EC2"
                },
                {
                    "AttributeValue": "VPC"
                }
            ]
        },
        {
            "AttributeName": "default-vpc",
            "AttributeValues": [
                {
                    "AttributeValue": "none"
                }
            ]
        },
        {
            "AttributeName": "max-elastic-ips",
            "AttributeValues": [
                {
                    "AttributeValue": "5"
                }
            ]
        },
        {
            "AttributeName": "vpc-max-elastic-ips",
            "AttributeValues": [
                {
                    "AttributeValue": "5"
                }
            ]
        }
    ]
}
```
** AWS 계정의 단일 속성을 설명하려면**  
이 예제에서는 AWS 계정의 `supported-platforms` 속성을 설명합니다.  
명령:  

```
aws ec2 describe-account-attributes --attribute-names supported-platforms
```
출력:  

```
{
    "AccountAttributes": [
        {
            "AttributeName": "supported-platforms",
            "AttributeValues": [
                {
                    "AttributeValue": "EC2"
                },
                {
                    "AttributeValue": "VPC"
                }
            ]
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeAccountAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-account-attributes.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 리전의 EC2-Classic 및 EC2-VPC에서 인스턴스를 시작할 수 있는지 아니면 EC2-VPC에서만 인스턴스를 시작할 수 있는지 설명합니다.**  

```
(Get-EC2AccountAttribute -AttributeName supported-platforms).AttributeValues
```
**출력:**  

```
AttributeValue
--------------
EC2
VPC
```
**예제 2: 이 예제에서는 기본 VPC를 설명하며, 해당 리전에 기본 VPC가 없는 경우 'none'으로 표시됩니다.**  

```
(Get-EC2AccountAttribute -AttributeName default-vpc).AttributeValues
```
**출력:**  

```
AttributeValue
--------------
vpc-12345678
```
**예제 3: 이 예제에서는 실행할 수 있는 최대 온디맨드 인스턴스 수를 설명합니다.**  

```
(Get-EC2AccountAttribute -AttributeName max-instances).AttributeValues
```
**출력:**  

```
AttributeValue
--------------
20
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeAccountAttributes](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 리전의 EC2-Classic 및 EC2-VPC에서 인스턴스를 시작할 수 있는지 아니면 EC2-VPC에서만 인스턴스를 시작할 수 있는지 설명합니다.**  

```
(Get-EC2AccountAttribute -AttributeName supported-platforms).AttributeValues
```
**출력:**  

```
AttributeValue
--------------
EC2
VPC
```
**예제 2: 이 예제에서는 기본 VPC를 설명하며, 해당 리전에 기본 VPC가 없는 경우 'none'으로 표시됩니다.**  

```
(Get-EC2AccountAttribute -AttributeName default-vpc).AttributeValues
```
**출력:**  

```
AttributeValue
--------------
vpc-12345678
```
**예제 3: 이 예제에서는 실행할 수 있는 최대 온디맨드 인스턴스 수를 설명합니다.**  

```
(Get-EC2AccountAttribute -AttributeName max-instances).AttributeValues
```
**출력:**  

```
AttributeValue
--------------
20
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeAccountAttributes](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeAddresses` 함께 사용
<a name="example_ec2_DescribeAddresses_section"></a>

다음 코드 예시는 `DescribeAddresses`의 사용 방법을 보여 줍니다.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Describe all Elastic IP addresses.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeAddresses(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DescribeAddresses](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeAddresses) 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 모든 탄력적 IP 주소에 대한 세부 정보를 검색하는 방법**  
다음 `describe addresses` 예제에서는 탄력적 IP 주소에 대한 세부 정보를 표시합니다.  

```
aws ec2 describe-addresses
```
출력:  

```
{
    "Addresses": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "PublicIp": "198.51.100.0",
            "PublicIpv4Pool": "amazon",
            "Domain": "standard"
        },
        {
            "Domain": "vpc",
            "PublicIpv4Pool": "amazon",
            "InstanceId": "i-1234567890abcdef0",
            "NetworkInterfaceId": "eni-12345678",
            "AssociationId": "eipassoc-12345678",
            "NetworkInterfaceOwnerId": "123456789012",
            "PublicIp": "203.0.113.0",
            "AllocationId": "eipalloc-12345678",
            "PrivateIpAddress": "10.0.1.241"
        }
    ]
}
```
**예제 2: EC2-VPC에 대한 탄력적 IP 주소의 세부 정보를 검색하는 방법**  
다음 `describe-addresses` 예제에서는 VPC의 인스턴스에서 사용할 탄력적 IP 주소의 세부 정보를 표시합니다.  

```
aws ec2 describe-addresses \
    --filters "Name=domain,Values=vpc"
```
출력:  

```
{
    "Addresses": [
        {
            "Domain": "vpc",
            "PublicIpv4Pool": "amazon",
            "InstanceId": "i-1234567890abcdef0",
            "NetworkInterfaceId": "eni-12345678",
            "AssociationId": "eipassoc-12345678",
            "NetworkInterfaceOwnerId": "123456789012",
            "PublicIp": "203.0.113.0",
            "AllocationId": "eipalloc-12345678",
            "PrivateIpAddress": "10.0.1.241"
        }
    ]
}
```
**예제 3: 할당 ID로 지정된 탄력적 IP 주소의 세부 정보를 검색하는 방법**  
다음 `describe-addresses` 예제에서는 EC2-VPC의 인스턴스와 연결된, 지정된 할당 ID를 보유한 탄력적 IP 주소의 세부 정보를 표시합니다.  

```
aws ec2 describe-addresses \
    --allocation-ids eipalloc-282d9641
```
출력:  

```
{
    "Addresses": [
        {
            "Domain": "vpc",
            "PublicIpv4Pool": "amazon",
            "InstanceId": "i-1234567890abcdef0",
            "NetworkInterfaceId": "eni-1a2b3c4d",
            "AssociationId": "eipassoc-123abc12",
            "NetworkInterfaceOwnerId": "1234567891012",
            "PublicIp": "203.0.113.25",
            "AllocationId": "eipalloc-282d9641",
            "PrivateIpAddress": "10.251.50.12"
        }
    ]
}
```
**예제 4: VPC 프라이빗 IP 주소로 지정된 탄력적 IP 주소의 세부 정보를 검색하는 방법**  
다음 `describe-addresses` 예제에서는 EC2-VPC 내 특정 프라이빗 IP 주소와 연결된 탄력적 IP 주소의 세부 정보를 표시합니다.  

```
aws ec2 describe-addresses \
    --filters "Name=private-ip-address,Values=10.251.50.12"
```
**예제 5: EC2-Classic에서 탄력적 IP 주소의 세부 정보를 검색하는 방법**  
다음 `describe-addresses` 예제에서는 EC2-Classic에서 사용할 탄력적 IP 주소에 대한 세부 정보를 표시합니다.  

```
aws ec2 describe-addresses \
    --filters "Name=domain,Values=standard"
```
출력:  

```
{
    "Addresses": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "PublicIp": "203.0.110.25",
            "PublicIpv4Pool": "amazon",
            "Domain": "standard"
        }
    ]
}
```
**예제 6: 퍼블릭 IP 주소로 지정된 탄력적 IP 주소의 세부 정보를 검색하는 방법**  
다음 `describe-addresses` 예제에서는 EC2-Classic의 인스턴스와 연결된, 값이 `203.0.110.25`인 탄력적 IP 주소의 세부 정보를 표시합니다.  

```
aws ec2 describe-addresses \
    --public-ips 203.0.110.25
```
출력:  

```
{
    "Addresses": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "PublicIp": "203.0.110.25",
            "PublicIpv4Pool": "amazon",
            "Domain": "standard"
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeAddresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-addresses.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { DescribeAddressesCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Describes the specified Elastic IP addresses or all of your Elastic IP addresses.
 * @param {{ allocationId: string }} options
 */
export const main = async ({ allocationId }) => {
  const client = new EC2Client({});
  const command = new DescribeAddressesCommand({
    // You can omit this property to show all addresses.
    AllocationIds: [allocationId],
  });

  try {
    const { Addresses } = await client.send(command);
    const addressList = Addresses.map((address) => ` • ${address.PublicIp}`);
    console.log("Elastic IP addresses:");
    console.log(addressList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidAllocationID.NotFound"
    ) {
      console.warn(`${caught.message}. Please provide a valid AllocationId.`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DescribeAddresses](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeAddressesCommand) 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 EC2-Classic의 인스턴스에 대해 지정된 탄력적 IP 주소를 설명합니다.**  

```
Get-EC2Address -AllocationId eipalloc-12345678
```
**출력:**  

```
AllocationId            : eipalloc-12345678
AssociationId           : eipassoc-12345678
Domain                  : vpc
InstanceId              : i-87654321
NetworkInterfaceId      : eni-12345678
NetworkInterfaceOwnerId : 12345678
PrivateIpAddress        : 10.0.2.172
PublicIp                : 198.51.100.2
```
**예제 2: 이 예제에서는 VPC의 인스턴스에 대한 탄력적 IP 주소를 설명합니다. 이 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Get-EC2Address -Filter @{ Name="domain";Values="vpc" }
```
**예제 3: 이 예제에서는 EC2-Classic의 인스턴스에 대해 지정된 탄력적 IP 주소를 설명합니다.**  

```
Get-EC2Address -PublicIp 203.0.113.17
```
**출력:**  

```
AllocationId            :
AssociationId           :
Domain                  : standard
InstanceId              : i-12345678
NetworkInterfaceId      :
NetworkInterfaceOwnerId :
PrivateIpAddress        :
PublicIp                : 203.0.113.17
```
**예제 4: 이 예제에서는 EC2-Classic의 인스턴스에 대한 탄력적 IP 주소를 설명합니다. 이 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Get-EC2Address -Filter @{ Name="domain";Values="standard" }
```
**예제 5: 이 예제에서는 모든 탄력적 IP 주소를 설명합니다.**  

```
Get-EC2Address
```
**예제 6: 이 예제에서는 필터에 제공된 인스턴스 ID의 퍼블릭 및 프라이빗 IP를 반환합니다.**  

```
Get-EC2Address -Region eu-west-1 -Filter @{Name="instance-id";Values="i-0c12d3f4f567ffb89"} | Select-Object PrivateIpAddress, PublicIp
```
**출력:**  

```
PrivateIpAddress PublicIp
---------------- --------
10.0.0.99        63.36.5.227
```
**예제 7: 이 예제에서는 할당 ID, 연결 ID, 인스턴스 ID가 있는 모든 탄력적 IP를 검색합니다.**  

```
Get-EC2Address -Region eu-west-1 | Select-Object InstanceId, AssociationId, AllocationId, PublicIp
```
**출력:**  

```
InstanceId          AssociationId              AllocationId               PublicIp
----------          -------------              ------------               --------
                                               eipalloc-012e3b456789e1fad 17.212.120.178
i-0c123dfd3415bac67 eipassoc-0e123456bb7890bdb eipalloc-01cd23ebf45f7890c 17.212.124.77
                                               eipalloc-012345678eeabcfad 17.212.225.7
i-0123d405c67e89a0c eipassoc-0c123b456783966ba eipalloc-0123cdd456a8f7892 37.216.52.173
i-0f1bf2f34c5678d09 eipassoc-0e12934568a952d96 eipalloc-0e1c23e4d5e6789e4 37.218.222.278
i-012e3cb4df567e8aa eipassoc-0d1b2fa4d67d03810 eipalloc-0123f456f78a01b58 37.210.82.27
i-0123bcf4b567890e1 eipassoc-01d2345f678903fb1 eipalloc-0e1db23cfef5c45c7 37.215.222.270
```
**예제 8: 이 예제에서는 태그 키가 'Category'이고 값이 'Prod'인 EC2 IP 주소 목록을 가져옵니다.**  

```
Get-EC2Address -Filter @{Name="tag:Category";Values="Prod"}
```
**출력:**  

```
AllocationId            : eipalloc-0123f456f81a01b58
AssociationId           : eipassoc-0d1b23a456d103810
CustomerOwnedIp         :
CustomerOwnedIpv4Pool   :
Domain                  : vpc
InstanceId              : i-012e3cb4df567e1aa
NetworkBorderGroup      : eu-west-1
NetworkInterfaceId      : eni-0123f41d5a60d5f40
NetworkInterfaceOwnerId : 123456789012
PrivateIpAddress        : 192.168.1.84
PublicIp                : 34.250.81.29
PublicIpv4Pool          : amazon
Tags                    : {Category, Name}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeAddresses](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 EC2-Classic의 인스턴스에 대해 지정된 탄력적 IP 주소를 설명합니다.**  

```
Get-EC2Address -AllocationId eipalloc-12345678
```
**출력:**  

```
AllocationId            : eipalloc-12345678
AssociationId           : eipassoc-12345678
Domain                  : vpc
InstanceId              : i-87654321
NetworkInterfaceId      : eni-12345678
NetworkInterfaceOwnerId : 12345678
PrivateIpAddress        : 10.0.2.172
PublicIp                : 198.51.100.2
```
**예제 2: 이 예제에서는 VPC의 인스턴스에 대한 탄력적 IP 주소를 설명합니다. 이 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Get-EC2Address -Filter @{ Name="domain";Values="vpc" }
```
**예제 3: 이 예제에서는 EC2-Classic의 인스턴스에 대해 지정된 탄력적 IP 주소를 설명합니다.**  

```
Get-EC2Address -PublicIp 203.0.113.17
```
**출력:**  

```
AllocationId            :
AssociationId           :
Domain                  : standard
InstanceId              : i-12345678
NetworkInterfaceId      :
NetworkInterfaceOwnerId :
PrivateIpAddress        :
PublicIp                : 203.0.113.17
```
**예제 4: 이 예제에서는 EC2-Classic의 인스턴스에 대한 탄력적 IP 주소를 설명합니다. 이 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Get-EC2Address -Filter @{ Name="domain";Values="standard" }
```
**예제 5: 이 예제에서는 모든 탄력적 IP 주소를 설명합니다.**  

```
Get-EC2Address
```
**예제 6: 이 예제에서는 필터에 제공된 인스턴스 ID의 퍼블릭 및 프라이빗 IP를 반환합니다.**  

```
Get-EC2Address -Region eu-west-1 -Filter @{Name="instance-id";Values="i-0c12d3f4f567ffb89"} | Select-Object PrivateIpAddress, PublicIp
```
**출력:**  

```
PrivateIpAddress PublicIp
---------------- --------
10.0.0.99        63.36.5.227
```
**예제 7: 이 예제에서는 할당 ID, 연결 ID, 인스턴스 ID가 있는 모든 탄력적 IP를 검색합니다.**  

```
Get-EC2Address -Region eu-west-1 | Select-Object InstanceId, AssociationId, AllocationId, PublicIp
```
**출력:**  

```
InstanceId          AssociationId              AllocationId               PublicIp
----------          -------------              ------------               --------
                                               eipalloc-012e3b456789e1fad 17.212.120.178
i-0c123dfd3415bac67 eipassoc-0e123456bb7890bdb eipalloc-01cd23ebf45f7890c 17.212.124.77
                                               eipalloc-012345678eeabcfad 17.212.225.7
i-0123d405c67e89a0c eipassoc-0c123b456783966ba eipalloc-0123cdd456a8f7892 37.216.52.173
i-0f1bf2f34c5678d09 eipassoc-0e12934568a952d96 eipalloc-0e1c23e4d5e6789e4 37.218.222.278
i-012e3cb4df567e8aa eipassoc-0d1b2fa4d67d03810 eipalloc-0123f456f78a01b58 37.210.82.27
i-0123bcf4b567890e1 eipassoc-01d2345f678903fb1 eipalloc-0e1db23cfef5c45c7 37.215.222.270
```
**예제 8: 이 예제에서는 태그 키가 'Category'이고 값이 'Prod'인 EC2 IP 주소 목록을 가져옵니다.**  

```
Get-EC2Address -Filter @{Name="tag:Category";Values="Prod"}
```
**출력:**  

```
AllocationId            : eipalloc-0123f456f81a01b58
AssociationId           : eipassoc-0d1b23a456d103810
CustomerOwnedIp         :
CustomerOwnedIpv4Pool   :
Domain                  : vpc
InstanceId              : i-012e3cb4df567e1aa
NetworkBorderGroup      : eu-west-1
NetworkInterfaceId      : eni-0123f41d5a60d5f40
NetworkInterfaceOwnerId : 123456789012
PrivateIpAddress        : 192.168.1.84
PublicIp                : 34.250.81.29
PublicIpv4Pool          : amazon
Tags                    : {Category, Name}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeAddresses](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->describeaddresses( ).                        " oo_result is returned for testing purposes. "
        DATA(lt_addresses) = oo_result->get_addresses( ).
        MESSAGE 'Retrieved information about Elastic IP addresses.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DescribeAddresses](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeAvailabilityZones` 함께 사용
<a name="example_ec2_DescribeAvailabilityZones_section"></a>

다음 코드 예시는 `DescribeAvailabilityZones`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](example_cross_ResilientService_section.md) 
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 
+  [Transit Gateway 시작하기](example_vpc_TransitGatewayGettingStarted_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Get a list of Availability Zones in the AWS Region of the Amazon EC2 Client.
    /// </summary>
    /// <returns>A list of availability zones.</returns>
    public async Task<List<string>> DescribeAvailabilityZones()
    {
        try
        {
            var zoneResponse = await _amazonEc2.DescribeAvailabilityZonesAsync(
                new DescribeAvailabilityZonesRequest());
            return zoneResponse.AvailabilityZones.Select(z => z.ZoneName).ToList();
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            _logger.LogError($"An Amazon EC2 error occurred while listing availability zones.: {ec2Exception.Message}");
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while listing availability zones.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeAvailabilityZones)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! DescribeAvailabilityZones
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
int AwsDoc::EC2::describeAvailabilityZones(const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    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;

    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeAvailabilityZones)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**가용 영역을 설명하는 방법**  
다음 `describe-availability-zones` 예제에서는 사용 가능한 가용 영역에 대한 세부 정보를 표시합니다. 응답에는 현재 리전의 가용 영역만 포함됩니다. 이 예제에서는 프로파일의 기본 `us-west-2`(오리건) 리전을 사용합니다.  

```
aws ec2 describe-availability-zones
```
출력:  

```
{
    "AvailabilityZones": [
        {
            "State": "available",
            "OptInStatus": "opt-in-not-required",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2a",
            "ZoneId": "usw2-az1",
            "GroupName": "us-west-2",
            "NetworkBorderGroup": "us-west-2"
        },
        {
            "State": "available",
            "OptInStatus": "opt-in-not-required",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2b",
            "ZoneId": "usw2-az2",
            "GroupName": "us-west-2",
            "NetworkBorderGroup": "us-west-2"
        },
        {
            "State": "available",
            "OptInStatus": "opt-in-not-required",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2c",
            "ZoneId": "usw2-az3",
            "GroupName": "us-west-2",
            "NetworkBorderGroup": "us-west-2"
        },
        {
            "State": "available",
            "OptInStatus": "opt-in-not-required",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2d",
            "ZoneId": "usw2-az4",
            "GroupName": "us-west-2",
            "NetworkBorderGroup": "us-west-2"
        },
        {
            "State": "available",
            "OptInStatus": "opted-in",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2-lax-1a",
            "ZoneId": "usw2-lax1-az1",
            "GroupName": "us-west-2-lax-1",
            "NetworkBorderGroup": "us-west-2-lax-1"
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeAvailabilityZones](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-availability-zones.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 사용 가능한 현재 리전의 가용 영역을 설명합니다.**  

```
Get-EC2AvailabilityZone
```
**출력:**  

```
Messages    RegionName    State        ZoneName
--------    ----------    -----        --------
{}          us-west-2     available    us-west-2a
{}          us-west-2     available    us-west-2b
{}          us-west-2     available    us-west-2c
```
**예제 2: 이 예제에서는 손상된 상태의 가용 영역을 설명합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Get-EC2AvailabilityZone -Filter @{ Name="state";Values="impaired" }
```
**예제 3: PowerShell 버전 2에서 필터를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = "impaired"

Get-EC2AvailabilityZone -Filter $filter
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeAvailabilityZones](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 사용 가능한 현재 리전의 가용 영역을 설명합니다.**  

```
Get-EC2AvailabilityZone
```
**출력:**  

```
Messages    RegionName    State        ZoneName
--------    ----------    -----        --------
{}          us-west-2     available    us-west-2a
{}          us-west-2     available    us-west-2b
{}          us-west-2     available    us-west-2c
```
**예제 2: 이 예제에서는 손상된 상태의 가용 영역을 설명합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
Get-EC2AvailabilityZone -Filter @{ Name="state";Values="impaired" }
```
**예제 3: PowerShell 버전 2에서 필터를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = "impaired"

Get-EC2AvailabilityZone -Filter $filter
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeAvailabilityZones](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def get_availability_zones(self) -> List[str]:
        """
        Gets a list of Availability Zones in the AWS Region of the Amazon EC2 client.

        :return: The list of Availability Zones for the client Region.
        """
        try:
            response = self.ec2_client.describe_availability_zones()
            zones = [zone["ZoneName"] for zone in response["AvailabilityZones"]]
            log.info(f"Retrieved {len(zones)} availability zones: {zones}.")
        except ClientError as err:
            log.error("Failed to retrieve availability zones.")
            log.error(f"Full error:\n\t{err}")
        else:
            return zones
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeAvailabilityZones)를 참조하십시오.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->describeavailabilityzones( ).                        " oo_result is returned for testing purposes. "
        DATA(lt_zones) = oo_result->get_availabilityzones( ).
        MESSAGE 'Retrieved information about Availability Zones.' TYPE 'I'.

      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DescribeAvailabilityZones](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeBundleTasks` 사용
<a name="example_ec2_DescribeBundleTasks_section"></a>

다음 코드 예시는 `DescribeBundleTasks`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**번들 태스크 설명**  
이 예시에서는 모든 번들 태스크를 설명합니다.  
명령:  

```
aws ec2 describe-bundle-tasks
```
출력:  

```
{
  "BundleTasks": [
    {
      "UpdateTime": "2015-09-15T13:26:54.000Z",
      "InstanceId": "i-1234567890abcdef0",
      "Storage": {
        "S3": {
            "Prefix": "winami",
            "Bucket": "bundletasks"
        }
      },
      "State": "bundling",
      "StartTime": "2015-09-15T13:24:35.000Z",
      "Progress": "3%",
      "BundleId": "bun-2a4e041c"
    }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeBundleTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-bundle-tasks.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 번들 작업을 설명합니다.**  

```
Get-EC2BundleTask -BundleId bun-12345678
```
**예제 2: 이 예제에서는 상태가 'complete' 또는 'failed'인 번들 작업을 설명합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "complete", "failed" )

Get-EC2BundleTask -Filter $filter
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeBundleTasks](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 번들 작업을 설명합니다.**  

```
Get-EC2BundleTask -BundleId bun-12345678
```
**예제 2: 이 예제에서는 상태가 'complete' 또는 'failed'인 번들 작업을 설명합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "complete", "failed" )

Get-EC2BundleTask -Filter $filter
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeBundleTasks](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeCapacityReservations` 사용
<a name="example_ec2_DescribeCapacityReservations_section"></a>

다음 코드 예시는 `DescribeCapacityReservations`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 하나 이상의 용량 예약 설명**  
다음 `describe-capacity-reservations` 예시에서는 현재 AWS 리전의 모든 용량 예약에 대한 세부 정보를 표시합니다.  

```
aws ec2 describe-capacity-reservations
```
출력:  

```
{
    "CapacityReservations": [
        {
            "CapacityReservationId": "cr-1234abcd56EXAMPLE ",
            "OwnerId": "123456789111",
            "CapacityReservationArn": "arn:aws:ec2:us-east-1:123456789111:capacity-reservation/cr-1234abcd56EXAMPLE",
            "AvailabilityZoneId": "use1-az2",
            "InstanceType": "c5.large",
            "InstancePlatform": "Linux/UNIX",
            "AvailabilityZone": "us-east-1a",
            "Tenancy": "default",
            "TotalInstanceCount": 1,
            "AvailableInstanceCount": 1,
            "EbsOptimized": true,
            "EphemeralStorage": false,
            "State": "active",
            "StartDate": "2024-10-23T15:00:24+00:00",
            "EndDateType": "unlimited",
            "InstanceMatchCriteria": "open",
            "CreateDate": "2024-10-23T15:00:24+00:00",
            "Tags": [],
            "CapacityAllocations": []
        },
        {
            "CapacityReservationId": "cr-abcdEXAMPLE9876ef ",
            "OwnerId": "123456789111",
            "CapacityReservationArn": "arn:aws:ec2:us-east-1:123456789111:capacity-reservation/cr-abcdEXAMPLE9876ef",
            "AvailabilityZoneId": "use1-az2",
            "InstanceType": "c4.large",
            "InstancePlatform": "Linux/UNIX",
            "AvailabilityZone": "us-east-1a",
            "Tenancy": "default",
            "TotalInstanceCount": 1,
            "AvailableInstanceCount": 1,
            "EbsOptimized": true,
            "EphemeralStorage": false,
            "State": "cancelled",
            "StartDate": "2024-10-23T15:01:03+00:00",
            "EndDateType": "unlimited",
            "InstanceMatchCriteria": "open",
            "CreateDate": "2024-10-23T15:01:02+00:00",
            "Tags": [],
            "CapacityAllocations": []
        }
    ]
}
```
**예시 2: 하나 이상의 용량 예약 설명**  
다음 `describe-capacity-reservations` 예시에서는 지정된 용량 예약에 대한 세부 정보를 표시합니다.  

```
aws ec2 describe-capacity-reservations \
    --capacity-reservation-ids cr-1234abcd56EXAMPLE
```
출력:  

```
{
    "CapacityReservations": [
        {
            "CapacityReservationId": "cr-abcdEXAMPLE9876ef ",
            "OwnerId": "123456789111",
            "CapacityReservationArn": "arn:aws:ec2:us-east-1:123456789111:capacity-reservation/cr-abcdEXAMPLE9876ef",
            "AvailabilityZoneId": "use1-az2",
            "InstanceType": "c4.large",
            "InstancePlatform": "Linux/UNIX",
            "AvailabilityZone": "us-east-1a",
            "Tenancy": "default",
            "TotalInstanceCount": 1,
            "AvailableInstanceCount": 1,
            "EbsOptimized": true,
            "EphemeralStorage": false,
            "State": "active",
            "StartDate": "2024-10-23T15:01:03+00:00",
            "EndDateType": "unlimited",
            "InstanceMatchCriteria": "open",
            "CreateDate": "2024-10-23T15:01:02+00:00",
            "Tags": [],
            "CapacityAllocations": []
        }
    ]
}
```
자세한 내용은 *Linux 인스턴스용 Amazon Elastic Compute Cloud 사용 설명서*의 [용량 예약 보기](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html#capacity-reservations-view)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeCapacityReservations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-capacity-reservations.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 리전에 대한 하나 이상의 용량 예약을 설명합니다.**  

```
Get-EC2CapacityReservation -Region eu-west-1
```
**출력:**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeCapacityReservations](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 리전에 대한 하나 이상의 용량 예약을 설명합니다.**  

```
Get-EC2CapacityReservation -Region eu-west-1
```
**출력:**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeCapacityReservations](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeCustomerGateways` 사용
<a name="example_ec2_DescribeCustomerGateways_section"></a>

다음 코드 예시는 `DescribeCustomerGateways`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**고객 게이트웨이 설명**  
이 예시에서는 고객 게이트웨이를 설명합니다.  
명령:  

```
aws ec2 describe-customer-gateways
```
출력:  

```
{
    "CustomerGateways": [
        {
            "CustomerGatewayId": "cgw-b4dc3961",
            "IpAddress": "203.0.113.12",
            "State": "available",
            "Type": "ipsec.1",
            "BgpAsn": "65000"
        },
        {
            "CustomerGatewayId": "cgw-0e11f167",
            "IpAddress": "12.1.2.3",
            "State": "available",
            "Type": "ipsec.1",
            "BgpAsn": "65534"
        }
    ]
}
```
**특정 고객 게이트웨이 설명**  
이 예시에서는 지정된 고객 게이트웨이를 설명합니다.  
명령:  

```
aws ec2 describe-customer-gateways --customer-gateway-ids cgw-0e11f167
```
출력:  

```
{
    "CustomerGateways": [
        {
            "CustomerGatewayId": "cgw-0e11f167",
            "IpAddress": "12.1.2.3",
            "State": "available",
            "Type": "ipsec.1",
            "BgpAsn": "65534"
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeCustomerGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-customer-gateways.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 고객 게이트웨이를 설명합니다.**  

```
Get-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**출력:**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
**예제 2: 이 예제에서는 상태가 pending이거나 available인 모든 고객 게이트웨이를 설명합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2CustomerGateway -Filter $filter
```
**예제 3: 이 예제에서는 모든 고객 게이트웨이를 설명합니다.**  

```
Get-EC2CustomerGateway
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeCustomerGateways](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 고객 게이트웨이를 설명합니다.**  

```
Get-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**출력:**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
**예제 2: 이 예제에서는 상태가 pending이거나 available인 모든 고객 게이트웨이를 설명합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2CustomerGateway -Filter $filter
```
**예제 3: 이 예제에서는 모든 고객 게이트웨이를 설명합니다.**  

```
Get-EC2CustomerGateway
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeCustomerGateways](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeDhcpOptions` 사용
<a name="example_ec2_DescribeDhcpOptions_section"></a>

다음 코드 예시는 `DescribeDhcpOptions`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: DHCP 옵션 설명**  
다음 `describe-dhcp-options` 예시에서는 DHCP 옵션에 대한 세부 정보를 검색합니다.  

```
aws ec2 describe-dhcp-options
```
출력:  

```
{
    "DhcpOptions": [
        {
            "DhcpConfigurations": [
                {
                    "Key": "domain-name",
                    "Values": [
                        {
                            "Value": "us-east-2.compute.internal"
                        }
                    ]
                },
                {
                    "Key": "domain-name-servers",
                    "Values": [
                        {
                            "Value": "AmazonProvidedDNS"
                        }
                    ]
                }
            ],
            "DhcpOptionsId": "dopt-19edf471",
            "OwnerId": "111122223333"
        },
        {
            "DhcpConfigurations": [
                {
                    "Key": "domain-name",
                    "Values": [
                        {
                            "Value": "us-east-2.compute.internal"
                        }
                    ]
                },
                {
                    "Key": "domain-name-servers",
                    "Values": [
                        {
                            "Value": "AmazonProvidedDNS"
                        }
                    ]
                }
            ],
            "DhcpOptionsId": "dopt-fEXAMPLE",
            "OwnerId": "111122223333"
        }
    ]
}
```
자세한 내용은 *AWS Amazon VPC 사용 설명서*의 [DHCP 옵션 세트 작업](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html#DHCPOptionSet)을 참조하세요.  
**예시 2: DHCP 옵션 설명 및 출력 필터링**  
다음 `describe-dhcp-options` 예시에서는 도메인 네임 서버에 `example.com`가 있는 DHCP 옵션만 반환하는 필터를 사용하여 DHCP 옵션을 설명합니다. 이 예시에서는 `--query` 파라미터를 사용하여 출력에 구성 정보와 ID만 표시할 수 있습니다.  

```
aws ec2 describe-dhcp-options \
    --filters Name=key,Values=domain-name-servers Name=value,Values=example.com \
    --query "DhcpOptions[*].[DhcpConfigurations,DhcpOptionsId]"
```
출력:  

```
[
    [
        [
            {
                "Key": "domain-name",
                "Values": [
                    {
                        "Value": "example.com"
                    }
                ]
            },
            {
                "Key": "domain-name-servers",
                "Values": [
                    {
                        "Value": "172.16.16.16"
                    }
                ]
            }
        ],
        "dopt-001122334455667ab"
    ]
]
```
자세한 내용은 *AWS Amazon VPC 사용 설명서*의 [DHCP 옵션 세트 작업](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html#DHCPOptionSet)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeDhcpOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-dhcp-options.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 DHCP 옵션 세트를 나열합니다.**  

```
Get-EC2DhcpOption
```
**출력:**  

```
DhcpConfigurations                    DhcpOptionsId    Tag
------------------                    -------------    ---
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
{domain-name-servers}                 dopt-3a4b5c6d    {}
```
**예제 2: 이 예제에서는 지정된 DHCP 옵션 세트에 대한 구성 세부 정보를 가져옵니다.**  

```
(Get-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d).DhcpConfigurations
```
**출력:**  

```
Key                    Values
---                    ------
domain-name            {abc.local}
domain-name-servers    {10.0.0.101, 10.0.0.102}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeDhcpOptions](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 DHCP 옵션 세트를 나열합니다.**  

```
Get-EC2DhcpOption
```
**출력:**  

```
DhcpConfigurations                    DhcpOptionsId    Tag
------------------                    -------------    ---
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
{domain-name-servers}                 dopt-3a4b5c6d    {}
```
**예제 2: 이 예제에서는 지정된 DHCP 옵션 세트에 대한 구성 세부 정보를 가져옵니다.**  

```
(Get-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d).DhcpConfigurations
```
**출력:**  

```
Key                    Values
---                    ------
domain-name            {abc.local}
domain-name-servers    {10.0.0.101, 10.0.0.102}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeFlowLogs` 사용
<a name="example_ec2_DescribeFlowLogs_section"></a>

다음 코드 예시는 `DescribeFlowLogs`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 모든 흐름 로그 설명**  
다음 `describe-flow-logs` 예시에서는 모든 흐름 로그에 대한 세부 정보를 표시합니다.  

```
aws ec2 describe-flow-logs
```
출력:  

```
{
    "FlowLogs": [
        {
            "CreationTime": "2018-02-21T13:22:12.644Z",
            "DeliverLogsPermissionArn": "arn:aws:iam::123456789012:role/flow-logs-role",
            "DeliverLogsStatus": "SUCCESS",
            "FlowLogId": "fl-aabbccdd112233445",
            "MaxAggregationInterval": 600,
            "FlowLogStatus": "ACTIVE",
            "LogGroupName": "FlowLogGroup",
            "ResourceId": "subnet-12345678901234567",
            "TrafficType": "ALL",
            "LogDestinationType": "cloud-watch-logs",
            "LogFormat": "${version} ${account-id} ${interface-id} ${srcaddr} ${dstaddr} ${srcport} ${dstport} ${protocol} ${packets} ${bytes} ${start} ${end} ${action} ${log-status}"
        },
        {
            "CreationTime": "2020-02-04T15:22:29.986Z",
            "DeliverLogsStatus": "SUCCESS",
            "FlowLogId": "fl-01234567890123456",
            "MaxAggregationInterval": 60,
            "FlowLogStatus": "ACTIVE",
            "ResourceId": "vpc-00112233445566778",
            "TrafficType": "ACCEPT",
            "LogDestinationType": "s3",
            "LogDestination": "arn:aws:s3:::my-flow-log-bucket/custom",
            "LogFormat": "${version} ${vpc-id} ${subnet-id} ${instance-id} ${interface-id} ${account-id} ${type} ${srcaddr} ${dstaddr} ${srcport} ${dstport} ${pkt-srcaddr} ${pkt-dstaddr} ${protocol} ${bytes} ${packets} ${start} ${end} ${action} ${tcp-flags} ${log-status}"
        }
    ]
}
```
**예시 2: 흐름 로그의 하위 세트 설명**  
다음 `describe-flow-logs` 예시에서는 필터를 사용하여 Amazon CloudWatch Logs에서 지정된 로그 그룹에 있는 흐름 로그에 대한 세부 정보만 표시합니다.  

```
aws ec2 describe-flow-logs \
    --filter "Name=log-group-name,Values=MyFlowLogs"
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeFlowLogs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-flow-logs.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 로그 대상 유형이 's3'인 하나 이상의 흐름 로그를 설명합니다.**  

```
Get-EC2FlowLog -Filter @{Name="log-destination-type";Values="s3"}
```
**출력:**  

```
CreationTime             : 2/25/2019 9:07:36 PM
DeliverLogsErrorMessage  :
DeliverLogsPermissionArn :
DeliverLogsStatus        : SUCCESS
FlowLogId                : fl-01b2e3d45f67f8901
FlowLogStatus            : ACTIVE
LogDestination           : arn:aws:s3:::amzn-s3-demo-bucket-dd-tata
LogDestinationType       : s3
LogGroupName             :
ResourceId               : eni-01d2dda3456b7e890
TrafficType              : ALL
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeFlowLogs](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 로그 대상 유형이 's3'인 하나 이상의 흐름 로그를 설명합니다.**  

```
Get-EC2FlowLog -Filter @{Name="log-destination-type";Values="s3"}
```
**출력:**  

```
CreationTime             : 2/25/2019 9:07:36 PM
DeliverLogsErrorMessage  :
DeliverLogsPermissionArn :
DeliverLogsStatus        : SUCCESS
FlowLogId                : fl-01b2e3d45f67f8901
FlowLogStatus            : ACTIVE
LogDestination           : arn:aws:s3:::amzn-s3-demo-bucket-dd-tata
LogDestinationType       : s3
LogGroupName             :
ResourceId               : eni-01d2dda3456b7e890
TrafficType              : ALL
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeHostReservationOfferings` 사용
<a name="example_ec2_DescribeHostReservationOfferings_section"></a>

다음 코드 예시는 `DescribeHostReservationOfferings`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**전용 호스트 예약 제안 설명**  
이 예시에서는 구매할 수 있는 M4 인스턴스 제품군에 대한 전용 호스트 예약을 설명합니다.  
명령:  

```
aws ec2 describe-host-reservation-offerings --filter Name=instance-family,Values=m4
```
출력:  

```
{
  "OfferingSet": [
      {
          "HourlyPrice": "1.499",
          "OfferingId": "hro-03f707bf363b6b324",
          "InstanceFamily": "m4",
          "PaymentOption": "NoUpfront",
          "UpfrontPrice": "0.000",
          "Duration": 31536000
      },
      {
          "HourlyPrice": "1.045",
          "OfferingId": "hro-0ef9181cabdef7a02",
          "InstanceFamily": "m4",
          "PaymentOption": "NoUpfront",
          "UpfrontPrice": "0.000",
          "Duration": 94608000
      },
      {
          "HourlyPrice": "0.714",
          "OfferingId": "hro-04567a15500b92a51",
          "InstanceFamily": "m4",
          "PaymentOption": "PartialUpfront",
          "UpfrontPrice": "6254.000",
          "Duration": 31536000
      },
      {
          "HourlyPrice": "0.484",
          "OfferingId": "hro-0d5d7a9d23ed7fbfe",
          "InstanceFamily": "m4",
          "PaymentOption": "PartialUpfront",
          "UpfrontPrice": "12720.000",
          "Duration": 94608000
      },
      {
          "HourlyPrice": "0.000",
          "OfferingId": "hro-05da4108ca998c2e5",
          "InstanceFamily": "m4",
          "PaymentOption": "AllUpfront",
          "UpfrontPrice": "23913.000",
          "Duration": 94608000
      },
      {
          "HourlyPrice": "0.000",
          "OfferingId": "hro-0a9f9be3b95a3dc8f",
          "InstanceFamily": "m4",
          "PaymentOption": "AllUpfront",
          "UpfrontPrice": "12257.000",
          "Duration": 31536000
      }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeHostReservationOfferings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-host-reservation-offerings.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 PaymentOption이 'NoUpfront'인 지정된 'instance-family' 필터에 대해 구매할 수 있는 전용 호스트 예약을 설명합니다.**  

```
Get-EC2HostReservationOffering -Filter @{Name="instance-family";Values="m4"} | Where-Object PaymentOption -eq NoUpfront
```
**출력:**  

```
CurrencyCode   :
Duration       : 94608000
HourlyPrice    : 1.307
InstanceFamily : m4
OfferingId     : hro-0c1f234567890d9ab
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000

CurrencyCode   :
Duration       : 31536000
HourlyPrice    : 1.830
InstanceFamily : m4
OfferingId     : hro-04ad12aaaf34b5a67
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeHostReservationOfferings](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 PaymentOption이 'NoUpfront'인 지정된 'instance-family' 필터에 대해 구매할 수 있는 전용 호스트 예약을 설명합니다.**  

```
Get-EC2HostReservationOffering -Filter @{Name="instance-family";Values="m4"} | Where-Object PaymentOption -eq NoUpfront
```
**출력:**  

```
CurrencyCode   :
Duration       : 94608000
HourlyPrice    : 1.307
InstanceFamily : m4
OfferingId     : hro-0c1f234567890d9ab
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000

CurrencyCode   :
Duration       : 31536000
HourlyPrice    : 1.830
InstanceFamily : m4
OfferingId     : hro-04ad12aaaf34b5a67
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeHostReservationOfferings](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeHosts` 사용
<a name="example_ec2_DescribeHosts_section"></a>

다음 코드 예시는 `DescribeHosts`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**전용 호스트에 관한 세부 정보 보기**  
다음 `describe-hosts` 예시에서는 AWS 계정의 `available` 전용 호스트에 대한 세부 정보를 표시합니다.  

```
aws ec2 describe-hosts --filter "Name=state,Values=available"
```
출력:  

```
{
    "Hosts": [
        {
            "HostId": "h-07879acf49EXAMPLE",
            "Tags": [
                {
                    "Value": "production",
                    "Key": "purpose"
                }
            ],
            "HostProperties": {
                "Cores": 48,
                "TotalVCpus": 96,
                "InstanceType": "m5.large",
                "Sockets": 2
            },
            "Instances": [],
            "State": "available",
            "AvailabilityZone": "eu-west-1a",
            "AvailableCapacity": {
                "AvailableInstanceCapacity": [
                    {
                        "AvailableCapacity": 48,
                        "InstanceType": "m5.large",
                        "TotalCapacity": 48
                    }
                ],
                "AvailableVCpus": 96
            },
            "HostRecovery": "on",
            "AllocationTime": "2019-08-19T08:57:44.000Z",
            "AutoPlacement": "off"
        }
    ]
}
```
자세한 내용은 *Linux 인스턴스용 Amazon Elastic Compute Cloud 사용 설명서*의 [전용 호스트 보기](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/how-dedicated-hosts-work.html#dedicated-hosts-managing)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeHosts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-hosts.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 EC2 호스트 세부 정보를 반환합니다.**  

```
Get-EC2Host
```
**출력:**  

```
AllocationTime    : 3/23/2019 4:55:22 PM
AutoPlacement     : off
AvailabilityZone  : eu-west-1b
AvailableCapacity : Amazon.EC2.Model.AvailableCapacity
ClientToken       :
HostId            : h-01e23f4cd567890f1
HostProperties    : Amazon.EC2.Model.HostProperties
HostReservationId :
Instances         : {}
ReleaseTime       : 1/1/0001 12:00:00 AM
State             : available
Tags              : {}
```
**예제 2: 이 예제에서는 호스트 h-01e23f4cd567899f1에 대한 AvailableInstanceCapacity를 쿼리합니다.**  

```
Get-EC2Host -HostId h-01e23f4cd567899f1 | Select-Object -ExpandProperty AvailableCapacity | Select-Object -expand AvailableInstanceCapacity
```
**출력:**  

```
AvailableCapacity InstanceType TotalCapacity
----------------- ------------ -------------
11                m4.xlarge    11
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeHosts](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 EC2 호스트 세부 정보를 반환합니다.**  

```
Get-EC2Host
```
**출력:**  

```
AllocationTime    : 3/23/2019 4:55:22 PM
AutoPlacement     : off
AvailabilityZone  : eu-west-1b
AvailableCapacity : Amazon.EC2.Model.AvailableCapacity
ClientToken       :
HostId            : h-01e23f4cd567890f1
HostProperties    : Amazon.EC2.Model.HostProperties
HostReservationId :
Instances         : {}
ReleaseTime       : 1/1/0001 12:00:00 AM
State             : available
Tags              : {}
```
**예제 2: 이 예제에서는 호스트 h-01e23f4cd567899f1에 대한 AvailableInstanceCapacity를 쿼리합니다.**  

```
Get-EC2Host -HostId h-01e23f4cd567899f1 | Select-Object -ExpandProperty AvailableCapacity | Select-Object -expand AvailableInstanceCapacity
```
**출력:**  

```
AvailableCapacity InstanceType TotalCapacity
----------------- ------------ -------------
11                m4.xlarge    11
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeHosts](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeIamInstanceProfileAssociations` 함께 사용
<a name="example_ec2_DescribeIamInstanceProfileAssociations_section"></a>

다음 코드 예시는 `DescribeIamInstanceProfileAssociations`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](example_cross_ResilientService_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Get the instance profile association data for an instance.
    /// </summary>
    /// <param name="instanceId">The Id of the instance.</param>
    /// <returns>Instance profile associations data.</returns>
    public async Task<IamInstanceProfileAssociation> GetInstanceProfile(string instanceId)
    {
        try
        {
            var response = await _amazonEc2.DescribeIamInstanceProfileAssociationsAsync(
                new DescribeIamInstanceProfileAssociationsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("instance-id", new List<string>() { instanceId })
                    },
                });
            return response.IamInstanceProfileAssociations[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 **AWS SDK for .NET API 참조의 [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**IAM 인스턴스 프로파일 연결을 설명하는 방법**  
이 예제에서는 모든 IAM 인스턴스 프로파일 연결을 설명합니다.  
명령:  

```
aws ec2 describe-iam-instance-profile-associations
```
출력:  

```
{
  "IamInstanceProfileAssociations": [
      {
          "InstanceId": "i-09eb09efa73ec1dee",
          "State": "associated",
          "AssociationId": "iip-assoc-0db249b1f25fa24b8",
          "IamInstanceProfile": {
              "Id": "AIPAJVQN4F5WVLGCJDRGM",
              "Arn": "arn:aws:iam::123456789012:instance-profile/admin-role"
          }
      },
      {
          "InstanceId": "i-0402909a2f4dffd14",
          "State": "associating",
          "AssociationId": "iip-assoc-0d1ec06278d29f44a",
          "IamInstanceProfile": {
              "Id": "AGJAJVQN4F5WVLGCJABCM",
              "Arn": "arn:aws:iam::123456789012:instance-profile/user1-role"
          }
      }
   ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeIamInstanceProfileAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-iam-instance-profile-associations.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
      const ec2Client = new EC2Client({});
      const { IamInstanceProfileAssociations } = await ec2Client.send(
        new DescribeIamInstanceProfileAssociationsCommand({
          Filters: [
            { Name: "instance-id", Values: [state.targetInstance.InstanceId] },
          ],
        }),
      );
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeIamInstanceProfileAssociationsCommand)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def get_instance_profile(self, instance_id: str) -> Dict[str, Any]:
        """
        Gets data about the profile associated with an instance.

        :param instance_id: The ID of the instance to look up.
        :return: The profile data.
        """
        try:
            response = self.ec2_client.describe_iam_instance_profile_associations(
                Filters=[{"Name": "instance-id", "Values": [instance_id]}]
            )
            if not response["IamInstanceProfileAssociations"]:
                log.info(f"No instance profile found for instance {instance_id}.")
            profile_data = response["IamInstanceProfileAssociations"][0]
            log.info(f"Retrieved instance profile for instance {instance_id}.")
            return profile_data
        except ClientError as err:
            log.error(
                f"Failed to retrieve instance profile for instance {instance_id}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                log.error(f"The instance ID '{instance_id}' does not exist.")
            log.error(f"Full error:\n\t{err}")
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeIdFormat` 사용
<a name="example_ec2_DescribeIdFormat_section"></a>

다음 코드 예시는 `DescribeIdFormat`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 리소스의 ID 형식 설명**  
다음 `describe-id-format` 예시에서는 보안 그룹의 ID 형식 지정을 설명합니다.  

```
aws ec2 describe-id-format \
    --resource security-group
```
다음 예시 출력에서는 `Deadline` 값이 이 리소스 유형이 짧은 ID 형식에서 긴 ID 형식으로 영구적으로 전환해야 하는 기한이 2018년 8월 15일 00:00 UTC에 만료되었음을 나타냅니다.  

```
{
    "Statuses": [
        {
            "Deadline": "2018-08-15T00:00:00.000Z",
            "Resource": "security-group",
            "UseLongIds": true
        }
    ]
}
```
**예시 2: 모든 리소스의 ID 형식 설명**  
다음 `describe-id-format` 예시에서는 모든 리소스 유형에 대한 ID 형식을 설명합니다. 짧은 ID 형식을 지원하던 모든 리소스 유형이 긴 ID 형식을 사용하도록 전환되었습니다.  

```
aws ec2 describe-id-format
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeIdFormat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-id-format.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 리소스 유형의 ID 형식을 설명합니다.**  

```
Get-EC2IdFormat -Resource instance
```
**출력:**  

```
Resource       UseLongIds
--------       ----------
instance       False
```
**예제 2: 이 예제에서는 더 긴 ID를 지원하는 모든 리소스 유형의 ID 형식을 설명합니다.**  

```
Get-EC2IdFormat
```
**출력:**  

```
Resource       UseLongIds
--------       ----------
reservation    False
instance       False
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeIdFormat](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 리소스 유형의 ID 형식을 설명합니다.**  

```
Get-EC2IdFormat -Resource instance
```
**출력:**  

```
Resource       UseLongIds
--------       ----------
instance       False
```
**예제 2: 이 예제에서는 더 긴 ID를 지원하는 모든 리소스 유형의 ID 형식을 설명합니다.**  

```
Get-EC2IdFormat
```
**출력:**  

```
Resource       UseLongIds
--------       ----------
reservation    False
instance       False
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeIdentityIdFormat` 사용
<a name="example_ec2_DescribeIdentityIdFormat_section"></a>

다음 코드 예시는 `DescribeIdentityIdFormat`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**IAM 역할의 ID 형식 설명**  
다음 `describe-identity-id-format` 예제에서는 `EC2Role` AWS 계정의 IAM 역할에서 생성한 인스턴스에서 수신한 ID 형식을 설명합니다.  

```
aws ec2 describe-identity-id-format \
    --principal-arn arn:aws:iam::123456789012:role/my-iam-role \
    --resource instance
```
다음 출력에서는 이 역할에 의해 생성된 인스턴스가 긴 ID 형식의 ID를 수신한다는 것을 나타냅니다.  

```
{
    "Statuses": [
        {
            "Deadline": "2016-12-15T00:00:00Z",
            "Resource": "instance",
            "UseLongIds": true
        }
    ]
}
```
**IAM 사용자의 ID 형식 설명**  
다음 `describe-identity-id-format` 예제에서는 `AdminUser` AWS 계정의 IAM 사용자가 생성한 스냅샷에서 수신한 ID 형식을 설명합니다.  

```
aws ec2 describe-identity-id-format \
    --principal-arn arn:aws:iam::123456789012:user/AdminUser \
    --resource snapshot
```
출력은 이 사용자가 만든 스냅샷이 긴 ID 형식의 ID를 받는다는 것을 나타냅니다.  

```
{
    "Statuses": [
        {
            "Deadline": "2016-12-15T00:00:00Z",
            "Resource": "snapshot",
            "UseLongIds": true
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeIdentityIdFormat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-identity-id-format.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 역할에 대한 리소스 'image'의 ID 형식을 반환합니다.**  

```
Get-EC2IdentityIdFormat -PrincipalArn arn:aws:iam::123456789511:role/JDBC -Resource image
```
**출력:**  

```
Deadline             Resource UseLongIds
--------             -------- ----------
8/2/2018 11:30:00 PM image    True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeIdentityIdFormat](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 역할에 대한 리소스 'image'의 ID 형식을 반환합니다.**  

```
Get-EC2IdentityIdFormat -PrincipalArn arn:aws:iam::123456789511:role/JDBC -Resource image
```
**출력:**  

```
Deadline             Resource UseLongIds
--------             -------- ----------
8/2/2018 11:30:00 PM image    True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeIdentityIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeImageAttribute` 사용
<a name="example_ec2_DescribeImageAttribute_section"></a>

다음 코드 예시는 `DescribeImageAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**AMI의 시작 권한 설명**  
이 예시에서는 지정된 AMI에 대한 실행 권한을 설명합니다.  
명령:  

```
aws ec2 describe-image-attribute --image-id ami-5731123e --attribute launchPermission
```
출력:  

```
{
    "LaunchPermissions": [
        {
            "UserId": "123456789012"
        }
    ],
    "ImageId": "ami-5731123e",
}
```
**AMI의 제품 코드 설명**  
이 예시에서는 지정된 AMI의 제품 코드를 설명합니다. 이 AMI에는 제품 코드가 없습니다.  
명령:  

```
aws ec2 describe-image-attribute --image-id ami-5731123e --attribute productCodes
```
출력:  

```
{
    "ProductCodes": [],
    "ImageId": "ami-5731123e",
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeImageAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-image-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 AMI에 대한 설명을 가져옵니다.**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute description
```
**출력:**  

```
BlockDeviceMappings : {}
Description         : My image description
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**예제 2: 이 예제에서는 지정된 AMI에 대한 시작 권한을 가져옵니다.**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
**출력:**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {all}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**예제 3: 이 예제에서는 향상된 네트워킹이 활성화되어 있는지 테스트합니다.**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute sriovNetSupport
```
**출력:**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     : simple
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeImageAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 AMI에 대한 설명을 가져옵니다.**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute description
```
**출력:**  

```
BlockDeviceMappings : {}
Description         : My image description
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**예제 2: 이 예제에서는 지정된 AMI에 대한 시작 권한을 가져옵니다.**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
**출력:**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {all}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**예제 3: 이 예제에서는 향상된 네트워킹이 활성화되어 있는지 테스트합니다.**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute sriovNetSupport
```
**출력:**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     : simple
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeImages` 함께 사용
<a name="example_ec2_DescribeImages_section"></a>

다음 코드 예시는 `DescribeImages`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_describe_images
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) images.
#
# Parameters:
#       -i image_ids - A space-separated  list of image IDs (optional).
#       -h - Display help.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_images() {
  local image_ids response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_images"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) images."
    echo "  -i image_ids - A space-separated list of image IDs (optional)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) image_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local aws_cli_args=()

  if [[ -n "$image_ids" ]]; then
    # shellcheck disable=SC2206
    aws_cli_args+=("--image-ids" $image_ids)
  fi

  response=$(aws ec2 describe-images \
    "${aws_cli_args[@]}" \
    --query 'Images[*].[Description,Architecture,ImageId]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports describe-images operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeImages](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeImages)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: AMI를 설명하는 방법**  
다음 `describe-images` 예제에서는 지정된 리전에서 지정된 AMI를 설명합니다.  

```
aws ec2 describe-images \
    --region us-east-1 \
    --image-ids ami-1234567890EXAMPLE
```
출력:  

```
{
    "Images": [
        {
            "VirtualizationType": "hvm",
            "Description": "Provided by Red Hat, Inc.",
            "PlatformDetails": "Red Hat Enterprise Linux",
            "EnaSupport": true,
            "Hypervisor": "xen",
            "State": "available",
            "SriovNetSupport": "simple",
            "ImageId": "ami-1234567890EXAMPLE",
            "UsageOperation": "RunInstances:0010",
            "BlockDeviceMappings": [
                {
                    "DeviceName": "/dev/sda1",
                    "Ebs": {
                        "SnapshotId": "snap-111222333444aaabb",
                        "DeleteOnTermination": true,
                        "VolumeType": "gp2",
                        "VolumeSize": 10,
                        "Encrypted": false
                    }
                }
            ],
            "Architecture": "x86_64",
            "ImageLocation": "123456789012/RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2",
            "RootDeviceType": "ebs",
            "OwnerId": "123456789012",
            "RootDeviceName": "/dev/sda1",
            "CreationDate": "2019-05-10T13:17:12.000Z",
            "Public": true,
            "ImageType": "machine",
            "Name": "RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2"
        }
    ]
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [Amazon Machine Image(AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)를 참조하세요.  
**예제 2: 필터를 기반으로 AMI를 설명하는 방법**  
다음 `describe-images` 예제에서는 Amazon에서 제공하는 Amazon EBS 지원 Windows AMI를 설명합니다.  

```
aws ec2 describe-images \
    --owners amazon \
    --filters "Name=platform,Values=windows" "Name=root-device-type,Values=ebs"
```
`describe-images` 출력 예제는 예제 1을 참조하세요.  
필터를 사용하는 추가 예제는 *Amazon EC2 사용 설명서*에서 [리소스 나열 및 필터링](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)을 참조하세요.  
**예제 3: 태그를 기반으로 AMI를 설명하는 방법**  
다음 `describe-images` 예제에서는 `Type=Custom` 태그가 있는 모든 AMI를 설명합니다. 이 예제에서는 `--query` 파라미터를 사용하여 AMI ID만 표시합니다.  

```
aws ec2 describe-images \
    --filters "Name=tag:Type,Values=Custom" \
    --query 'Images[*].[ImageId]' \
    --output text
```
출력:  

```
ami-1234567890EXAMPLE
ami-0abcdef1234567890
```
태그 필터를 사용하는 추가 예제는 *Amazon EC2 사용 설명서*에서 [태그 작업](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-images.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, paginateDescribeImages } from "@aws-sdk/client-ec2";

/**
 * Describes the specified images (AMIs, AKIs, and ARIs) available to you or all of the images available to you.
 * @param {{ architecture: string, pageSize: number }} options
 */
export const main = async ({ architecture, pageSize }) => {
  pageSize = Number.parseInt(pageSize);
  const client = new EC2Client({});

  // The paginate function is a wrapper around the base command.
  const paginator = paginateDescribeImages(
    // Without limiting the page size, this call can take a long time. pageSize is just sugar for
    // the MaxResults property in the base command.
    { client, pageSize },
    {
      // There are almost 70,000 images available. Be specific with your filtering
      // to increase efficiency.
      // See https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-ec2/interfaces/describeimagescommandinput.html#filters
      Filters: [{ Name: "architecture", Values: [architecture] }],
    },
  );

  /**
   * @type {import('@aws-sdk/client-ec2').Image[]}
   */
  const images = [];
  let recordsScanned = 0;

  try {
    for await (const page of paginator) {
      recordsScanned += pageSize;
      if (page.Images.length) {
        images.push(...page.Images);
        break;
      }
      console.log(
        `No matching image found yet. Searched ${recordsScanned} records.`,
      );
    }

    if (images.length) {
      console.log(
        `Found ${images.length} images:\n\n${images.map((image) => image.Name).join("\n")}\n`,
      );
    } else {
      console.log(
        `No matching images found. Searched ${recordsScanned} records.\n`,
      );
    }

    return images;
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}`);
      return [];
    }
    throw caught;
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DescribeImages](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeImagesCommand)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 AMI를 설명합니다.**  

```
Get-EC2Image -ImageId ami-12345678
```
**출력:**  

```
Architecture        : x86_64
BlockDeviceMappings : {/dev/xvda}
CreationDate        : 2014-10-20T00:56:28.000Z
Description         : My image
Hypervisor          : xen
ImageId             : ami-12345678
ImageLocation       : 123456789012/my-image
ImageOwnerAlias     :
ImageType           : machine
KernelId            :
Name                : my-image
OwnerId             : 123456789012
Platform            :
ProductCodes        : {}
Public              : False
RamdiskId           :
RootDeviceName      : /dev/xvda
RootDeviceType      : ebs
SriovNetSupport     : simple
State               : available
StateReason         :
Tags                : {Name}
VirtualizationType  : hvm
```
**예제 2: 이 예제에서는 사용자가 소유한 AMI를 설명합니다.**  

```
Get-EC2Image -owner self
```
**예제 3: 이 예제에서는 Microsoft Windows Server를 실행하는 퍼블릭 AMI를 설명합니다.**  

```
Get-EC2Image -Filter @{ Name="platform"; Values="windows" }
```
**예제 4: 이 예제에서는 'us-west-2' 리전의 모든 퍼블릭 AMI를 설명합니다.**  

```
Get-EC2Image -Region us-west-2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeImages](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 AMI를 설명합니다.**  

```
Get-EC2Image -ImageId ami-12345678
```
**출력:**  

```
Architecture        : x86_64
BlockDeviceMappings : {/dev/xvda}
CreationDate        : 2014-10-20T00:56:28.000Z
Description         : My image
Hypervisor          : xen
ImageId             : ami-12345678
ImageLocation       : 123456789012/my-image
ImageOwnerAlias     :
ImageType           : machine
KernelId            :
Name                : my-image
OwnerId             : 123456789012
Platform            :
ProductCodes        : {}
Public              : False
RamdiskId           :
RootDeviceName      : /dev/xvda
RootDeviceType      : ebs
SriovNetSupport     : simple
State               : available
StateReason         :
Tags                : {Name}
VirtualizationType  : hvm
```
**예제 2: 이 예제에서는 사용자가 소유한 AMI를 설명합니다.**  

```
Get-EC2Image -owner self
```
**예제 3: 이 예제에서는 Microsoft Windows Server를 실행하는 퍼블릭 AMI를 설명합니다.**  

```
Get-EC2Image -Filter @{ Name="platform"; Values="windows" }
```
**예제 4: 이 예제에서는 'us-west-2' 리전의 모든 퍼블릭 AMI를 설명합니다.**  

```
Get-EC2Image -Region us-west-2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeImages](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def get_images(self, image_ids: List[str]) -> List[Dict[str, Any]]:
        """
        Gets information about Amazon Machine Images (AMIs) from a list of AMI IDs.

        :param image_ids: The list of AMI IDs to look up.
        :return: A list of dictionaries representing the requested AMIs.
        """
        try:
            response = self.ec2_client.describe_images(ImageIds=image_ids)
            images = response["Images"]
        except ClientError as err:
            logger.error(f"Failed to stop AMI(s): {','.join(map(str, image_ids))}")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAMIID.NotFound":
                logger.error("One or more of the AMI IDs does not exist.")
            raise
        return images
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeImages](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeImages)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn list_images(&self, ids: Vec<Parameter>) -> Result<Vec<Image>, EC2Error> {
        let image_ids = ids.into_iter().filter_map(|p| p.value).collect();
        let output = self
            .client
            .describe_images()
            .set_image_ids(Some(image_ids))
            .send()
            .await?;

        let images = output.images.unwrap_or_default();
        if images.is_empty() {
            Err(EC2Error::new("No images for selected AMIs"))
        } else {
            Ok(images)
        }
    }
```
list\$1images 함수를 SSM과 함께 사용하여 환경에 맞게 제한합니다. SSM에 대한 자세한 내용은 https://docs.aws.amazon.com/systems-manager/latest/userguide/example\$1ssm\$1GetParameters\$1section.html 페이지를 참조하세요.  

```
    async fn find_image(&mut self) -> Result<ScenarioImage, EC2Error> {
        let params: Vec<Parameter> = self
            .ssm
            .list_path("/aws/service/ami-amazon-linux-latest")
            .await
            .map_err(|e| e.add_message("Could not find parameters for available images"))?
            .into_iter()
            .filter(|param| param.name().is_some_and(|name| name.contains("amzn2")))
            .collect();
        let amzn2_images: Vec<ScenarioImage> = self
            .ec2
            .list_images(params)
            .await
            .map_err(|e| e.add_message("Could not find images"))?
            .into_iter()
            .map(ScenarioImage::from)
            .collect();
        println!("We will now create an instance from an Amazon Linux 2 AMI");
        let ami = self.util.select_scenario_image(amzn2_images)?;
        Ok(ami)
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DescribeImages](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_images)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->describeimages( it_imageids = it_image_ids ).             " oo_result is returned for testing purposes. "
        DATA(lt_images) = oo_result->get_images( ).
        MESSAGE 'Retrieved information about Amazon Machine Images (AMIs).' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DescribeImages](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Return an array of `EC2ClientTypes.Image` objects describing all of
    /// the images in the specified array.
    /// 
    /// - Parameter idList: A list of image ID strings indicating the images
    ///   to return details about.
    ///
    /// - Returns: An array of the images.
    func describeImages(_ idList: [String]) async -> [EC2ClientTypes.Image] {
        do {
            let output = try await ec2Client.describeImages(
                input: DescribeImagesInput(
                    imageIds: idList
                )
            )

            guard let images = output.images else {
                print("*** No images found.")
                return []
            }

            for image in images {
                guard let id = image.imageId else {
                    continue
                }
                print("   \(id): \(image.description ?? "<no description>")")
            }

            return images
        } catch {
            print("*** Error getting image descriptions: \(error.localizedDescription)")
            return []
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DescribeImages](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describeimages(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeImportImageTasks` 사용
<a name="example_ec2_DescribeImportImageTasks_section"></a>

다음 코드 예시는 `DescribeImportImageTasks`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**이미지 가져오기 태스크 모니터링**  
다음 `describe-import-image-tasks` 예시에서는 지정된 가져오기 이미지 태스크의 상태를 확인합니다.  

```
aws ec2 describe-import-image-tasks \
    --import-task-ids import-ami-1234567890abcdef0
```
진행 중인 이미지 내보내기 작업의 출력입니다.  

```
{
    "ImportImageTasks": [
        {
            "ImportTaskId": "import-ami-1234567890abcdef0",
            "Progress": "28",
            "SnapshotDetails": [
                {
                    "DiskImageSize": 705638400.0,
                    "Format": "ova",
                    "Status": "completed",
                    "UserBucket": {
                        "S3Bucket": "my-import-bucket",
                        "S3Key": "vms/my-server-vm.ova"
                    }
                }
            ],
            "Status": "active",
            "StatusMessage": "converting"
        }
    ]
}
```
완료된 이미지 내보내기 작업의 출력입니다. 결과 AMI의 ID는 `ImageId`에서 제공합니다.  

```
{
    "ImportImageTasks": [
        {
            "ImportTaskId": "import-ami-1234567890abcdef0",
            "ImageId": "ami-1234567890abcdef0",
            "SnapshotDetails": [
                {
                    "DiskImageSize": 705638400.0,
                    "Format": "ova",
                    "SnapshotId": "snap-1234567890abcdef0"
                    "Status": "completed",
                    "UserBucket": {
                        "S3Bucket": "my-import-bucket",
                        "S3Key": "vms/my-server-vm.ova"
                    }
                }
            ],
            "Status": "completed"
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeImportImageTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-import-image-tasks.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 이미지 가져오기 작업을 설명합니다.**  

```
Get-EC2ImportImageTask -ImportTaskId import-ami-hgfedcba
```
**출력:**  

```
Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
**예제 2: 이 예제에서는 모든 이미지 가져오기 작업을 설명합니다.**  

```
Get-EC2ImportImageTask
```
**출력:**  

```
Architecture    :
Description     : Windows Image 1
Hypervisor      :
ImageId         :
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {}
Status          : deleted
StatusMessage   : User initiated task cancelation

Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeImportImageTasks](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 이미지 가져오기 작업을 설명합니다.**  

```
Get-EC2ImportImageTask -ImportTaskId import-ami-hgfedcba
```
**출력:**  

```
Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
**예제 2: 이 예제에서는 모든 이미지 가져오기 작업을 설명합니다.**  

```
Get-EC2ImportImageTask
```
**출력:**  

```
Architecture    :
Description     : Windows Image 1
Hypervisor      :
ImageId         :
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {}
Status          : deleted
StatusMessage   : User initiated task cancelation

Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeImportImageTasks](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeImportSnapshotTasks` 사용
<a name="example_ec2_DescribeImportSnapshotTasks_section"></a>

다음 코드 예시는 `DescribeImportSnapshotTasks`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스냅샷 가져오기 태스크 모니터링**  
다음 `describe-import-snapshot-tasks` 예시에서는 지정된 가져오기 스냅샷 태스크의 상태를 확인합니다.  

```
aws ec2 describe-import-snapshot-tasks \
    --import-task-ids import-snap-1234567890abcdef0
```
진행 중인 스냅샷 가져오기 작업의 출력:  

```
{
    "ImportSnapshotTasks": [
        {
            "Description": "My server VMDK",
            "ImportTaskId": "import-snap-1234567890abcdef0",
            "SnapshotTaskDetail": {
                "Description": "My server VMDK",
                "DiskImageSize": "705638400.0",
                "Format": "VMDK",
                "Progress": "42",
                "Status": "active",
                "StatusMessage": "downloading/converting",
                "UserBucket": {
                    "S3Bucket": "my-import-bucket",
                    "S3Key": "vms/my-server-vm.vmdk"
                }
            }
        }
    ]
}
```
완료된 스냅샷 가져오기 작업의 출력: 결과 스냅샷의 ID는 `SnapshotId`에서 제공합니다.  

```
{
    "ImportSnapshotTasks": [
        {
            "Description": "My server VMDK",
            "ImportTaskId": "import-snap-1234567890abcdef0",
            "SnapshotTaskDetail": {
                "Description": "My server VMDK",
                "DiskImageSize": "705638400.0",
                "Format": "VMDK",
                "SnapshotId": "snap-1234567890abcdef0"
                "Status": "completed",
                "UserBucket": {
                    "S3Bucket": "my-import-bucket",
                    "S3Key": "vms/my-server-vm.vmdk"
                }
            }
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeImportSnapshotTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-import-snapshot-tasks.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스냅샷 가져오기 작업을 설명합니다.**  

```
Get-EC2ImportSnapshotTask -ImportTaskId import-snap-abcdefgh
```
**출력:**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
**예제 2: 이 예제에서는 모든 스냅샷 가져오기 작업을 설명합니다.**  

```
Get-EC2ImportSnapshotTask
```
**출력:**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail 
Disk Image Import 2     import-snap-hgfedcba       Amazon.EC2.Model.SnapshotTaskDetail
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeImportSnapshotTasks](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스냅샷 가져오기 작업을 설명합니다.**  

```
Get-EC2ImportSnapshotTask -ImportTaskId import-snap-abcdefgh
```
**출력:**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
**예제 2: 이 예제에서는 모든 스냅샷 가져오기 작업을 설명합니다.**  

```
Get-EC2ImportSnapshotTask
```
**출력:**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail 
Disk Image Import 2     import-snap-hgfedcba       Amazon.EC2.Model.SnapshotTaskDetail
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeImportSnapshotTasks](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeInstanceAttribute` 사용
<a name="example_ec2_DescribeInstanceAttribute_section"></a>

다음 코드 예시는 `DescribeInstanceAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스 유형 설명**  
이 예시에서는 지정된 인스턴스의 인스턴스 유형을 설명합니다.  
명령:  

```
aws ec2 describe-instance-attribute --instance-id i-1234567890abcdef0 --attribute instanceType
```
출력:  

```
{
    "InstanceId": "i-1234567890abcdef0"
    "InstanceType": {
        "Value": "t1.micro"
    }
}
```
**disableApiTermination 속성 설명**  
이 예시에서는 지정된 인스턴스의 `disableApiTermination` 속성을 설명합니다.  
명령:  

```
aws ec2 describe-instance-attribute --instance-id i-1234567890abcdef0 --attribute disableApiTermination
```
출력:  

```
{
"InstanceId": "i-1234567890abcdef0"
    "DisableApiTermination": {
        "Value": "false"
    }
}
```
**인스턴스의 블록 디바이스 매핑 설명**  
이 예시에서는 지정된 인스턴스의 `blockDeviceMapping` 속성을 설명합니다.  
명령:  

```
aws ec2 describe-instance-attribute --instance-id i-1234567890abcdef0 --attribute blockDeviceMapping
```
출력:  

```
{
    "InstanceId": "i-1234567890abcdef0"
    "BlockDeviceMappings": [
        {
            "DeviceName": "/dev/sda1",
            "Ebs": {
                "Status": "attached",
                "DeleteOnTermination": true,
                "VolumeId": "vol-049df61146c4d7901",
                "AttachTime": "2013-05-17T22:42:34.000Z"
            }
        },
        {
            "DeviceName": "/dev/sdf",
            "Ebs": {
                "Status": "attached",
                "DeleteOnTermination": false,
                "VolumeId": "vol-049df61146c4d7901",
                "AttachTime": "2013-09-10T23:07:00.000Z"
            }
        }
    ],
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeInstanceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스의 인스턴스 유형을 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceType
```
**출력:**  

```
InstanceType                      : t2.micro
```
**예제 2: 이 예제에서는 지정된 인스턴스에 대해 향상된 네트워킹이 활성화되었는지 여부를 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**출력:**  

```
SriovNetSupport                   : simple
```
**예제 3: 이 예제에서는 지정된 인스턴스의 보안 그룹을 설명합니다.**  

```
(Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute groupSet).Groups
```
**출력:**  

```
GroupId
-------
sg-12345678
sg-45678901
```
**예제 4: 이 예제에서는 지정된 인스턴스에 대해 EBS 최적화가 활성화되었는지 여부를 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**출력:**  

```
EbsOptimized                      : False
```
**예제 5: 이 예제에서는 지정된 인스턴스의 'disableApiTermination' 속성을 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**출력:**  

```
DisableApiTermination             : False
```
**예제 6: 이 예제에서는 지정된 인스턴스의 'instanceInitiatedShutdownBehavior' 속성을 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
**출력:**  

```
InstanceInitiatedShutdownBehavior : stop
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeInstanceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스의 인스턴스 유형을 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceType
```
**출력:**  

```
InstanceType                      : t2.micro
```
**예제 2: 이 예제에서는 지정된 인스턴스에 대해 향상된 네트워킹이 활성화되었는지 여부를 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**출력:**  

```
SriovNetSupport                   : simple
```
**예제 3: 이 예제에서는 지정된 인스턴스의 보안 그룹을 설명합니다.**  

```
(Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute groupSet).Groups
```
**출력:**  

```
GroupId
-------
sg-12345678
sg-45678901
```
**예제 4: 이 예제에서는 지정된 인스턴스에 대해 EBS 최적화가 활성화되었는지 여부를 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**출력:**  

```
EbsOptimized                      : False
```
**예제 5: 이 예제에서는 지정된 인스턴스의 'disableApiTermination' 속성을 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**출력:**  

```
DisableApiTermination             : False
```
**예제 6: 이 예제에서는 지정된 인스턴스의 'instanceInitiatedShutdownBehavior' 속성을 설명합니다.**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
**출력:**  

```
InstanceInitiatedShutdownBehavior : stop
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeInstanceStatus` 함께 사용
<a name="example_ec2_DescribeInstanceStatus_section"></a>

다음 코드 예시는 `DescribeInstanceStatus`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스 상태를 설명하는 방법**  
다음 `describe-instance-status` 예제에서는 지정된 인스턴스의 현재 상태를 설명합니다.  

```
aws ec2 describe-instance-status \
    --instance-ids i-1234567890abcdef0
```
출력:  

```
{
    "InstanceStatuses": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "InstanceState": {
                "Code": 16,
                "Name": "running"
            },
            "AvailabilityZone": "us-east-1d",
            "SystemStatus": {
                "Status": "ok",
                "Details": [
                    {
                        "Status": "passed",
                        "Name": "reachability"
                    }
                ]
            },
            "InstanceStatus": {
                "Status": "ok",
                "Details": [
                    {
                        "Status": "passed",
                        "Name": "reachability"
                    }
                ]
            }
        }
    ]
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [인스턴스 상태 모니터링](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeInstanceStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-status.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스의 상태를 설명합니다.**  

```
Get-EC2InstanceStatus -InstanceId i-12345678
```
**출력:**  

```
AvailabilityZone : us-west-2a
Events           : {}
InstanceId       : i-12345678
InstanceState    : Amazon.EC2.Model.InstanceState
Status           : Amazon.EC2.Model.InstanceStatusSummary
SystemStatus     : Amazon.EC2.Model.InstanceStatusSummary
```

```
$status = Get-EC2InstanceStatus -InstanceId i-12345678
$status.InstanceState
```
**출력:**  

```
Code    Name
----    ----
16      running
```

```
$status.Status
```
**출력:**  

```
Details           Status
-------           ------
{reachability}    ok
```

```
$status.SystemStatus
```
**출력:**  

```
Details           Status
-------           ------
{reachability}    ok
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeInstanceStatus](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스의 상태를 설명합니다.**  

```
Get-EC2InstanceStatus -InstanceId i-12345678
```
**출력:**  

```
AvailabilityZone : us-west-2a
Events           : {}
InstanceId       : i-12345678
InstanceState    : Amazon.EC2.Model.InstanceState
Status           : Amazon.EC2.Model.InstanceStatusSummary
SystemStatus     : Amazon.EC2.Model.InstanceStatusSummary
```

```
$status = Get-EC2InstanceStatus -InstanceId i-12345678
$status.InstanceState
```
**출력:**  

```
Code    Name
----    ----
16      running
```

```
$status.Status
```
**출력:**  

```
Details           Status
-------           ------
{reachability}    ok
```

```
$status.SystemStatus
```
**출력:**  

```
Details           Status
-------           ------
{reachability}    ok
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeInstanceStatus](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
async fn show_all_events(client: &Client) -> Result<(), Error> {
    let resp = client.describe_regions().send().await.unwrap();

    for region in resp.regions.unwrap_or_default() {
        let reg: &'static str = Box::leak(Box::from(region.region_name().unwrap()));
        let region_provider = RegionProviderChain::default_provider().or_else(reg);
        let config = aws_config::from_env().region(region_provider).load().await;
        let new_client = Client::new(&config);

        let resp = new_client.describe_instance_status().send().await;

        println!("Instances in region {}:", reg);
        println!();

        for status in resp.unwrap().instance_statuses() {
            println!(
                "  Events scheduled for instance ID: {}",
                status.instance_id().unwrap_or_default()
            );
            for event in status.events() {
                println!("    Event ID:     {}", event.instance_event_id().unwrap());
                println!("    Description:  {}", event.description().unwrap());
                println!("    Event code:   {}", event.code().unwrap().as_ref());
                println!();
            }
        }
    }

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DescribeInstanceStatus](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_instance_status)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeInstanceTypes` 함께 사용
<a name="example_ec2_DescribeInstanceTypes_section"></a>

다음 코드 예시는 `DescribeInstanceTypes`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Describe the instance types available.
    /// </summary>
    /// <returns>A list of instance type information.</returns>
    public async Task<List<InstanceTypeInfo>> DescribeInstanceTypes(ArchitectureValues architecture)
    {
        try
        {
            var request = new DescribeInstanceTypesRequest();

            var filters = new List<Filter>
            {
                new Filter("processor-info.supported-architecture",
                    new List<string> { architecture.ToString() })
            };
            filters.Add(new Filter("instance-type", new() { "*.micro", "*.small" }));

            request.Filters = filters;
            var instanceTypes = new List<InstanceTypeInfo>();

            var paginator = _amazonEC2.Paginators.DescribeInstanceTypes(request);
            await foreach (var instanceType in paginator.InstanceTypes)
            {
                instanceTypes.Add(instanceType);
            }

            return instanceTypes;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidParameterValue")
            {
                _logger.LogError(
                    $"Parameters are invalid. Ensure architecture and size strings conform to DescribeInstanceTypes API reference.");
            }

            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete the security group because: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DescribeInstanceTypes](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstanceTypes)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# ec2_describe_instance_types
#
# This function describes EC2 instance types filtered by processor architecture
# and optionally by instance type. It takes the following arguments:
#
# -a, --architecture ARCHITECTURE  Specify the processor architecture (e.g., x86_64)
# -t, --type INSTANCE_TYPE         Comma-separated list of instance types (e.g., t2.micro)
# -h, --help                       Show the usage help
#
# The function prints the instance type and supported architecture for each
# matching instance type.
###############################################################################
function ec2_describe_instance_types() {
  local architecture=""
  local instance_types=""

  # bashsupport disable=BP5008
  function usage() {
    echo "Usage: ec2_describe_instance_types [-a|--architecture ARCHITECTURE] [-t|--type INSTANCE_TYPE] [-h|--help]"
    echo "  -a, --architecture ARCHITECTURE  Specify the processor architecture (e.g., x86_64)"
    echo "  -t, --type INSTANCE_TYPE         Comma-separated list of instance types (e.g., t2.micro)"
    echo "  -h, --help                       Show this help message"
  }

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -a | --architecture)
        architecture="$2"
        shift 2
        ;;
      -t | --type)
        instance_types="$2"
        shift 2
        ;;
      -h | --help)
        usage
        return 0
        ;;
      *)
        echo "Unknown argument: $1"
        return 1
        ;;
    esac
  done

  if [[ -z "$architecture" ]]; then
    errecho "Error: Architecture not specified."
    usage
    return 1
  fi

  if [[ -z "$instance_types" ]]; then
    errecho "Error: Instance type not specified."
    usage
    return 1
  fi

  local tmp_json_file="temp_ec2.json"
  echo -n '[
    {
      "Name": "processor-info.supported-architecture",
      "Values": [' >"$tmp_json_file"

  local items
  IFS=',' read -ra items <<<"$architecture"
  local array_size
  array_size=${#items[@]}
  for i in $(seq 0 $((array_size - 1))); do
    echo -n '"'"${items[$i]}"'"' >>"$tmp_json_file"
    if [[ $i -lt $((array_size - 1)) ]]; then
      echo -n ',' >>"$tmp_json_file"
    fi
  done
  echo -n ']},
    {
    "Name": "instance-type",
      "Values": [' >>"$tmp_json_file"
  IFS=',' read -ra items <<<"$instance_types"
  local array_size
  array_size=${#items[@]}
  for i in $(seq 0 $((array_size - 1))); do
    echo -n '"'"${items[$i]}"'"' >>"$tmp_json_file"
    if [[ $i -lt $((array_size - 1)) ]]; then
      echo -n ',' >>"$tmp_json_file"
    fi
  done

  echo -n ']}]' >>"$tmp_json_file"

  local response
  response=$(aws ec2 describe-instance-types --filters file://"$tmp_json_file" \
    --query 'InstanceTypes[*].[InstanceType]' --output text)

  local error_code=$?

  rm "$tmp_json_file"

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    echo "ERROR: AWS reports describe-instance-types operation failed."
    return 1
  fi

  echo "$response"
  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeInstanceTypes](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeInstanceTypes)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 인스턴스 유형을 설명하는 방법**  
다음 `describe-instance-types` 예제에서는 지정된 인스턴스 유형의 세부 정보를 표시합니다.  

```
aws ec2 describe-instance-types \
    --instance-types t2.micro
```
출력:  

```
{
    "InstanceTypes": [
        {
            "InstanceType": "t2.micro",
            "CurrentGeneration": true,
            "FreeTierEligible": true,
            "SupportedUsageClasses": [
                "on-demand",
                "spot"
            ],
            "SupportedRootDeviceTypes": [
                "ebs"
            ],
            "BareMetal": false,
            "Hypervisor": "xen",
            "ProcessorInfo": {
                "SupportedArchitectures": [
                    "i386",
                    "x86_64"
                ],
                "SustainedClockSpeedInGhz": 2.5
            },
            "VCpuInfo": {
                "DefaultVCpus": 1,
                "DefaultCores": 1,
                "DefaultThreadsPerCore": 1,
                "ValidCores": [
                    1
                ],
                "ValidThreadsPerCore": [
                    1
                ]
            },
            "MemoryInfo": {
                "SizeInMiB": 1024
            },
            "InstanceStorageSupported": false,
            "EbsInfo": {
                "EbsOptimizedSupport": "unsupported",
                "EncryptionSupport": "supported"
            },
            "NetworkInfo": {
                "NetworkPerformance": "Low to Moderate",
                "MaximumNetworkInterfaces": 2,
                "Ipv4AddressesPerInterface": 2,
                "Ipv6AddressesPerInterface": 2,
                "Ipv6Supported": true,
                "EnaSupport": "unsupported"
            },
            "PlacementGroupInfo": {
                "SupportedStrategies": [
                    "partition",
                    "spread"
                ]
            },
            "HibernationSupported": false,
            "BurstablePerformanceSupported": true,
            "DedicatedHostsSupported": false,
            "AutoRecoverySupported": true
        }
    ]
}
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*의 [인스턴스 유형](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html)을 참조하세요.  
**예제 2: 사용 가능한 인스턴스 유형을 필터링하는 방법**  
필터를 지정하여 결과 범위를 특정 특성의 인스턴스 유형으로 지정할 수 있습니다. 다음 `describe-instance-types` 예제에서는 최대 절전 모드를 지원하는 인스턴스 유형을 나열합니다.  

```
aws ec2 describe-instance-types \
    --filters Name=hibernation-supported,Values=true --query 'InstanceTypes[*].InstanceType'
```
출력:  

```
[
    "m5.8xlarge",
    "r3.large",
    "c3.8xlarge",
    "r5.large",
    "m4.4xlarge",
    "c4.large",
    "m5.xlarge",
    "m4.xlarge",
    "c3.large",
    "c4.8xlarge",
    "c4.4xlarge",
    "c5.xlarge",
    "c5.12xlarge",
    "r5.4xlarge",
    "c5.4xlarge"
]
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*의 [인스턴스 유형](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeInstanceTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-types.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Asynchronously retrieves the instance types available in the current AWS region.
     * <p>
     * This method uses the AWS SDK's asynchronous API to fetch the available instance types
     * and then processes the response. It logs the memory information, network information,
     * and instance type for each instance type returned. Additionally, it returns a
     * {@link CompletableFuture} that resolves to the instance type string for the "t2.2xlarge"
     * instance type, if it is found in the response. If the "t2.2xlarge" instance type is not
     * found, an empty string is returned.
     * </p>
     *
     * @return a {@link CompletableFuture} that resolves to the instance type string for the
     * "t2.2xlarge" instance type, or an empty string if the instance type is not found
     */
    public CompletableFuture<String> getInstanceTypesAsync() {
        DescribeInstanceTypesRequest typesRequest = DescribeInstanceTypesRequest.builder()
            .maxResults(10)
            .build();

        CompletableFuture<DescribeInstanceTypesResponse> response = getAsyncClient().describeInstanceTypes(typesRequest);
        response.whenComplete((resp, ex) -> {
            if (resp != null) {
                List<InstanceTypeInfo> instanceTypes = resp.instanceTypes();
                for (InstanceTypeInfo type : instanceTypes) {
                    logger.info("The memory information of this type is " + type.memoryInfo().sizeInMiB());
                    logger.info("Network information is " + type.networkInfo().toString());
                    logger.info("Instance type is " + type.instanceType().toString());
                }
            } else {
                throw (RuntimeException) ex;
            }
        });

        return response.thenApply(resp -> {
            for (InstanceTypeInfo type : resp.instanceTypes()) {
                String instanceType = type.instanceType().toString();
                if (instanceType.equals("t2.2xlarge")) {
                    return instanceType;
                }
            }
            return "";
        });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DescribeInstanceTypes](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstanceTypes)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, paginateDescribeInstanceTypes } from "@aws-sdk/client-ec2";

/**
 * Describes the specified instance types. By default, all instance types for the
 * current Region are described. Alternatively, you can filter the results.
 * @param {{ pageSize: string, supportedArch: string[], freeTier: boolean }} options
 */
export const main = async ({ pageSize, supportedArch, freeTier }) => {
  pageSize = Number.parseInt(pageSize);
  const client = new EC2Client({});

  // The paginate function is a wrapper around the underlying command.
  const paginator = paginateDescribeInstanceTypes(
    // Without limiting the page size, this call can take a long time. pageSize is just sugar for
    // the MaxResults property in the underlying command.
    { client, pageSize },
    {
      Filters: [
        {
          Name: "processor-info.supported-architecture",
          Values: supportedArch,
        },
        { Name: "free-tier-eligible", Values: [freeTier ? "true" : "false"] },
      ],
    },
  );

  try {
    /**
     * @type {import('@aws-sdk/client-ec2').InstanceTypeInfo[]}
     */
    const instanceTypes = [];

    for await (const page of paginator) {
      if (page.InstanceTypes.length) {
        instanceTypes.push(...page.InstanceTypes);

        // When we have at least 1 result, we can stop.
        if (instanceTypes.length >= 1) {
          break;
        }
      }
    }
    console.log(
      `Memory size in MiB for matching instance types:\n\n${instanceTypes.map((it) => `${it.InstanceType}: ${it.MemoryInfo.SizeInMiB} MiB`).join("\n")}`,
    );
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}`);
      return [];
    }
    throw caught;
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DescribeInstanceTypes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstanceTypesCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
// Get a list of instance types.
suspend fun getInstanceTypesSc(): String {
    var instanceType = ""
    val filterObs = ArrayList<Filter>()
    val filter =
        Filter {
            name = "processor-info.supported-architecture"
            values = listOf("arm64")
        }

    filterObs.add(filter)
    val typesRequest =
        DescribeInstanceTypesRequest {
            filters = filterObs
            maxResults = 10
        }
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeInstanceTypes(typesRequest)
        response.instanceTypes?.forEach { type ->
            println("The memory information of this type is ${type.memoryInfo?.sizeInMib}")
            println("Maximum number of network cards is ${type.networkInfo?.maximumNetworkCards}")
            instanceType = type.instanceType.toString()
        }
        return instanceType
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DescribeInstanceTypes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하십시오.

------
#### [ Python ]

**SDK for Python (Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def get_instance_types(
        self, architecture: str = "x86_64", sizes: List[str] = ["*.micro", "*.small"]
    ) -> List[Dict[str, Any]]:
        """
        Gets instance types that support the specified architecture and size.
        See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstanceTypes.html
        for a list of allowable parameters.

        :param architecture: The architecture supported by instance types. Default: 'x86_64'.
        :param sizes: The size of instance types. Default: '*.micro', '*.small',
        :return: A list of dictionaries representing instance types that support the specified architecture and size.
        """
        try:
            inst_types = []
            paginator = self.ec2_client.get_paginator("describe_instance_types")
            for page in paginator.paginate(
                Filters=[
                    {
                        "Name": "processor-info.supported-architecture",
                        "Values": [architecture],
                    },
                    {"Name": "instance-type", "Values": sizes},
                ]
            ):
                inst_types += page["InstanceTypes"]
        except ClientError as err:
            logger.error(
                f"Failed to get instance types: {architecture}, {','.join(map(str, sizes))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidParameterValue":
                logger.error(
                    "Parameters are invalid. "
                    "Ensure architecture and size strings conform to DescribeInstanceTypes API reference."
                )
            raise
        else:
            return inst_types
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeInstanceTypes](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstanceTypes)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// List instance types that match an image's architecture and are free tier eligible.
    pub async fn list_instance_types(&self, image: &Image) -> Result<Vec<InstanceType>, EC2Error> {
        let architecture = format!(
            "{}",
            image.architecture().ok_or_else(|| EC2Error::new(format!(
                "Image {:?} does not have a listed architecture",
                image.image_id()
            )))?
        );
        let free_tier_eligible_filter = Filter::builder()
            .name("free-tier-eligible")
            .values("false")
            .build();
        let supported_architecture_filter = Filter::builder()
            .name("processor-info.supported-architecture")
            .values(architecture)
            .build();
        let response = self
            .client
            .describe_instance_types()
            .filters(free_tier_eligible_filter)
            .filters(supported_architecture_filter)
            .send()
            .await?;

        Ok(response
            .instance_types
            .unwrap_or_default()
            .into_iter()
            .filter_map(|iti| iti.instance_type)
            .collect())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DescribeInstanceTypes](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_instance_types)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    " Create filters for architecture and instance type patterns
    " iv_architecture = 'x86_64'
    DATA lt_filters TYPE /aws1/cl_ec2filter=>tt_filterlist.
    APPEND NEW /aws1/cl_ec2filter(
      iv_name = 'processor-info.supported-architecture'
      it_values = VALUE /aws1/cl_ec2valuestringlist_w=>tt_valuestringlist(
        ( NEW /aws1/cl_ec2valuestringlist_w( iv_architecture ) )
      )
    ) TO lt_filters.
    " Filter for instance type patterns like '*.micro', '*.small'
    APPEND NEW /aws1/cl_ec2filter(
      iv_name = 'instance-type'
      it_values = VALUE /aws1/cl_ec2valuestringlist_w=>tt_valuestringlist(
        ( NEW /aws1/cl_ec2valuestringlist_w( '*.micro' ) )
        ( NEW /aws1/cl_ec2valuestringlist_w( '*.small' ) )
      )
    ) TO lt_filters.

    TRY.
        oo_result = lo_ec2->describeinstancetypes( it_filters = lt_filters ).             " oo_result is returned for testing purposes. "
        DATA(lt_instance_types) = oo_result->get_instancetypes( ).
        MESSAGE 'Retrieved information about EC2 instance types.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조의* [DescribeInstanceTypes](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html).

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Return a list of instance types matching the specified architecture
    /// and instance sizes.
    /// 
    /// - Parameters:
    ///   - architecture: The architecture of the instance types to return, as
    ///     a member of `EC2ClientTypes.ArchitectureValues`.
    ///   - sizes: An array of one or more strings identifying sizes of
    ///     instance type to accept.
    /// 
    /// - Returns: An array of `EC2ClientTypes.InstanceTypeInfo` records
    ///   describing the instance types matching the given requirements.
    func getMatchingInstanceTypes(architecture: EC2ClientTypes.ArchitectureValues = EC2ClientTypes.ArchitectureValues.x8664,
                          sizes: [String] = ["*.micro", "*.small"]) async
                          -> [EC2ClientTypes.InstanceTypeInfo] {
        var instanceTypes: [EC2ClientTypes.InstanceTypeInfo] = []    

        let archFilter = EC2ClientTypes.Filter(
            name: "processor-info.supported-architecture",
            values: [architecture.rawValue]
        )
        let sizeFilter = EC2ClientTypes.Filter(
            name: "instance-type",
            values: sizes
        )

        do {
            let pages = ec2Client.describeInstanceTypesPaginated(
                input: DescribeInstanceTypesInput(
                    filters: [archFilter, sizeFilter]
                )
            )

            for try await page in pages {
                guard let types = page.instanceTypes else {
                    return []
                }

                instanceTypes += types
            }
        } catch {
            print("*** Error getting image types: \(error.localizedDescription)")
            return []
        }

        return instanceTypes
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DescribeInstanceTypes](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describeinstancetypes(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeInstances` 함께 사용
<a name="example_ec2_DescribeInstances_section"></a>

다음 코드 예시는 `DescribeInstances`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [복원력이 뛰어난 서비스 구축 및 관리](example_cross_ResilientService_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Get information about EC2 instances with a particular state.
    /// </summary>
    /// <param name="tagName">The name of the tag to filter on.</param>
    /// <param name="tagValue">The value of the tag to look for.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> GetInstancesWithState(string state)
    {
        try
        {
            // Filters the results of the instance list.
            var filters = new List<Filter>
            {
                new Filter
                {
                    Name = $"instance-state-name",
                    Values = new List<string> { state, },
                },
            };
            var request = new DescribeInstancesRequest { Filters = filters, };

            Console.WriteLine($"\nShowing instances with state {state}");
            var paginator = _amazonEC2.Paginators.DescribeInstances(request);

            await foreach (var response in paginator.Responses)
            {
                foreach (var reservation in response.Reservations)
                {
                    foreach (var instance in reservation.Instances)
                    {
                        Console.Write($"Instance ID: {instance.InstanceId} ");
                        Console.WriteLine($"\tCurrent State: {instance.State.Name}");
                    }
                }
            }

            return true;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidParameterValue")
            {
                _logger.LogError(
                    $"Invalid parameter value for filtering instances.");
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't list instances because: {ex.Message}");
            return false;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DescribeInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstances) 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_describe_instances
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i instance_id - The ID of the instance to describe (optional).
#       -q query - The query to filter the response (optional).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_instances() {
  local instance_id query response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_instances"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_id - The ID of the instance to describe (optional)."
    echo "  -q query - The query to filter the response (optional)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:q:h" option; do
    case "${option}" in
      i) instance_id="${OPTARG}" ;;
      q) query="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local aws_cli_args=()

  if [[ -n "$instance_id" ]]; then
    # shellcheck disable=SC2206
    aws_cli_args+=("--instance-ids" $instance_id)
  fi

  local query_arg=""
  if [[ -n "$query" ]]; then
    query_arg="--query '$query'"
  else
    query_arg="--query Reservations[*].Instances[*].[InstanceId,ImageId,InstanceType,KeyName,VpcId,PublicIpAddress,State.Name]"
  fi

  # shellcheck disable=SC2086
  response=$(aws ec2 describe-instances \
    "${aws_cli_args[@]}" \
    $query_arg \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports describe-instances operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeInstances)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) instances associated with an account.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeInstances(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
        }
    }

    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DescribeInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeInstances) 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 인스턴스를 설명하는 방법**  
다음 `describe-instances` 예제에서는 지정된 인스턴스를 설명합니다.  

```
aws ec2 describe-instances \
    --instance-ids i-1234567890abcdef0
```
출력:  

```
{
    "Reservations": [
        {
            "Groups": [],
            "Instances": [
                {
                    "AmiLaunchIndex": 0,
                    "ImageId": "ami-0abcdef1234567890",
                    "InstanceId": "i-1234567890abcdef0",
                    "InstanceType": "t3.nano",
                    "KeyName": "my-key-pair",
                    "LaunchTime": "2022-11-15T10:48:59+00:00",
                    "Monitoring": {
                        "State": "disabled"
                    },
                    "Placement": {
                        "AvailabilityZone": "us-east-2a",
                        "GroupName": "",
                        "Tenancy": "default"
                    },
                    "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                    "PrivateIpAddress": "10-0-0-157",
                    "ProductCodes": [],
                    "PublicDnsName": "ec2-34-253-223-13.us-east-2.compute.amazonaws.com",
                    "PublicIpAddress": "34.253.223.13",
                    "State": {
                        "Code": 16,
                        "Name": "running"
                    },
                    "StateTransitionReason": "",
                    "SubnetId": "subnet-04a636d18e83cfacb",
                    "VpcId": "vpc-1234567890abcdef0",
                    "Architecture": "x86_64",
                    "BlockDeviceMappings": [
                        {
                            "DeviceName": "/dev/xvda",
                            "Ebs": {
                                "AttachTime": "2022-11-15T10:49:00+00:00",
                                "DeleteOnTermination": true,
                                "Status": "attached",
                                "VolumeId": "vol-02e6ccdca7de29cf2"
                            }
                        }
                    ],
                    "ClientToken": "1234abcd-1234-abcd-1234-d46a8903e9bc",
                    "EbsOptimized": true,
                    "EnaSupport": true,
                    "Hypervisor": "xen",
                    "IamInstanceProfile": {
                        "Arn": "arn:aws:iam::111111111111:instance-profile/AmazonSSMRoleForInstancesQuickSetup",
                        "Id": "111111111111111111111"
                    },
                    "NetworkInterfaces": [
                        {
                            "Association": {
                                "IpOwnerId": "amazon",
                                "PublicDnsName": "ec2-34-253-223-13.us-east-2.compute.amazonaws.com",
                                "PublicIp": "34.253.223.13"
                            },
                            "Attachment": {
                                "AttachTime": "2022-11-15T10:48:59+00:00",
                                "AttachmentId": "eni-attach-1234567890abcdefg",
                                "DeleteOnTermination": true,
                                "DeviceIndex": 0,
                                "Status": "attached",
                                "NetworkCardIndex": 0
                            },
                            "Description": "",
                            "Groups": [
                                {
                                    "GroupName": "launch-wizard-146",
                                    "GroupId": "sg-1234567890abcdefg"
                                }
                            ],
                            "Ipv6Addresses": [],
                            "MacAddress": "00:11:22:33:44:55",
                            "NetworkInterfaceId": "eni-1234567890abcdefg",
                            "OwnerId": "104024344472",
                            "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                            "PrivateIpAddress": "10-0-0-157",
                            "PrivateIpAddresses": [
                                {
                                    "Association": {
                                        "IpOwnerId": "amazon",
                                        "PublicDnsName": "ec2-34-253-223-13.us-east-2.compute.amazonaws.com",
                                        "PublicIp": "34.253.223.13"
                                    },
                                    "Primary": true,
                                    "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                                    "PrivateIpAddress": "10-0-0-157"
                                }
                            ],
                            "SourceDestCheck": true,
                            "Status": "in-use",
                            "SubnetId": "subnet-1234567890abcdefg",
                            "VpcId": "vpc-1234567890abcdefg",
                            "InterfaceType": "interface"
                        }
                    ],
                    "RootDeviceName": "/dev/xvda",
                    "RootDeviceType": "ebs",
                    "SecurityGroups": [
                        {
                            "GroupName": "launch-wizard-146",
                            "GroupId": "sg-1234567890abcdefg"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Tags": [
                        {
                            "Key": "Name",
                            "Value": "my-instance"
                        }
                    ],
                    "VirtualizationType": "hvm",
                    "CpuOptions": {
                        "CoreCount": 1,
                        "ThreadsPerCore": 2
                    },
                    "CapacityReservationSpecification": {
                        "CapacityReservationPreference": "open"
                    },
                    "HibernationOptions": {
                        "Configured": false
                    },
                    "MetadataOptions": {
                        "State": "applied",
                        "HttpTokens": "optional",
                        "HttpPutResponseHopLimit": 1,
                        "HttpEndpoint": "enabled",
                        "HttpProtocolIpv6": "disabled",
                        "InstanceMetadataTags": "enabled"
                    },
                    "EnclaveOptions": {
                        "Enabled": false
                    },
                    "PlatformDetails": "Linux/UNIX",
                    "UsageOperation": "RunInstances",
                    "UsageOperationUpdateTime": "2022-11-15T10:48:59+00:00",
                    "PrivateDnsNameOptions": {
                        "HostnameType": "ip-name",
                        "EnableResourceNameDnsARecord": true,
                        "EnableResourceNameDnsAAAARecord": false
                    },
                    "MaintenanceOptions": {
                        "AutoRecovery": "default"
                    }
                }
            ],
            "OwnerId": "111111111111",
            "ReservationId": "r-1234567890abcdefg"
        }
    ]
}
```
**예제 2: 지정된 유형으로 인스턴스를 필터링하는 방법**  
다음 `describe-instances` 예제에서는 필터를 사용하여 결과 범위를 지정된 유형의 인스턴스로 지정합니다.  

```
aws ec2 describe-instances \
    --filters Name=instance-type,Values=m5.large
```
예제 출력은 예제 1을 참조하세요.  
자세한 내용은 *Amazon EC2 사용 설명서*에서 [CLI를 사용하여 나열 및 필터링](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)을 참조하세요.  
**예제 3: 지정된 유형 및 가용 영역으로 인스턴스를 필터링하는 방법**  
다음 `describe-instances` 예제에서는 여러 필터를 사용하여 결과 범위를 지정된 가용 영역에도 있는 지정된 유형의 인스턴스로 지정합니다.  

```
aws ec2 describe-instances \
    --filters Name=instance-type,Values=t2.micro,t3.micro Name=availability-zone,Values=us-east-2c
```
예제 출력은 예제 1을 참조하세요.  
**예제 4: JSON 파일을 사용하여 지정된 유형과 가용 영역의 인스턴스를 필터링하는 방법**  
다음 `describe-instances` 예제에서는 JSON 입력 파일을 사용하여 이전 예제와 동일한 필터링을 수행합니다. 필터가 복잡해지면 JSON 파일에서 필터를 더 쉽게 지정할 수 있습니다.  

```
aws ec2 describe-instances \
    --filters file://filters.json
```
`filters.json`의 콘텐츠:  

```
[
    {
        "Name": "instance-type",
        "Values": ["t2.micro", "t3.micro"]
    },
    {
        "Name": "availability-zone",
        "Values": ["us-east-2c"]
    }
]
```
예제 출력은 예제 1을 참조하세요.  
**예제 5: 지정된 소유자 태그로 인스턴스를 필터링하는 방법**  
다음 `describe-instances` 예제에서는 태그 필터를 사용하여 결과 범위를 태그 값에 관계없이 지정된 태그 키(소유자)의 태그가 있는 인스턴스로 지정합니다.  

```
aws ec2 describe-instances \
    --filters "Name=tag-key,Values=Owner"
```
예제 출력은 예제 1을 참조하세요.  
**예제 6: 지정된 my-team 태그 값으로 인스턴스를 필터링하는 방법**  
다음 `describe-instances` 예제에서는 태그 필터를 사용하여 결과 범위를 태그 값에 관계없이 지정된 태그 값(my-team)의 태그가 있는 인스턴스로 지정합니다.  

```
aws ec2 describe-instances \
    --filters "Name=tag-value,Values=my-team"
```
예제 출력은 예제 1을 참조하세요.  
**예제 7: 지정된 소유자 태그와 my-team 값으로 인스턴스를 필터링하는 방법**  
다음 `describe-instances` 예제에서는 태그 필터를 사용하여 결과 범위를 지정된 태그의 인스턴스(소유자=my-team)로 지정합니다.  

```
aws ec2 describe-instances \
    --filters "Name=tag:Owner,Values=my-team"
```
예제 출력은 예제 1을 참조하세요.  
**예제 8: 모든 인스턴스의 인스턴스 및 서브넷 ID만 표시하는 방법**  
다음 `describe-instances` 예제에서는 `--query` 파라미터를 사용하여 모든 인스턴스의 인스턴스 및 서브넷 ID만 JSON 형식으로 표시합니다.  
Linux 및 macOS:  

```
aws ec2 describe-instances \
    --query 'Reservations[*].Instances[*].{Instance:InstanceId,Subnet:SubnetId}' \
    --output json
```
Windows:  

```
aws ec2 describe-instances ^
    --query "Reservations[*].Instances[*].{Instance:InstanceId,Subnet:SubnetId}" ^
    --output json
```
출력:  

```
[
    {
        "Instance": "i-057750d42936e468a",
        "Subnet": "subnet-069beee9b12030077"
    },
    {
        "Instance": "i-001efd250faaa6ffa",
        "Subnet": "subnet-0b715c6b7db68927a"
    },
    {
        "Instance": "i-027552a73f021f3bd",
        "Subnet": "subnet-0250c25a1f4e15235"
    }
    ...
]
```
**예제 9: 지정된 유형의 인스턴스를 필터링하고 해당 인스턴스 ID만 표시하는 방법**  
다음 `describe-instances` 예제에서는 필터를 사용하여 결과 범위를 지정된 유형의 인스턴스로 지정하고 `--query` 파라미터를 사용하여 인스턴스 ID만 표시합니다.  

```
aws ec2 describe-instances \
    --filters "Name=instance-type,Values=t2.micro" \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
```
출력:  

```
i-031c0dc19de2fb70c
i-00d8bff789a736b75
i-0b715c6b7db68927a
i-0626d4edd54f1286d
i-00b8ae04f9f99908e
i-0fc71c25d2374130c
```
**예제 10: 지정된 유형의 인스턴스를 필터링하고 인스턴스 ID, 가용 영역, 지정된 태그 값만 표시하는 방법**  
다음 `describe-instances` 예제에서는 이름이 `tag-key`인 태그의 인스턴스에 대해 인스턴스 ID, 가용 영역, `Name` 태그 값을 테이블 형식으로 표시합니다.  
Linux 및 macOS:  

```
aws ec2 describe-instances \
    --filters Name=tag-key,Values=Name \
    --query 'Reservations[*].Instances[*].{Instance:InstanceId,AZ:Placement.AvailabilityZone,Name:Tags[?Key==`Name`]|[0].Value}' \
    --output table
```
Windows:  

```
aws ec2 describe-instances ^
    --filters Name=tag-key,Values=Name ^
    --query "Reservations[*].Instances[*].{Instance:InstanceId,AZ:Placement.AvailabilityZone,Name:Tags[?Key=='Name']|[0].Value}" ^
    --output table
```
출력:  

```
-------------------------------------------------------------
|                     DescribeInstances                     |
+--------------+-----------------------+--------------------+
|      AZ      |       Instance        |        Name        |
+--------------+-----------------------+--------------------+
|  us-east-2b  |  i-057750d42936e468a  |  my-prod-server    |
|  us-east-2a  |  i-001efd250faaa6ffa  |  test-server-1     |
|  us-east-2a  |  i-027552a73f021f3bd  |  test-server-2     |
+--------------+-----------------------+--------------------+
```
**예제 11: 파티션 배치 그룹에서 인스턴스를 설명하는 방법**  
다음 `describe-instances` 예제에서는 지정된 인스턴스를 설명합니다. 응답에는 인스턴스의 배치 정보가 포함되며, 이 정보는 인스턴스의 배치 그룹 이름 및 파티션 번호를 포함합니다.  

```
aws ec2 describe-instances \
    --instance-ids i-0123a456700123456 \
    --query "Reservations[*].Instances[*].Placement"
```
출력:  

```
[
    [
        {
            "AvailabilityZone": "us-east-1c",
            "GroupName": "HDFS-Group-A",
            "PartitionNumber": 3,
            "Tenancy": "default"
        }

    ]
]
```
자세한 내용은 *Linux 인스턴스용 Amazon EC2 사용 설명서*에서 [배치 그룹의 인스턴스 설명](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html#describe-instance-placement)을 참조하세요.  
**예제 12: 지정된 배치 그룹과 파티션 번호로 인스턴스를 필터링하는 방법**  
다음 `describe-instances` 예제에서는 결과를 지정된 배치 그룹 및 파티션 번호의 인스턴스로만 필터링합니다.  

```
aws ec2 describe-instances \
    --filters "Name=placement-group-name,Values=HDFS-Group-A" "Name=placement-partition-number,Values=7"
```
다음에서는 출력의 관련 정보만 보여줍니다.  

```
"Instances": [
    {
        "InstanceId": "i-0123a456700123456",
        "InstanceType": "r4.large",
        "Placement": {
            "AvailabilityZone": "us-east-1c",
            "GroupName": "HDFS-Group-A",
            "PartitionNumber": 7,
            "Tenancy": "default"
        }
    },
    {
        "InstanceId": "i-9876a543210987654",
        "InstanceType": "r4.large",
        "Placement": {
            "AvailabilityZone": "us-east-1c",
            "GroupName": "HDFS-Group-A",
            "PartitionNumber": 7,
            "Tenancy": "default"
        }
    ],
```
자세한 내용은 *Linux 인스턴스용 Amazon EC2 사용 설명서*에서 [배치 그룹의 인스턴스 설명](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html#describe-instance-placement)을 참조하세요.  
**예제 13: 인스턴스 메타데이터에서 태그에 액세스할 수 있도록 구성된 인스턴스를 필터링하는 방법**  
다음 `describe-instances` 예제에서는 인스턴스 메타데이터에서 인스턴스 태그에 액세스할 수 있도록 구성된 인스턴스로만 결과를 필터링합니다.  

```
aws ec2 describe-instances \
    --filters "Name=metadata-options.instance-metadata-tags,Values=enabled" \
    --query "Reservations[*].Instances[*].InstanceId" \
    --output text
```
다음에서는 예상 출력을 보여줍니다.  

```
i-1234567890abcdefg
i-abcdefg1234567890
i-11111111aaaaaaaaa
i-aaaaaaaa111111111
```
자세한 내용은 [Amazon EC2 사용 설명서](https://docs.aws.amazon.com/en_us/AWSEC2/latest/UserGuide/Using_Tags.html#view-access-to-tags-in-IMDS)에서 *인스턴스 메타데이터의 인스턴스 태그 작업*을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instances.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Asynchronously describes the state of an EC2 instance.
     * The paginator helps you iterate over multiple pages of results.
     *
     * @param newInstanceId the ID of the EC2 instance to describe
     * @return a {@link CompletableFuture} that, when completed, contains a string describing the state of the EC2 instance
     */
    public CompletableFuture<String> describeEC2InstancesAsync(String newInstanceId) {
        DescribeInstancesRequest request = DescribeInstancesRequest.builder()
            .instanceIds(newInstanceId)
            .build();

        DescribeInstancesPublisher paginator = getAsyncClient().describeInstancesPaginator(request);
        AtomicReference<String> publicIpAddressRef = new AtomicReference<>();
        return paginator.subscribe(response -> {
            response.reservations().stream()
                .flatMap(reservation -> reservation.instances().stream())
                .filter(instance -> instance.instanceId().equals(newInstanceId))
                .findFirst()
                .ifPresent(instance -> publicIpAddressRef.set(instance.publicIpAddress()));
        }).thenApply(v -> {
            String publicIpAddress = publicIpAddressRef.get();
            if (publicIpAddress == null) {
                throw new RuntimeException("Instance with ID " + newInstanceId + " not found.");
            }
            return publicIpAddress;
        }).exceptionally(ex -> {
            logger.info("Failed to describe instances: " + ex.getMessage());
            throw new RuntimeException("Failed to describe instances", ex);
        });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DescribeInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstances) 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, paginateDescribeInstances } from "@aws-sdk/client-ec2";

/**
 * List all of your EC2 instances running with the provided architecture that
 * were launched in the past month.
 * @param {{ pageSize: string, architectures: string[] }} options
 */
export const main = async ({ pageSize, architectures }) => {
  pageSize = Number.parseInt(pageSize);
  const client = new EC2Client({});
  const d = new Date();
  const year = d.getFullYear();
  const month = `0${d.getMonth() + 1}`.slice(-2);
  const launchTimePattern = `${year}-${month}-*`;

  const paginator = paginateDescribeInstances(
    {
      client,
      pageSize,
    },
    {
      Filters: [
        { Name: "architecture", Values: architectures },
        { Name: "instance-state-name", Values: ["running"] },
        {
          Name: "launch-time",
          Values: [launchTimePattern],
        },
      ],
    },
  );

  try {
    /**
     * @type {import('@aws-sdk/client-ec2').Instance[]}
     */
    const instanceList = [];
    for await (const page of paginator) {
      const { Reservations } = page;
      for (const reservation of Reservations) {
        instanceList.push(...reservation.Instances);
      }
    }
    console.log(
      `Running instances launched this month:\n\n${instanceList.map((instance) => instance.InstanceId).join("\n")}`,
    );
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}.`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DescribeInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstancesCommand) 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun describeEC2Instances() {
    val request =
        DescribeInstancesRequest {
            maxResults = 6
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeInstances(request)
        response.reservations?.forEach { reservation ->
            reservation.instances?.forEach { instance ->
                println("Instance Id is ${instance.instanceId}")
                println("Image id is ${instance.imageId}")
                println("Instance type is ${instance.instanceType}")
                println("Instance state name is ${instance.state?.name}")
                println("monitoring information is ${instance.monitoring?.state}")
            }
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DescribeInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스를 설명합니다.**  

```
(Get-EC2Instance -InstanceId i-12345678).Instances
```
**출력:**  

```
AmiLaunchIndex        : 0
Architecture          : x86_64
BlockDeviceMappings   : {/dev/sda1}
ClientToken           : TleEy1448154045270
EbsOptimized          : False
Hypervisor            : xen
IamInstanceProfile    : Amazon.EC2.Model.IamInstanceProfile
ImageId               : ami-12345678
InstanceId            : i-12345678
InstanceLifecycle     :
InstanceType          : t2.micro
KernelId              :
KeyName               : my-key-pair
LaunchTime            : 12/4/2015 4:44:40 PM
Monitoring            : Amazon.EC2.Model.Monitoring
NetworkInterfaces     : {ip-10-0-2-172.us-west-2.compute.internal}
Placement             : Amazon.EC2.Model.Placement
Platform              : Windows
PrivateDnsName        : ip-10-0-2-172.us-west-2.compute.internal
PrivateIpAddress      : 10.0.2.172
ProductCodes          : {}
PublicDnsName         : 
PublicIpAddress       : 
RamdiskId             :
RootDeviceName        : /dev/sda1
RootDeviceType        : ebs
SecurityGroups        : {default}
SourceDestCheck       : True
SpotInstanceRequestId :
SriovNetSupport       :
State                 : Amazon.EC2.Model.InstanceState
StateReason           :
StateTransitionReason :
SubnetId              : subnet-12345678
Tags                  : {Name}
VirtualizationType    : hvm
VpcId                 : vpc-12345678
```
**예제 2: 이 예제에서는 예약별로 그룹화된 현재 리전의 모든 인스턴스를 설명합니다. 인스턴스 세부 정보를 보려면 각 예약 객체 내에서 인스턴스 컬렉션을 확장합니다.**  

```
Get-EC2Instance
```
**출력:**  

```
GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 226008221399
ReservationId : r-c5df370c

GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 854251627541
ReservationId : r-63e65bab
...
```
**예제 3: 이 예제에서는 필터를 사용하여 VPC의 특정 서브넷에서 EC2 인스턴스를 쿼리하는 방법을 보여줍니다.**  

```
(Get-EC2Instance -Filter @{Name="vpc-id";Values="vpc-1a2bc34d"},@{Name="subnet-id";Values="subnet-1a2b3c4d"}).Instances
```
**출력:**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-01af...82cf180e19 t2.medium    Windows  10.0.0.98                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0374...7e9d5b0c45 t2.xlarge    Windows  10.0.0.53                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**예제 4: 이 예제에서는 여러 값이 있는 필터를 사용하여 running 및 stopped 상태의 EC2 인스턴스를 쿼리하는 방법을 보여줍니다.**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

(Get-EC2Instance @InstanceParams).Instances
```
**출력:**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**예제 5: 이 예제에서는 여러 값이 있는 필터를 사용하여 running 및 stopped 상태의 EC2 인스턴스를 쿼리하고 Select-Object cmdlet을 사용하여 출력할 특정 값을 선택하는 방법을 보여줍니다.**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

$SelectParams = @{
    Property = @(
        "InstanceID", "InstanceType", "Platform", "PrivateIpAddress",
        @{Name="Name";Expression={$_.Tags[$_.Tags.Key.IndexOf("Name")].Value}},
        @{Name="State";Expression={$_.State.Name}}
    )
}

$result = Get-EC2Instance @InstanceParams
$result.Instances | Select-Object @SelectParams | Format-Table -AutoSize
```
**출력:**  

```
InstanceId          InstanceType Platform PrivateIpAddress Name         State
----------          ------------ -------- ---------------- ----         -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7         ec2-name-01  running
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8         ec2-name-02  stopped
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10        ec2-name-03  running
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11        ec2-name-04  stopped
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5         ec2-name-05  running
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6         ec2-name-06  stopped
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스를 설명합니다.**  

```
(Get-EC2Instance -InstanceId i-12345678).Instances
```
**출력:**  

```
AmiLaunchIndex        : 0
Architecture          : x86_64
BlockDeviceMappings   : {/dev/sda1}
ClientToken           : TleEy1448154045270
EbsOptimized          : False
Hypervisor            : xen
IamInstanceProfile    : Amazon.EC2.Model.IamInstanceProfile
ImageId               : ami-12345678
InstanceId            : i-12345678
InstanceLifecycle     :
InstanceType          : t2.micro
KernelId              :
KeyName               : my-key-pair
LaunchTime            : 12/4/2015 4:44:40 PM
Monitoring            : Amazon.EC2.Model.Monitoring
NetworkInterfaces     : {ip-10-0-2-172.us-west-2.compute.internal}
Placement             : Amazon.EC2.Model.Placement
Platform              : Windows
PrivateDnsName        : ip-10-0-2-172.us-west-2.compute.internal
PrivateIpAddress      : 10.0.2.172
ProductCodes          : {}
PublicDnsName         : 
PublicIpAddress       : 
RamdiskId             :
RootDeviceName        : /dev/sda1
RootDeviceType        : ebs
SecurityGroups        : {default}
SourceDestCheck       : True
SpotInstanceRequestId :
SriovNetSupport       :
State                 : Amazon.EC2.Model.InstanceState
StateReason           :
StateTransitionReason :
SubnetId              : subnet-12345678
Tags                  : {Name}
VirtualizationType    : hvm
VpcId                 : vpc-12345678
```
**예제 2: 이 예제에서는 예약별로 그룹화된 현재 리전의 모든 인스턴스를 설명합니다. 인스턴스 세부 정보를 보려면 각 예약 객체 내에서 인스턴스 컬렉션을 확장합니다.**  

```
Get-EC2Instance
```
**출력:**  

```
GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 226008221399
ReservationId : r-c5df370c

GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 854251627541
ReservationId : r-63e65bab
...
```
**예제 3: 이 예제에서는 필터를 사용하여 VPC의 특정 서브넷에서 EC2 인스턴스를 쿼리하는 방법을 보여줍니다.**  

```
(Get-EC2Instance -Filter @{Name="vpc-id";Values="vpc-1a2bc34d"},@{Name="subnet-id";Values="subnet-1a2b3c4d"}).Instances
```
**출력:**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-01af...82cf180e19 t2.medium    Windows  10.0.0.98                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0374...7e9d5b0c45 t2.xlarge    Windows  10.0.0.53                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**예제 4: 이 예제에서는 여러 값이 있는 필터를 사용하여 running 및 stopped 상태의 EC2 인스턴스를 쿼리하는 방법을 보여줍니다.**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

(Get-EC2Instance @InstanceParams).Instances
```
**출력:**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**예제 5: 이 예제에서는 여러 값이 있는 필터를 사용하여 running 및 stopped 상태의 EC2 인스턴스를 쿼리하고 Select-Object cmdlet을 사용하여 출력할 특정 값을 선택하는 방법을 보여줍니다.**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

$SelectParams = @{
    Property = @(
        "InstanceID", "InstanceType", "Platform", "PrivateIpAddress",
        @{Name="Name";Expression={$_.Tags[$_.Tags.Key.IndexOf("Name")].Value}},
        @{Name="State";Expression={$_.State.Name}}
    )
}

$result = Get-EC2Instance @InstanceParams
$result.Instances | Select-Object @SelectParams | Format-Table -AutoSize
```
**출력:**  

```
InstanceId          InstanceType Platform PrivateIpAddress Name         State
----------          ------------ -------- ---------------- ----         -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7         ec2-name-01  running
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8         ec2-name-02  stopped
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10        ec2-name-03  running
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11        ec2-name-04  stopped
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5         ec2-name-05  running
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6         ec2-name-06  stopped
```
**예제 6: 이 예제에서는 인스턴스를 실제로 가져오지 않고 DryRun 파라미터를 사용하여 EC2 인스턴스를 가져올 수 있는 권한을 검증합니다. 참고: 작업이 성공하면 예외가 발생하며 이는 정상적인 동작입니다.**  

```
Get-EC2Tag -DryRun $true
```
**출력:**  

```
Get-EC2Instance: Request would have succeeded, but DryRun flag is set.
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def display(self, state_filter: Optional[str] = "running") -> None:
        """
        Displays information about instances, filtering by the specified state.

        :param state_filter: The instance state to include in the output. Only instances in this state
                             will be displayed. Default is 'running'. Example states: 'running', 'stopped'.
        """
        if not self.instances:
            logger.info("No instances to display.")
            return

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        paginator = self.ec2_client.get_paginator("describe_instances")
        page_iterator = paginator.paginate(InstanceIds=instance_ids)

        try:
            for page in page_iterator:
                for reservation in page["Reservations"]:
                    for instance in reservation["Instances"]:
                        instance_state = instance["State"]["Name"]

                        # Apply the state filter (default is 'running')
                        if state_filter and instance_state != state_filter:
                            continue  # Skip this instance if it doesn't match the filter

                        # Create a formatted string with instance details
                        instance_info = (
                            f"• ID: {instance['InstanceId']}\n"
                            f"• Image ID: {instance['ImageId']}\n"
                            f"• Instance type: {instance['InstanceType']}\n"
                            f"• Key name: {instance['KeyName']}\n"
                            f"• VPC ID: {instance['VpcId']}\n"
                            f"• Public IP: {instance.get('PublicIpAddress', 'N/A')}\n"
                            f"• State: {instance_state}"
                        )
                        print(instance_info)

        except ClientError as err:
            logger.error(
                f"Failed to display instance(s). : {' '.join(map(str, instance_ids))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                logger.error(
                    "One or more instance IDs do not exist. "
                    "Please verify the instance IDs and try again."
                )
                raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstances)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'aws-sdk-ec2'

# @param ec2_resource [Aws::EC2::Resource] An initialized EC2 resource object.
# @example
#   list_instance_ids_states(Aws::EC2::Resource.new(region: 'us-west-2'))
def list_instance_ids_states(ec2_resource)
  response = ec2_resource.instances
  if response.count.zero?
    puts 'No instances found.'
  else
    puts 'Instances -- ID, state:'
    response.each do |instance|
      puts "#{instance.id}, #{instance.state.name}"
    end
  end
rescue StandardError => e
  puts "Error getting information about instances: #{e.message}"
end

# Example usage:
def run_me
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-get-all-instance-info.rb REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-get-all-instance-info.rb us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    region = ARGV[0]
  end
  ec2_resource = Aws::EC2::Resource.new(region: region)
  list_instance_ids_states(ec2_resource)
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DescribeInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/DescribeInstances) 참조하십시오.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
EC2 인스턴스에 대한 세부 정보를 검색합니다.  

```
    pub async fn describe_instance(&self, instance_id: &str) -> Result<Instance, EC2Error> {
        let response = self
            .client
            .describe_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        let instance = response
            .reservations()
            .first()
            .ok_or_else(|| EC2Error::new(format!("No instance reservations for {instance_id}")))?
            .instances()
            .first()
            .ok_or_else(|| {
                EC2Error::new(format!("No instances in reservation for {instance_id}"))
            })?;

        Ok(instance.clone())
    }
```
EC2 인스턴스를 만든 후 세부 정보를 검색하고 저장합니다.  

```
    /// Create an EC2 instance with the given ID on a given type, using a
    /// generated KeyPair and applying a list of security groups.
    pub async fn create(
        &mut self,
        ec2: &EC2,
        image_id: &str,
        instance_type: InstanceType,
        key_pair: &KeyPairInfo,
        security_groups: Vec<&SecurityGroup>,
    ) -> Result<(), EC2Error> {
        let instance_id = ec2
            .create_instance(image_id, instance_type, key_pair, security_groups)
            .await?;
        let instance = ec2.describe_instance(&instance_id).await?;
        self.instance = Some(instance);
        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DescribeInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_instances)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->describeinstances( ).                        " oo_result is returned for testing purposes. "

        " Retrieving details of EC2 instances. "
        DATA: lv_istance_id    TYPE /aws1/ec2string,
              lv_status        TYPE /aws1/ec2instancestatename,
              lv_instance_type TYPE /aws1/ec2instancetype,
              lv_image_id      TYPE /aws1/ec2string.
        LOOP AT oo_result->get_reservations( ) INTO DATA(lo_reservation).
          LOOP AT lo_reservation->get_instances( ) INTO DATA(lo_instance).
            lv_istance_id = lo_instance->get_instanceid( ).
            lv_status = lo_instance->get_state( )->get_name( ).
            lv_instance_type = lo_instance->get_instancetype( ).
            lv_image_id = lo_instance->get_imageid( ).
          ENDLOOP.
        ENDLOOP.
        MESSAGE 'Retrieved information about EC2 instances.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DescribeInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeInternetGateways` 사용
<a name="example_ec2_DescribeInternetGateways_section"></a>

다음 코드 예시는 `DescribeInternetGateways`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**인터넷 게이트웨이 설명**  
다음 `describe-internet-gateways` 예시에서는 지정된 인터넷 게이트웨이를 설명합니다.  

```
aws ec2 describe-internet-gateways \
    --internet-gateway-ids igw-0d0fb496b3EXAMPLE
```
출력:  

```
{
    "InternetGateways": [
        {
            "Attachments": [
                {
                    "State": "available",
                    "VpcId": "vpc-0a60eb65b4EXAMPLE"
                }
            ],
            "InternetGatewayId": "igw-0d0fb496b3EXAMPLE",
            "OwnerId": "123456789012",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "my-igw"
                }
            ]
        }
    ]
}
```
자세한 내용은 *Amazon VPC 사용 설명서*의 [인터넷 게이트웨이](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeInternetGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-internet-gateways.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인터넷 게이트웨이를 설명합니다.**  

```
Get-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**출력:**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
```
**예제 2: 이 예제에서는 모든 인터넷 게이트웨이를 설명합니다.**  

```
Get-EC2InternetGateway
```
**출력:**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
{}                igw-2a3b4c5d          {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeInternetGateways](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인터넷 게이트웨이를 설명합니다.**  

```
Get-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**출력:**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
```
**예제 2: 이 예제에서는 모든 인터넷 게이트웨이를 설명합니다.**  

```
Get-EC2InternetGateway
```
**출력:**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
{}                igw-2a3b4c5d          {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeInternetGateways](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeKeyPairs` 함께 사용
<a name="example_ec2_DescribeKeyPairs_section"></a>

다음 코드 예시는 `DescribeKeyPairs`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Get information about an Amazon EC2 key pair.
    /// </summary>
    /// <param name="keyPairName">The name of the key pair.</param>
    /// <returns>A list of key pair information.</returns>
    public async Task<List<KeyPairInfo>> DescribeKeyPairs(string keyPairName)
    {
        try
        {
            var request = new DescribeKeyPairsRequest();
            if (!string.IsNullOrEmpty(keyPairName))
            {
                request = new DescribeKeyPairsRequest
                {
                    KeyNames = new List<string> { keyPairName }
                };
            }

            var response = await _amazonEC2.DescribeKeyPairsAsync(request);
            return response.KeyPairs.ToList();
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidKeyPair.NotFound")
            {
                _logger.LogError(
                    $"A key pair called {keyPairName} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while describing the key pair.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DescribeKeyPairs](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeKeyPairs)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_describe_key_pairs
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) key pairs.
#
# Parameters:
#       -h - Display help.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_key_pairs() {
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_key_pairs"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) key pairs."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "h" option; do
    case "${option}" in
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local response

  response=$(aws ec2 describe-key-pairs \
    --query 'KeyPairs[*].[KeyName, KeyFingerprint]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports describe-key-pairs operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeKeyPairs](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeKeyPairs)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) instance key pairs.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeKeyPairs(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DescribeKeyPairs](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeKeyPairs)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**키 페어를 표시하는 방법**  
다음 `describe-key-pairs` 예제는 지정된 키 페어에 대한 정보를 표시합니다.  

```
aws ec2 describe-key-pairs \
    --key-names my-key-pair
```
출력:  

```
{
    "KeyPairs": [
        {
            "KeyPairId": "key-0b94643da6EXAMPLE",
            "KeyFingerprint": "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f",
            "KeyName": "my-key-pair",
            "KeyType": "rsa",
            "Tags": [],
            "CreateTime": "2022-05-27T21:51:16.000Z"
        }
    ]
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [퍼블릭 키 설명](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/describe-keys.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeKeyPairs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-key-pairs.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Asynchronously describes the key pairs associated with the current AWS account.
     *
     * @return a {@link CompletableFuture} containing the {@link DescribeKeyPairsResponse} object, which provides
     * information about the key pairs.
     */
    public CompletableFuture<DescribeKeyPairsResponse> describeKeysAsync() {
        CompletableFuture<DescribeKeyPairsResponse> responseFuture = getAsyncClient().describeKeyPairs();
        responseFuture.whenComplete((response, exception) -> {
            if (exception != null) {
              throw new RuntimeException("Failed to describe key pairs: " + exception.getMessage(), exception);
            }
        });

        return responseFuture;
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DescribeKeyPairs](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeKeyPairs)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { DescribeKeyPairsCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * List all key pairs in the current AWS account.
 * @param {{ dryRun: boolean }}
 */
export const main = async ({ dryRun }) => {
  const client = new EC2Client({});
  const command = new DescribeKeyPairsCommand({ DryRun: dryRun });

  try {
    const { KeyPairs } = await client.send(command);
    const keyPairList = KeyPairs.map(
      (kp) => ` • ${kp.KeyPairId}: ${kp.KeyName}`,
    ).join("\n");
    console.log("The following key pairs were found in your account:");
    console.log(keyPairList);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "DryRunOperation") {
      console.log(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DescribeKeyPairs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeKeyPairsCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun describeEC2Keys() {
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeKeyPairs(DescribeKeyPairsRequest {})
        response.keyPairs?.forEach { keyPair ->
            println("Found key pair with name ${keyPair.keyName} and fingerprint ${ keyPair.keyFingerprint}")
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DescribeKeyPairs](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 키 페어를 설명합니다.**  

```
Get-EC2KeyPair -KeyName my-key-pair
```
**출력:**  

```
KeyFingerprint                                              KeyName
--------------                                              -------
1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f my-key-pair
```
**예제 2: 이 예제에서는 모든 키 페어를 설명합니다.**  

```
Get-EC2KeyPair
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeKeyPairs](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 키 페어를 설명합니다.**  

```
Get-EC2KeyPair -KeyName my-key-pair
```
**출력:**  

```
KeyFingerprint                                              KeyName
--------------                                              -------
1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f my-key-pair
```
**예제 2: 이 예제에서는 모든 키 페어를 설명합니다.**  

```
Get-EC2KeyPair
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeKeyPairs](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class KeyPairWrapper:
    """
    Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.
    This class provides methods to create, list, and delete EC2 key pairs.
    """

    def __init__(
        self,
        ec2_client: boto3.client,
        key_file_dir: Union[tempfile.TemporaryDirectory, str],
        key_pair: Optional[dict] = None,
    ):
        """
        Initializes the KeyPairWrapper with the specified EC2 client, key file directory,
        and an optional key pair.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param key_file_dir: The folder where the private key information is stored.
                             This should be a secure folder.
        :param key_pair: A dictionary representing the Boto3 KeyPair object.
                         This is a high-level object that wraps key pair actions. Optional.
        """
        self.ec2_client = ec2_client
        self.key_pair = key_pair
        self.key_file_path: Optional[str] = None
        self.key_file_dir = key_file_dir

    @classmethod
    def from_client(cls) -> "KeyPairWrapper":
        """
        Class method to create an instance of KeyPairWrapper using a new EC2 client
        and a temporary directory for storing key files.

        :return: An instance of KeyPairWrapper.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client, tempfile.TemporaryDirectory())


    def list(self, limit: Optional[int] = None) -> None:
        """
        Displays a list of key pairs for the current account.

        WARNING: Results are not paginated.

        :param limit: The maximum number of key pairs to list. If not specified,
                      all key pairs will be listed.
        :raises ClientError: If there is an error in listing the key pairs.
        """
        try:
            response = self.ec2_client.describe_key_pairs()
            key_pairs = response.get("KeyPairs", [])

            if limit:
                key_pairs = key_pairs[:limit]

            for key_pair in key_pairs:
                logger.info(
                    f"Found {key_pair['KeyType']} key '{key_pair['KeyName']}' with fingerprint:"
                )
                logger.info(f"\t{key_pair['KeyFingerprint']}")
        except ClientError as err:
            logger.error(f"Failed to list key pairs: {str(err)}")
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeKeyPairs](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeKeyPairs)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn list_key_pair(&self) -> Result<Vec<KeyPairInfo>, EC2Error> {
        let output = self.client.describe_key_pairs().send().await?;
        Ok(output.key_pairs.unwrap_or_default())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DescribeKeyPairs](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_key_pairs)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->describekeypairs( ).                        " oo_result is returned for testing purposes. "
        DATA(lt_key_pairs) = oo_result->get_keypairs( ).
        MESSAGE 'Retrieved information about key pairs.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DescribeKeyPairs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Describe the key pairs associated with the user by outputting each key
    /// pair's name and fingerprint.
    func describeKeyPairs() async {
        do {
            let output = try await ec2Client.describeKeyPairs(
                input: DescribeKeyPairsInput()
            )

            guard let keyPairs = output.keyPairs else {
                print("*** No key pairs list available.")
                return
            }

            for keyPair in keyPairs {
                print(keyPair.keyName ?? "<unknown>", ":", keyPair.keyFingerprint ?? "<unknown>")
            }
        } catch {
            print("*** Error: Unable to obtain a key pair list.")
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DescribeKeyPairs](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describekeypairs(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeNetworkAcls` 사용
<a name="example_ec2_DescribeNetworkAcls_section"></a>

다음 코드 예시는 `DescribeNetworkAcls`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 ACL 설명**  
다음 `describe-network-acls` 예시에서는 네트워크 ACL에 대한 세부 정보를 검색합니다.  

```
aws ec2 describe-network-acls
```
출력:  

```
{
    "NetworkAcls": [
        {
            "Associations": [
                {
                    "NetworkAclAssociationId": "aclassoc-0c1679dc41EXAMPLE",
                    "NetworkAclId": "acl-0ea1f54ca7EXAMPLE",
                    "SubnetId": "subnet-0931fc2fa5EXAMPLE"
                }
            ],
            "Entries": [
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": true,
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 100
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": true,
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32767
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": false,
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 100
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": false,
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32767
                }
            ],
            "IsDefault": true,
            "NetworkAclId": "acl-0ea1f54ca7EXAMPLE",
            "Tags": [],
            "VpcId": "vpc-06e4ab6c6cEXAMPLE",
            "OwnerId": "111122223333"
        },
        {
            "Associations": [],
            "Entries": [
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": true,
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 100
                },
                {
                    "Egress": true,
                    "Ipv6CidrBlock": "::/0",
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 101
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": true,
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32767
                },
                {
                    "Egress": true,
                    "Ipv6CidrBlock": "::/0",
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32768
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": false,
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 100
                },
                {
                    "Egress": false,
                    "Ipv6CidrBlock": "::/0",
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 101
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": false,
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32767
                },
                {
                    "Egress": false,
                    "Ipv6CidrBlock": "::/0",
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32768
                }
            ],
            "IsDefault": true,
            "NetworkAclId": "acl-0e2a78e4e2EXAMPLE",
            "Tags": [],
            "VpcId": "vpc-03914afb3eEXAMPLE",
            "OwnerId": "111122223333"
        }
    ]
}
```
자세한 내용은 *AWS VPC 사용 설명서*의 [네트워크 ACL](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeNetworkAcls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-acls.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL을 설명합니다.**  

```
Get-EC2NetworkAcl -NetworkAclId acl-12345678
```
**출력:**  

```
Associations : {aclassoc-1a2b3c4d}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {Name}
VpcId        : vpc-12345678
```
**예제 2: 이 예제에서는 지정된 네트워크 ACL에 대한 규칙을 설명합니다.**  

```
(Get-EC2NetworkAcl -NetworkAclId acl-12345678).Entries
```
**출력:**  

```
CidrBlock    : 0.0.0.0/0
Egress       : True
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767

CidrBlock    : 0.0.0.0/0
Egress       : False
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767
```
**예제 3: 이 예제에서는 모든 네트워크 ACL을 설명합니다.**  

```
Get-EC2NetworkAcl
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeNetworkAcls](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL을 설명합니다.**  

```
Get-EC2NetworkAcl -NetworkAclId acl-12345678
```
**출력:**  

```
Associations : {aclassoc-1a2b3c4d}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {Name}
VpcId        : vpc-12345678
```
**예제 2: 이 예제에서는 지정된 네트워크 ACL에 대한 규칙을 설명합니다.**  

```
(Get-EC2NetworkAcl -NetworkAclId acl-12345678).Entries
```
**출력:**  

```
CidrBlock    : 0.0.0.0/0
Egress       : True
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767

CidrBlock    : 0.0.0.0/0
Egress       : False
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767
```
**예제 3: 이 예제에서는 모든 네트워크 ACL을 설명합니다.**  

```
Get-EC2NetworkAcl
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeNetworkAcls](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeNetworkInterfaceAttribute` 사용
<a name="example_ec2_DescribeNetworkInterfaceAttribute_section"></a>

다음 코드 예시는 `DescribeNetworkInterfaceAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 인터페이스의 연결 속성 설명**  
이 예시 명령은 지정된 네트워크 인터페이스의 `attachment` 속성을 설명합니다.  
명령:  

```
aws ec2 describe-network-interface-attribute --network-interface-id eni-686ea200 --attribute attachment
```
출력:  

```
{
  "NetworkInterfaceId": "eni-686ea200",
  "Attachment": {
      "Status": "attached",
      "DeviceIndex": 0,
      "AttachTime": "2015-05-21T20:02:20.000Z",
      "InstanceId": "i-1234567890abcdef0",
      "DeleteOnTermination": true,
      "AttachmentId": "eni-attach-43348162",
      "InstanceOwnerId": "123456789012"
  }
}
```
**네트워크 인터페이스의 설명 속성 설명**  
이 예시 명령은 지정된 네트워크 인터페이스의 `description` 속성을 설명합니다.  
명령:  

```
aws ec2 describe-network-interface-attribute --network-interface-id eni-686ea200 --attribute description
```
출력:  

```
{
  "NetworkInterfaceId": "eni-686ea200",
  "Description": {
      "Value": "My description"
  }
}
```
**네트워크 인터페이스의 groupSet 속성 설명**  
이 예시 명령은 지정된 네트워크 인터페이스의 `groupSet` 속성을 설명합니다.  
명령:  

```
aws ec2 describe-network-interface-attribute --network-interface-id eni-686ea200 --attribute groupSet
```
출력:  

```
{
  "NetworkInterfaceId": "eni-686ea200",
  "Groups": [
      {
          "GroupName": "my-security-group",
          "GroupId": "sg-903004f8"
      }
  ]
}
```
**네트워크 인터페이스의 sourceDestCheck 속성 설명**  
이 예시 명령은 지정된 네트워크 인터페이스의 `sourceDestCheck` 속성을 설명합니다.  
명령:  

```
aws ec2 describe-network-interface-attribute --network-interface-id eni-686ea200 --attribute sourceDestCheck
```
출력:  

```
{
  "NetworkInterfaceId": "eni-686ea200",
  "SourceDestCheck": {
      "Value": true
  }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeNetworkInterfaceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-interface-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Attachment
```
**출력:**  

```
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
```
**예제 2: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Description
```
**출력:**  

```
Description        : My description
```
**예제 3: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute GroupSet
```
**출력:**  

```
Groups             : {my-security-group}
```
**예제 4: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute SourceDestCheck
```
**출력:**  

```
SourceDestCheck    : True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Attachment
```
**출력:**  

```
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
```
**예제 2: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Description
```
**출력:**  

```
Description        : My description
```
**예제 3: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute GroupSet
```
**출력:**  

```
Groups             : {my-security-group}
```
**예제 4: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute SourceDestCheck
```
**출력:**  

```
SourceDestCheck    : True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeNetworkInterfaces` 사용
<a name="example_ec2_DescribeNetworkInterfaces_section"></a>

다음 코드 예시는 `DescribeNetworkInterfaces`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 인터페이스 설명**  
이 예시에서는 모든 네트워크 인터페이스를 설명합니다.  
명령:  

```
aws ec2 describe-network-interfaces
```
출력:  

```
{
  "NetworkInterfaces": [
      {
          "Status": "in-use",
          "MacAddress": "02:2f:8f:b0:cf:75",
          "SourceDestCheck": true,
          "VpcId": "vpc-a01106c2",
          "Description": "my network interface",
          "Association": {
              "PublicIp": "203.0.113.12",
              "AssociationId": "eipassoc-0fbb766a",
              "PublicDnsName": "ec2-203-0-113-12.compute-1.amazonaws.com",
              "IpOwnerId": "123456789012"
          },
          "NetworkInterfaceId": "eni-e5aa89a3",
          "PrivateIpAddresses": [
              {
                  "PrivateDnsName": "ip-10-0-1-17.ec2.internal",
                  "Association": {
                      "PublicIp": "203.0.113.12",
                      "AssociationId": "eipassoc-0fbb766a",
                      "PublicDnsName": "ec2-203-0-113-12.compute-1.amazonaws.com",
                      "IpOwnerId": "123456789012"
                  },
                  "Primary": true,
                  "PrivateIpAddress": "10.0.1.17"
              }
          ],
          "RequesterManaged": false,
          "Ipv6Addresses": [],
          "PrivateDnsName": "ip-10-0-1-17.ec2.internal",
          "AvailabilityZone": "us-east-1d",
          "Attachment": {
              "Status": "attached",
              "DeviceIndex": 1,
              "AttachTime": "2013-11-30T23:36:42.000Z",
              "InstanceId": "i-1234567890abcdef0",
              "DeleteOnTermination": false,
              "AttachmentId": "eni-attach-66c4350a",
              "InstanceOwnerId": "123456789012"
          },
          "Groups": [
              {
                  "GroupName": "default",
                  "GroupId": "sg-8637d3e3"
              }
          ],
          "SubnetId": "subnet-b61f49f0",
          "OwnerId": "123456789012",
          "TagSet": [],
          "PrivateIpAddress": "10.0.1.17"
      },
      {
          "Status": "in-use",
          "MacAddress": "02:58:f5:ef:4b:06",
          "SourceDestCheck": true,
          "VpcId": "vpc-a01106c2",
          "Description": "Primary network interface",
          "Association": {
              "PublicIp": "198.51.100.0",
              "IpOwnerId": "amazon"
          },
          "NetworkInterfaceId": "eni-f9ba99bf",
          "PrivateIpAddresses": [
              {
                  "Association": {
                      "PublicIp": "198.51.100.0",
                      "IpOwnerId": "amazon"
                  },
                  "Primary": true,
                  "PrivateIpAddress": "10.0.1.149"
              }
          ],
          "RequesterManaged": false,
          "Ipv6Addresses": [],
          "AvailabilityZone": "us-east-1d",
          "Attachment": {
              "Status": "attached",
              "DeviceIndex": 0,
              "AttachTime": "2013-11-30T23:35:33.000Z",
              "InstanceId": "i-0598c7d356eba48d7",
              "DeleteOnTermination": true,
              "AttachmentId": "eni-attach-1b9db777",
              "InstanceOwnerId": "123456789012"
          },
          "Groups": [
              {
                  "GroupName": "default",
                  "GroupId": "sg-8637d3e3"
              }
          ],
          "SubnetId": "subnet-b61f49f0",
          "OwnerId": "123456789012",
          "TagSet": [],
          "PrivateIpAddress": "10.0.1.149"
      }
  ]
}
```
이 예시에서는 `Purpose` 키와 `Prod` 값을 가진 태그가 있는 네트워크 인터페이스에 대해 설명합니다.  
명령:  

```
aws ec2 describe-network-interfaces --filters Name=tag:Purpose,Values=Prod
```
출력:  

```
{
  "NetworkInterfaces": [
      {
          "Status": "available",
          "MacAddress": "12:2c:bd:f9:bf:17",
          "SourceDestCheck": true,
          "VpcId": "vpc-8941ebec",
          "Description": "ProdENI",
          "NetworkInterfaceId": "eni-b9a5ac93",
          "PrivateIpAddresses": [
              {
                  "PrivateDnsName": "ip-10-0-1-55.ec2.internal",
                  "Primary": true,
                  "PrivateIpAddress": "10.0.1.55"
              },
              {
                  "PrivateDnsName": "ip-10-0-1-117.ec2.internal",
                  "Primary": false,
                  "PrivateIpAddress": "10.0.1.117"
              }
          ],
          "RequesterManaged": false,
          "PrivateDnsName": "ip-10-0-1-55.ec2.internal",
          "AvailabilityZone": "us-east-1d",
          "Ipv6Addresses": [],
          "Groups": [
              {
                  "GroupName": "MySG",
                  "GroupId": "sg-905002f5"
              }
          ],
          "SubnetId": "subnet-31d6c219",
          "OwnerId": "123456789012",
          "TagSet": [
              {
                  "Value": "Prod",
                  "Key": "Purpose"
              }
          ],
          "PrivateIpAddress": "10.0.1.55"
      }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeNetworkInterfaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-interfaces.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**출력:**  

```
Association        :
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
AvailabilityZone   : us-west-2c
Description        :
Groups             : {my-security-group}
MacAddress         : 0a:e9:a6:19:4c:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-107.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.107
PrivateIpAddresses : {ip-10-0-0-107.us-west-2.compute.internal}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : in-use
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
**예제 2: 이 예제에서는 모든 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterface
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeNetworkInterfaces](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**출력:**  

```
Association        :
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
AvailabilityZone   : us-west-2c
Description        :
Groups             : {my-security-group}
MacAddress         : 0a:e9:a6:19:4c:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-107.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.107
PrivateIpAddresses : {ip-10-0-0-107.us-west-2.compute.internal}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : in-use
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
**예제 2: 이 예제에서는 모든 네트워크 인터페이스를 설명합니다.**  

```
Get-EC2NetworkInterface
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeNetworkInterfaces](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribePlacementGroups` 사용
<a name="example_ec2_DescribePlacementGroups_section"></a>

다음 코드 예시는 `DescribePlacementGroups`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**모든 배치 그룹 설명**  
이 예시 명령은 모든 배치 그룹을 설명합니다.  
명령:  

```
aws ec2 describe-placement-groups
```
출력:  

```
{
    "PlacementGroups": [
        {
            "GroupName": "my-cluster",
            "State": "available",
            "Strategy": "cluster"
        },
        ...
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribePlacementGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-placement-groups.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 배치 그룹을 설명합니다.**  

```
Get-EC2PlacementGroup -GroupName my-placement-group
```
**출력:**  

```
GroupName             State        Strategy
---------             -----        --------
my-placement-group    available    cluster
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribePlacementGroups](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 배치 그룹을 설명합니다.**  

```
Get-EC2PlacementGroup -GroupName my-placement-group
```
**출력:**  

```
GroupName             State        Strategy
---------             -----        --------
my-placement-group    available    cluster
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribePlacementGroups](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribePrefixLists` 사용
<a name="example_ec2_DescribePrefixLists_section"></a>

다음 코드 예시는 `DescribePrefixLists`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**접두사 목록 설명**  
이 예시에서는 리전에서 사용 가능한 모든 접두사 목록을 나열합니다.  
명령:  

```
aws ec2 describe-prefix-lists
```
출력:  

```
{
  "PrefixLists": [
    {
      "PrefixListName": "com.amazonaws.us-east-1.s3",
      "Cidrs": [
        "54.231.0.0/17"
      ],
      "PrefixListId": "pl-63a5400a"
    }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribePrefixLists](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-prefix-lists.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1:이 예제에서는 리전 AWS 서비스 에 대해 접두사 목록 형식으로 사용 가능한를 가져옵니다.**  

```
Get-EC2PrefixList
```
**출력:**  

```
Cidrs                                          PrefixListId PrefixListName
-----                                          ------------ --------------
{52.94.5.0/24, 52.119.240.0/21, 52.94.24.0/23} pl-6fa54006  com.amazonaws.eu-west-1.dynamodb
{52.218.0.0/17, 54.231.128.0/19}               pl-6da54004  com.amazonaws.eu-west-1.s3
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribePrefixLists](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제에서는 리전 AWS 서비스 에 대해 접두사 목록 형식으로 사용 가능한를 가져옵니다.**  

```
Get-EC2PrefixList
```
**출력:**  

```
Cidrs                                          PrefixListId PrefixListName
-----                                          ------------ --------------
{52.94.5.0/24, 52.119.240.0/21, 52.94.24.0/23} pl-6fa54006  com.amazonaws.eu-west-1.dynamodb
{52.218.0.0/17, 54.231.128.0/19}               pl-6da54004  com.amazonaws.eu-west-1.s3
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribePrefixLists](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeRegions` 함께 사용
<a name="example_ec2_DescribeRegions_section"></a>

다음 코드 예시는 `DescribeRegions`의 사용 방법을 보여 줍니다.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) Regions.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeRegions(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    std::cout << std::endl;

    return outcome.IsSuccess();

}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1  API 참조*의 [DescribeRegions](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeRegions)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 활성화된 모든 리전을 설명하는 방법**  
다음 `describe-regions` 예제에서는 계정에서 활성화된 모든 리전을 설명합니다.  

```
aws ec2 describe-regions
```
출력:  

```
{
    "Regions": [
        {
            "Endpoint": "ec2.eu-north-1.amazonaws.com",
            "RegionName": "eu-north-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-south-1.amazonaws.com",
            "RegionName": "ap-south-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-3.amazonaws.com",
            "RegionName": "eu-west-3",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-2.amazonaws.com",
            "RegionName": "eu-west-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-1.amazonaws.com",
            "RegionName": "eu-west-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-3.amazonaws.com",
            "RegionName": "ap-northeast-3",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-2.amazonaws.com",
            "RegionName": "ap-northeast-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-1.amazonaws.com",
            "RegionName": "ap-northeast-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.sa-east-1.amazonaws.com",
            "RegionName": "sa-east-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ca-central-1.amazonaws.com",
            "RegionName": "ca-central-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-southeast-1.amazonaws.com",
            "RegionName": "ap-southeast-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-southeast-2.amazonaws.com",
            "RegionName": "ap-southeast-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-central-1.amazonaws.com",
            "RegionName": "eu-central-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-east-1.amazonaws.com",
            "RegionName": "us-east-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-east-2.amazonaws.com",
            "RegionName": "us-east-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-west-1.amazonaws.com",
            "RegionName": "us-west-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-west-2.amazonaws.com",
            "RegionName": "us-west-2",
            "OptInStatus": "opt-in-not-required"
        }
    ]
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [리전 및 가용 영역](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)을 참조하세요.  
**예제 2: 이름에 특정 문자열이 포함된 엔드포인트가 있는 활성화된 리전을 설명하는 방법**  
다음 `describe-regions` 예제에서는 엔드포인트에 'us' 문자열이 포함된 활성화한 모든 리전을 설명합니다.  

```
aws ec2 describe-regions \
    --filters "Name=endpoint,Values=*us*"
```
출력:  

```
{
    "Regions": [
        {
            "Endpoint": "ec2.us-east-1.amazonaws.com",
            "RegionName": "us-east-1"
        },
        {
            "Endpoint": "ec2.us-east-2.amazonaws.com",
            "RegionName": "us-east-2"
        },
        {
            "Endpoint": "ec2.us-west-1.amazonaws.com",
            "RegionName": "us-west-1"
        },
        {
            "Endpoint": "ec2.us-west-2.amazonaws.com",
            "RegionName": "us-west-2"
        }
    ]
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [리전 및 가용 영역](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)을 참조하세요.  
**예제 3: 모든 리전을 설명하는 방법**  
다음 `describe-regions` 예제에서는 비활성화된 리전을 포함하여 사용 가능한 모든 리전을 설명합니다.  

```
aws ec2 describe-regions \
    --all-regions
```
출력:  

```
{
    "Regions": [
        {
            "Endpoint": "ec2.eu-north-1.amazonaws.com",
            "RegionName": "eu-north-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-south-1.amazonaws.com",
            "RegionName": "ap-south-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-3.amazonaws.com",
            "RegionName": "eu-west-3",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-2.amazonaws.com",
            "RegionName": "eu-west-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-1.amazonaws.com",
            "RegionName": "eu-west-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-3.amazonaws.com",
            "RegionName": "ap-northeast-3",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.me-south-1.amazonaws.com",
            "RegionName": "me-south-1",
            "OptInStatus": "not-opted-in"
        },
        {
            "Endpoint": "ec2.ap-northeast-2.amazonaws.com",
            "RegionName": "ap-northeast-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-1.amazonaws.com",
            "RegionName": "ap-northeast-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.sa-east-1.amazonaws.com",
            "RegionName": "sa-east-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ca-central-1.amazonaws.com",
            "RegionName": "ca-central-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-east-1.amazonaws.com",
            "RegionName": "ap-east-1",
            "OptInStatus": "not-opted-in"
        },
        {
            "Endpoint": "ec2.ap-southeast-1.amazonaws.com",
            "RegionName": "ap-southeast-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-southeast-2.amazonaws.com",
            "RegionName": "ap-southeast-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-central-1.amazonaws.com",
            "RegionName": "eu-central-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-east-1.amazonaws.com",
            "RegionName": "us-east-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-east-2.amazonaws.com",
            "RegionName": "us-east-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-west-1.amazonaws.com",
            "RegionName": "us-west-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-west-2.amazonaws.com",
            "RegionName": "us-west-2",
            "OptInStatus": "opt-in-not-required"
        }
    ]
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [리전 및 가용 영역](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)을 참조하세요.  
**예제 4: 리전 이름만 나열하는 방법**  
다음 `describe-regions` 예제에서는 `--query` 파라미터를 사용하여 출력을 필터링하고 리전 이름만 텍스트로 반환합니다.  

```
aws ec2 describe-regions \
    --all-regions \
    --query "Regions[].{Name:RegionName}" \
    --output text
```
출력:  

```
eu-north-1
ap-south-1
eu-west-3
eu-west-2
eu-west-1
ap-northeast-3
ap-northeast-2
me-south-1
ap-northeast-1
sa-east-1
ca-central-1
ap-east-1
ap-southeast-1
ap-southeast-2
eu-central-1
us-east-1
us-east-2
us-west-1
us-west-2
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [리전 및 가용 영역](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeRegions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-regions.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { DescribeRegionsCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * List all available AWS regions.
 * @param {{ regionNames: string[], includeOptInRegions: boolean }} options
 */
export const main = async ({ regionNames, includeOptInRegions }) => {
  const client = new EC2Client({});
  const command = new DescribeRegionsCommand({
    // By default this command will not show regions that require you to opt-in.
    // When AllRegions is true, even the regions that require opt-in will be returned.
    AllRegions: includeOptInRegions,
    // You can omit the Filters property if you want to get all regions.
    Filters: regionNames?.length
      ? [
          {
            Name: "region-name",
            // You can specify multiple values for a filter.
            // You can also use '*' as a wildcard. This will return all
            // of the regions that start with `us-east-`.
            Values: regionNames,
          },
        ]
      : undefined,
  });

  try {
    const { Regions } = await client.send(command);
    const regionsList = Regions.map((reg) => ` • ${reg.RegionName}`);
    console.log("Found regions:");
    console.log(regionsList.join("\n"));
  } catch (caught) {
    if (caught instanceof Error && caught.name === "DryRunOperation") {
      console.log(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript  API 참조*의 [DescribeRegions](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeRegionsCommand)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 사용 가능한 리전을 설명합니다.**  

```
Get-EC2Region
```
**출력:**  

```
Endpoint                            RegionName
--------                            ----------
ec2.eu-west-1.amazonaws.com         eu-west-1
ec2.ap-southeast-1.amazonaws.com    ap-southeast-1
ec2.ap-southeast-2.amazonaws.com    ap-southeast-2
ec2.eu-central-1.amazonaws.com      eu-central-1
ec2.ap-northeast-1.amazonaws.com    ap-northeast-1
ec2.us-east-1.amazonaws.com         us-east-1
ec2.sa-east-1.amazonaws.com         sa-east-1
ec2.us-west-1.amazonaws.com         us-west-1
ec2.us-west-2.amazonaws.com         us-west-2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeRegions](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 사용 가능한 리전을 설명합니다.**  

```
Get-EC2Region
```
**출력:**  

```
Endpoint                            RegionName
--------                            ----------
ec2.eu-west-1.amazonaws.com         eu-west-1
ec2.ap-southeast-1.amazonaws.com    ap-southeast-1
ec2.ap-southeast-2.amazonaws.com    ap-southeast-2
ec2.eu-central-1.amazonaws.com      eu-central-1
ec2.ap-northeast-1.amazonaws.com    ap-northeast-1
ec2.us-east-1.amazonaws.com         us-east-1
ec2.sa-east-1.amazonaws.com         sa-east-1
ec2.us-west-1.amazonaws.com         us-west-1
ec2.us-west-2.amazonaws.com         us-west-2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeRegions](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'aws-sdk-ec2'

# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @example
#   list_regions_endpoints(Aws::EC2::Client.new(region: 'us-west-2'))
def list_regions_endpoints(ec2_client)
  result = ec2_client.describe_regions
  # Enable pretty printing.
  max_region_string_length = 16
  max_endpoint_string_length = 33
  # Print header.
  print 'Region'
  print ' ' * (max_region_string_length - 'Region'.length)
  print "  Endpoint\n"
  print '-' * max_region_string_length
  print '  '
  print '-' * max_endpoint_string_length
  print "\n"
  # Print Regions and their endpoints.
  result.regions.each do |region|
    print region.region_name
    print ' ' * (max_region_string_length - region.region_name.length)
    print '  '
    print region.endpoint
    print "\n"
  end
end

# Displays a list of Amazon Elastic Compute Cloud (Amazon EC2)
# Availability Zones available to you depending on the AWS Region
# of the Amazon EC2 client.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @example
#   list_availability_zones(Aws::EC2::Client.new(region: 'us-west-2'))
def list_availability_zones(ec2_client)
  result = ec2_client.describe_availability_zones
  # Enable pretty printing.
  max_region_string_length = 16
  max_zone_string_length = 18
  max_state_string_length = 9
  # Print header.
  print 'Region'
  print ' ' * (max_region_string_length - 'Region'.length)
  print '  Zone'
  print ' ' * (max_zone_string_length - 'Zone'.length)
  print "  State\n"
  print '-' * max_region_string_length
  print '  '
  print '-' * max_zone_string_length
  print '  '
  print '-' * max_state_string_length
  print "\n"
  # Print Regions, Availability Zones, and their states.
  result.availability_zones.each do |zone|
    print zone.region_name
    print ' ' * (max_region_string_length - zone.region_name.length)
    print '  '
    print zone.zone_name
    print ' ' * (max_zone_string_length - zone.zone_name.length)
    print '  '
    print zone.state
    # Print any messages for this Availability Zone.
    if zone.messages.count.positive?
      print "\n"
      puts '  Messages for this zone:'
      zone.messages.each do |message|
        print "    #{message.message}\n"
      end
    end
    print "\n"
  end
end

# Example usage:
def run_me
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-regions-availability-zones.rb REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-regions-availability-zones.rb us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    region = ARGV[0]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts 'AWS Regions for Amazon EC2 that are available to you:'
  list_regions_endpoints(ec2_client)
  puts "\n\nAmazon EC2 Availability Zones that are available to you for AWS Region '#{region}':"
  list_availability_zones(ec2_client)
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby  API 참조*의 [DescribeRegions](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/DescribeRegions)를 참조하십시오.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
async fn show_regions(client: &Client) -> Result<(), Error> {
    let rsp = client.describe_regions().send().await?;

    println!("Regions:");
    for region in rsp.regions() {
        println!("  {}", region.region_name().unwrap());
    }

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DescribeRegions](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_regions)을 참조하십시오.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ec2->describeregions( ).                        " oo_result is returned for testing purposes. "
        DATA(lt_regions) = oo_result->get_regions( ).
        MESSAGE 'Retrieved information about Regions.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DescribeRegions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeRouteTables` 함께 사용
<a name="example_ec2_DescribeRouteTables_section"></a>

다음 코드 예시는 `DescribeRouteTables`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 
+  [Transit Gateway 시작하기](example_vpc_TransitGatewayGettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**라우팅 테이블 설명**  
다음 `describe-route-tables` 예시에서는 라우팅 테이블에 대한 세부 정보를 검색합니다.  

```
aws ec2 describe-route-tables
```
출력:  

```
{
    "RouteTables": [
        {
            "Associations": [
                {
                    "Main": true,
                    "RouteTableAssociationId": "rtbassoc-0df3f54e06EXAMPLE",
                    "RouteTableId": "rtb-09ba434c1bEXAMPLE"
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-09ba434c1bEXAMPLE",
            "Routes": [
                {
                    "DestinationCidrBlock": "10.0.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "0.0.0.0/0",
                    "NatGatewayId": "nat-06c018cbd8EXAMPLE",
                    "Origin": "CreateRoute",
                    "State": "blackhole"
                }
            ],
            "Tags": [],
            "VpcId": "vpc-0065acced4EXAMPLE",
            "OwnerId": "111122223333"
        },
        {
            "Associations": [
                {
                    "Main": true,
                    "RouteTableAssociationId": "rtbassoc-9EXAMPLE",
                    "RouteTableId": "rtb-a1eec7de"
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-a1eec7de",
            "Routes": [
                {
                    "DestinationCidrBlock": "172.31.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "0.0.0.0/0",
                    "GatewayId": "igw-fEXAMPLE",
                    "Origin": "CreateRoute",
                    "State": "active"
                }
            ],
            "Tags": [],
            "VpcId": "vpc-3EXAMPLE",
            "OwnerId": "111122223333"
        },
        {
            "Associations": [
                {
                    "Main": false,
                    "RouteTableAssociationId": "rtbassoc-0b100c28b2EXAMPLE",
                    "RouteTableId": "rtb-07a98f76e5EXAMPLE",
                    "SubnetId": "subnet-0d3d002af8EXAMPLE"
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-07a98f76e5EXAMPLE",
            "Routes": [
                {
                    "DestinationCidrBlock": "10.0.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "0.0.0.0/0",
                    "GatewayId": "igw-06cf664d80EXAMPLE",
                    "Origin": "CreateRoute",
                    "State": "active"
                }
            ],
            "Tags": [],
            "VpcId": "vpc-0065acced4EXAMPLE",
            "OwnerId": "111122223333"
        }
    ]
}
```
자세한 내용은 *AWS VPC 사용 설명서*의 [라우팅 테이블 작업](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html#WorkWithRouteTables)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeRouteTables](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-route-tables.html) 섹션을 참조하세요.

------
#### [ PHP ]

**SDK for PHP**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * @param array $routeTableIds
     * @param array $filters
     * @return array
     */
    public function describeRouteTables(array $routeTableIds = [], array $filters = []): array
    {
        $parameters = [];
        if($routeTableIds){
            $parameters['RouteTableIds'] = $routeTableIds;
        }
        if($filters){
            $parameters['Filters'] = $filters;
        }
        try {
            $paginator = $this->ec2Client->getPaginator("DescribeRouteTables", $parameters);
            $contents = [];
            foreach ($paginator as $result) {
                foreach ($result['RouteTables'] as $object) {
                    $contents[] = $object['RouteTableId'];
                }
            }
        }catch (Ec2Exception $caught){
            echo "There was a problem paginating the results of DescribeRouteTables: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
        return $contents;
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [DescribeRouteTables](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/DescribeRouteTables)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 모든 라우팅 테이블을 설명합니다.**  

```
Get-EC2RouteTable
```
**출력:**  

```
DestinationCidrBlock    : 10.0.0.0/16
DestinationPrefixListId :
GatewayId               : local
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRouteTable
State                   : active
VpcPeeringConnectionId  :

DestinationCidrBlock    : 0.0.0.0/0
DestinationPrefixListId :
GatewayId               : igw-1a2b3c4d
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRoute
State                   : active
VpcPeeringConnectionId  :
```
**예제 2: 이 예제에서는 지정된 라우팅 테이블에 대한 세부 정보를 반환합니다.**  

```
Get-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**예제 3: 이 예제에서는 지정된 VPC의 라우팅 테이블을 설명합니다.**  

```
Get-EC2RouteTable -Filter @{ Name="vpc-id"; Values="vpc-1a2b3c4d" }
```
**출력:**  

```
Associations    : {rtbassoc-12345678}
PropagatingVgws : {}
Routes          : {, }
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeRouteTables](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 모든 라우팅 테이블을 설명합니다.**  

```
Get-EC2RouteTable
```
**출력:**  

```
DestinationCidrBlock    : 10.0.0.0/16
DestinationPrefixListId :
GatewayId               : local
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRouteTable
State                   : active
VpcPeeringConnectionId  :

DestinationCidrBlock    : 0.0.0.0/0
DestinationPrefixListId :
GatewayId               : igw-1a2b3c4d
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRoute
State                   : active
VpcPeeringConnectionId  :
```
**예제 2: 이 예제에서는 지정된 라우팅 테이블에 대한 세부 정보를 반환합니다.**  

```
Get-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**예제 3: 이 예제에서는 지정된 VPC의 라우팅 테이블을 설명합니다.**  

```
Get-EC2RouteTable -Filter @{ Name="vpc-id"; Values="vpc-1a2b3c4d" }
```
**출력:**  

```
Associations    : {rtbassoc-12345678}
PropagatingVgws : {}
Routes          : {, }
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeRouteTables](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def describe_route_tables(self, vpc_ids: list[str]) -> None:
        """
        Displays information about the route tables in the specified VPC.

        :param vpc_ids: A list of VPC IDs.
        """
        try:
            response = self.ec2_client.describe_route_tables(
                Filters=[{"Name": "vpc-id", "Values": vpc_ids}]
            )
            pp(response["RouteTables"])
        except ClientError as err:
            logger.error(
                "Couldn't describe route tables for VPCs %s. Here's why: %s: %s",
                vpc_ids,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeRouteTables](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeRouteTables)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    " Create filter for VPC ID
    " iv_vpc_id = 'vpc-abc123'
    DATA lt_filters TYPE /aws1/cl_ec2filter=>tt_filterlist.
    APPEND NEW /aws1/cl_ec2filter(
      iv_name = 'vpc-id'
      it_values = VALUE /aws1/cl_ec2valuestringlist_w=>tt_valuestringlist(
        ( NEW /aws1/cl_ec2valuestringlist_w( iv_vpc_id ) )
      )
    ) TO lt_filters.

    TRY.
        oo_result = lo_ec2->describeroutetables( it_filters = lt_filters ).             " oo_result is returned for testing purposes. "
        DATA(lt_route_tables) = oo_result->get_routetables( ).
        MESSAGE 'Retrieved information about route tables.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 SDK for SAP ABAP API 참조의 [DescribeRouteTables](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요. *AWS * 

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeScheduledInstanceAvailability` 사용
<a name="example_ec2_DescribeScheduledInstanceAvailability_section"></a>

다음 코드 예시는 `DescribeScheduledInstanceAvailability`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**사용 가능한 일정 설명**  
이 예시에서는 지정된 날짜부터 매주 일요일에 발생하는 일정을 설명합니다.  
명령:  

```
aws ec2 describe-scheduled-instance-availability --recurrence Frequency=Weekly,Interval=1,OccurrenceDays=[1] --first-slot-start-time-range EarliestTime=2016-01-31T00:00:00Z,LatestTime=2016-01-31T04:00:00Z
```
출력:  

```
{
  "ScheduledInstanceAvailabilitySet": [
    {
        "AvailabilityZone": "us-west-2b",
        "TotalScheduledInstanceHours": 1219,
        "PurchaseToken": "eyJ2IjoiMSIsInMiOjEsImMiOi...",
        "MinTermDurationInDays": 366,
        "AvailableInstanceCount": 20,
        "Recurrence": {
            "OccurrenceDaySet": [
                1
            ],
            "Interval": 1,
            "Frequency": "Weekly",
            "OccurrenceRelativeToEnd": false
        },
        "Platform": "Linux/UNIX",
        "FirstSlotStartTime": "2016-01-31T00:00:00Z",
        "MaxTermDurationInDays": 366,
        "SlotDurationInHours": 23,
        "NetworkPlatform": "EC2-VPC",
        "InstanceType": "c4.large",
        "HourlyPrice": "0.095"
    },
    ...
  ]
}
```
결과를 좁히려면 운영 체제, 네트워크 및 인스턴스 유형을 지정하는 필터를 추가할 수 있습니다.  
명령:  
--filters Name=platform,Values=Linux/UNIX Name=network-platform,Values=EC2-VPC Name=instance-type,Values=c4.large  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeScheduledInstanceAvailability](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-scheduled-instance-availability.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 날짜부터 매주 일요일에 발생하는 일정을 설명합니다.**  

```
Get-EC2ScheduledInstanceAvailability -Recurrence_Frequency Weekly -Recurrence_Interval 1 -Recurrence_OccurrenceDay 1 -FirstSlotStartTimeRange_EarliestTime 2016-01-31T00:00:00Z -FirstSlotStartTimeRange_LatestTime 2016-01-31T04:00:00Z
```
**출력:**  

```
AvailabilityZone            : us-west-2b
AvailableInstanceCount      : 20
FirstSlotStartTime          : 1/31/2016 8:00:00 AM
HourlyPrice                 : 0.095
InstanceType                : c4.large
MaxTermDurationInDays       : 366
MinTermDurationInDays       : 366
NetworkPlatform             : EC2-VPC
Platform                    : Linux/UNIX
PurchaseToken               : eyJ2IjoiMSIsInMiOjEsImMiOi...
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
SlotDurationInHours         : 23
TotalScheduledInstanceHours : 1219

...
```
**예제 2: 결과의 범위를 좁히려면 운영 체제, 네트워크, 인스턴스 유형과 같은 기준에 대한 필터를 추가할 수 있습니다.**  

```
-Filter @{ Name="platform";Values="Linux/UNIX" },@{ Name="network-platform";Values="EC2-VPC" },@{ Name="instance-type";Values="c4.large" }
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeScheduledInstanceAvailability](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 날짜부터 매주 일요일에 발생하는 일정을 설명합니다.**  

```
Get-EC2ScheduledInstanceAvailability -Recurrence_Frequency Weekly -Recurrence_Interval 1 -Recurrence_OccurrenceDay 1 -FirstSlotStartTimeRange_EarliestTime 2016-01-31T00:00:00Z -FirstSlotStartTimeRange_LatestTime 2016-01-31T04:00:00Z
```
**출력:**  

```
AvailabilityZone            : us-west-2b
AvailableInstanceCount      : 20
FirstSlotStartTime          : 1/31/2016 8:00:00 AM
HourlyPrice                 : 0.095
InstanceType                : c4.large
MaxTermDurationInDays       : 366
MinTermDurationInDays       : 366
NetworkPlatform             : EC2-VPC
Platform                    : Linux/UNIX
PurchaseToken               : eyJ2IjoiMSIsInMiOjEsImMiOi...
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
SlotDurationInHours         : 23
TotalScheduledInstanceHours : 1219

...
```
**예제 2: 결과의 범위를 좁히려면 운영 체제, 네트워크, 인스턴스 유형과 같은 기준에 대한 필터를 추가할 수 있습니다.**  

```
-Filter @{ Name="platform";Values="Linux/UNIX" },@{ Name="network-platform";Values="EC2-VPC" },@{ Name="instance-type";Values="c4.large" }
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeScheduledInstanceAvailability](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeScheduledInstances` 사용
<a name="example_ec2_DescribeScheduledInstances_section"></a>

다음 코드 예시는 `DescribeScheduledInstances`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**정기 인스턴스 설명**  
이 예시에서는 지정된 정기 인스턴스를 설명합니다.  
명령:  

```
aws ec2 describe-scheduled-instances --scheduled-instance-ids sci-1234-1234-1234-1234-123456789012
```
출력:  

```
{
  "ScheduledInstanceSet": [
      {
          "AvailabilityZone": "us-west-2b",
          "ScheduledInstanceId": "sci-1234-1234-1234-1234-123456789012",
          "HourlyPrice": "0.095",
          "CreateDate": "2016-01-25T21:43:38.612Z",
          "Recurrence": {
              "OccurrenceDaySet": [
                  1
              ],
              "Interval": 1,
              "Frequency": "Weekly",
              "OccurrenceRelativeToEnd": false,
              "OccurrenceUnit": ""
          },
          "Platform": "Linux/UNIX",
          "TermEndDate": "2017-01-31T09:00:00Z",
          "InstanceCount": 1,
          "SlotDurationInHours": 32,
          "TermStartDate": "2016-01-31T09:00:00Z",
          "NetworkPlatform": "EC2-VPC",
          "TotalScheduledInstanceHours": 1696,
          "NextSlotStartTime": "2016-01-31T09:00:00Z",
          "InstanceType": "c4.large"
      }
  ]
}
```
이 예시에서는 모든 정기 인스턴스를 설명합니다.  
명령:  

```
aws ec2 describe-scheduled-instances
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeScheduledInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-scheduled-instances.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 일정이 예약된 지정된 인스턴스를 설명합니다.**  

```
Get-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012
```
**출력:**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
**예제 2: 이 예제에서는 일정이 예약된 모든 인스턴스를 설명합니다.**  

```
Get-EC2ScheduledInstance
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeScheduledInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 일정이 예약된 지정된 인스턴스를 설명합니다.**  

```
Get-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012
```
**출력:**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
**예제 2: 이 예제에서는 일정이 예약된 모든 인스턴스를 설명합니다.**  

```
Get-EC2ScheduledInstance
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeSecurityGroups` 함께 사용
<a name="example_ec2_DescribeSecurityGroups_section"></a>

다음 코드 예시는 `DescribeSecurityGroups`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Retrieve information for one or all Amazon EC2 security group.
    /// </summary>
    /// <param name="groupId">The optional Id of a specific Amazon EC2 security group.</param>
    /// <returns>A list of security group information.</returns>
    public async Task<List<SecurityGroup>> DescribeSecurityGroups(string groupId)
    {
        try
        {
            var securityGroups = new List<SecurityGroup>();
            var request = new DescribeSecurityGroupsRequest();

            if (!string.IsNullOrEmpty(groupId))
            {
                var groupIds = new List<string> { groupId };
                request.GroupIds = groupIds;
            }

            var paginatorForSecurityGroups =
                _amazonEC2.Paginators.DescribeSecurityGroups(request);

            await foreach (var securityGroup in paginatorForSecurityGroups.SecurityGroups)
            {
                securityGroups.Add(securityGroup);
            }

            return securityGroups;

        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidGroup.NotFound")
            {
                _logger.LogError(
                    $"A security group {groupId} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while listing security groups. {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Display the information returned by the call to
    /// DescribeSecurityGroupsAsync.
    /// </summary>
    /// <param name="securityGroup">A list of security group information.</param>
    public void DisplaySecurityGroupInfoAsync(SecurityGroup securityGroup)
    {
        Console.WriteLine($"{securityGroup.GroupName}");
        Console.WriteLine("Ingress permissions:");
        securityGroup.IpPermissions.ForEach(permission =>
        {
            Console.WriteLine($"\tFromPort: {permission.FromPort}");
            Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}");

            Console.Write($"\tIpv4Ranges: ");
            permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); });

            Console.WriteLine($"\n\tIpv6Ranges:");
            permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });

            Console.Write($"\n\tPrefixListIds: ");
            permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} "));

            Console.WriteLine($"\n\tTo Port: {permission.ToPort}");
        });
        Console.WriteLine("Egress permissions:");
        securityGroup.IpPermissionsEgress.ForEach(permission =>
        {
            Console.WriteLine($"\tFromPort: {permission.FromPort}");
            Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}");

            Console.Write($"\tIpv4Ranges: ");
            permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); });

            Console.WriteLine($"\n\tIpv6Ranges:");
            permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });

            Console.Write($"\n\tPrefixListIds: ");
            permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} "));

            Console.WriteLine($"\n\tTo Port: {permission.ToPort}");
        });
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeSecurityGroups)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_describe_security_groups
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups.
#
# Parameters:
#       -g security_group_id - The ID of the security group to describe (optional).
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_security_groups() {
  local security_group_id response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_security_groups"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups."
    echo "  -g security_group_id - The ID of the security group to describe (optional)."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "g:h" option; do
    case "${option}" in
      g) security_group_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local query="SecurityGroups[*].[GroupName, GroupId, VpcId, IpPermissions[*].[IpProtocol, FromPort, ToPort, IpRanges[*].CidrIp]]"

  if [[ -n "$security_group_id" ]]; then
    response=$(aws ec2 describe-security-groups --group-ids "$security_group_id" --query "${query}" --output text)
  else
    response=$(aws ec2 describe-security-groups --query "${query}" --output text)
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports describe-security-groups operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeSecurityGroups)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) security groups, or a specific group.
/*!
  \param groupID: A group ID, ignored if empty.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeSecurityGroups(const Aws::String &groupID,
                                         const Aws::Client::ClientConfiguration &clientConfiguration) {
    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());

    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeSecurityGroups)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 보안 그룹 설명하는 방법**  
다음 `describe-security-groups` 예제에서는 지정된 보안 그룹을 설명합니다.  

```
aws ec2 describe-security-groups \
    --group-ids sg-903004f8
```
출력:  

```
{
    "SecurityGroups": [
        {
            "IpPermissionsEgress": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": [],
                    "PrefixListIds": []
                }
            ],
            "Description": "My security group",
            "Tags": [
                {
                    "Value": "SG1",
                    "Key": "Name"
                }
            ],
            "IpPermissions": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [],
                    "UserIdGroupPairs": [
                        {
                            "UserId": "123456789012",
                            "GroupId": "sg-903004f8"
                        }
                    ],
                    "PrefixListIds": []
                },
                {
                    "PrefixListIds": [],
                    "FromPort": 22,
                    "IpRanges": [
                        {
                            "Description": "Access from NY office",
                            "CidrIp": "203.0.113.0/24"
                        }
                    ],
                    "ToPort": 22,
                    "IpProtocol": "tcp",
                    "UserIdGroupPairs": []
                    }
            ],
            "GroupName": "MySecurityGroup",
            "VpcId": "vpc-1a2b3c4d",
            "OwnerId": "123456789012",
            "GroupId": "sg-903004f8",
        }
    ]
}
```
**예제 2: 특정 규칙이 있는 보안 그룹을 설명하는 방법**  
다음 `describe-security-groups` 예시에서는 필터를 사용하여 SSH 트래픽을 허용하는 규칙(포트 22)과 모든 주소(`0.0.0.0/0`)의 트래픽을 허용하는 규칙이 있는 보안 그룹으로 결과 범위를 지정합니다. 이 예제에서는 `--query` 파라미터를 사용하여 보안 그룹의 이름만 표시합니다. 보안 그룹이 결과에 반환될 모든 필터와 일치해야 하지만 단일 규칙이 모든 필터와 일치할 필요는 없습니다. 예를 들어 출력은 특정 IP 주소의 SSH 트래픽을 허용하는 규칙과 모든 주소의 HTTP 트래픽을 허용하는 다른 규칙이 포함된 보안 그룹을 반환합니다.  

```
aws ec2 describe-security-groups \
    --filters Name=ip-permission.from-port,Values=22 Name=ip-permission.to-port,Values=22 Name=ip-permission.cidr,Values='0.0.0.0/0' \
    --query "SecurityGroups[*].[GroupName]" \
    --output text
```
출력:  

```
default
my-security-group
web-servers
launch-wizard-1
```
**예제 3: 태그를 기반으로 보안 그룹을 설명하는 방법**  
다음 `describe-security-groups` 예제에서는 필터를 사용하여 결과 범위를 보안 그룹 이름에 `test`가 포함되고 `Test=To-delete` 태그가 있는 보안 그룹으로 지정합니다. 이 예제에서는 `--query` 파라미터를 사용하여 보안 그룹의 이름 및 ID만 표시합니다.  

```
aws ec2 describe-security-groups \
    --filters Name=group-name,Values=*test* Name=tag:Test,Values=To-delete \
    --query "SecurityGroups[*].{Name:GroupName,ID:GroupId}"
```
출력:  

```
[
    {
        "Name": "testfornewinstance",
        "ID": "sg-33bb22aa"
    },
    {
        "Name": "newgrouptest",
        "ID": "sg-1a2b3c4d"
    }
]
```
태그 필터를 사용하는 추가 예제는 *Amazon EC2 사용 설명서*에서 [태그 작업](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeSecurityGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-security-groups.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Asynchronously describes the security groups for the specified group ID.
     *
     * @param groupName the name of the security group to describe
     * @return a {@link CompletableFuture} that represents the asynchronous operation
     *         of describing the security groups. The future will complete with a
     *         {@link DescribeSecurityGroupsResponse} object that contains the
     *         security group information.
     */
    public CompletableFuture<String> describeSecurityGroupArnByNameAsync(String groupName) {
        DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder()
            .groupNames(groupName)
            .build();

        DescribeSecurityGroupsPublisher paginator = getAsyncClient().describeSecurityGroupsPaginator(request);
        AtomicReference<String> groupIdRef = new AtomicReference<>();
        return paginator.subscribe(response -> {
            response.securityGroups().stream()
                .filter(securityGroup -> securityGroup.groupName().equals(groupName))
                .findFirst()
                .ifPresent(securityGroup -> groupIdRef.set(securityGroup.groupId()));
        }).thenApply(v -> {
            String groupId = groupIdRef.get();
            if (groupId == null) {
                throw new RuntimeException("No security group found with the name: " + groupName);
            }
            return groupId;
        }).exceptionally(ex -> {
            logger.info("Failed to describe security group: " + ex.getMessage());
            throw new RuntimeException("Failed to describe security group", ex);
        });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeSecurityGroups)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { DescribeSecurityGroupsCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Describes the specified security groups or all of your security groups.
 * @param {{ groupIds: string[] }} options
 */
export const main = async ({ groupIds = [] }) => {
  const client = new EC2Client({});
  const command = new DescribeSecurityGroupsCommand({
    GroupIds: groupIds,
  });

  try {
    const { SecurityGroups } = await client.send(command);
    const sgList = SecurityGroups.map(
      (sg) => `• ${sg.GroupName} (${sg.GroupId}): ${sg.Description}`,
    ).join("\n");
    if (sgList.length) {
      console.log(`Security groups:\n${sgList}`);
    } else {
      console.log("No security groups found.");
    }
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidGroupId.Malformed") {
      console.warn(`${caught.message}. Please provide a valid GroupId.`);
    } else if (
      caught instanceof Error &&
      caught.name === "InvalidGroup.NotFound"
    ) {
      console.warn(caught.message);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DescribeSecurityGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSecurityGroupsCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun describeEC2SecurityGroups(groupId: String) {
    val request =
        DescribeSecurityGroupsRequest {
            groupIds = listOf(groupId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeSecurityGroups(request)
        response.securityGroups?.forEach { group ->
            println("Found Security Group with id ${group.groupId}, vpc id ${group.vpcId} and description ${group.description}")
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DescribeSecurityGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 VPC에 지정된 보안 그룹을 설명합니다. VPC에 속한 보안 그룹으로 작업할 때는 이름(-GroupName 파라미터)이 아닌 보안 그룹 ID(-GroupId 파라미터)를 사용하여 그룹을 참조해야 합니다.**  

```
Get-EC2SecurityGroup -GroupId sg-12345678
```
**출력:**  

```
Description         : default VPC security group
GroupId             : sg-12345678
GroupName           : default
IpPermissions       : {Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {Amazon.EC2.Model.IpPermission}
OwnerId             : 123456789012
Tags                : {}
VpcId               : vpc-12345678
```
**예제 2: 이 예제에서는 EC2-Classic에 지정된 보안 그룹을 설명합니다. EC2-Classic의 보안 그룹으로 작업할 때 그룹 이름(-GroupName 파라미터) 또는 그룹 ID(-GroupId 파라미터)를 사용하여 보안 그룹을 참조할 수 있습니다.**  

```
Get-EC2SecurityGroup -GroupName my-security-group
```
**출력:**  

```
Description         : my security group
GroupId             : sg-45678901
GroupName           : my-security-group
IpPermissions       : {Amazon.EC2.Model.IpPermission, Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {}
OwnerId             : 123456789012
Tags                : {}
VpcId               :
```
**예제 3: 이 예제에서는 vpc-0fc1ff23456b789eb에 대한 모든 보안 그룹을 검색합니다.**  

```
Get-EC2SecurityGroup -Filter @{Name="vpc-id";Values="vpc-0fc1ff23456b789eb"}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSecurityGroups](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 VPC에 지정된 보안 그룹을 설명합니다. VPC에 속한 보안 그룹으로 작업할 때는 이름(-GroupName 파라미터)이 아닌 보안 그룹 ID(-GroupId 파라미터)를 사용하여 그룹을 참조해야 합니다.**  

```
Get-EC2SecurityGroup -GroupId sg-12345678
```
**출력:**  

```
Description         : default VPC security group
GroupId             : sg-12345678
GroupName           : default
IpPermissions       : {Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {Amazon.EC2.Model.IpPermission}
OwnerId             : 123456789012
Tags                : {}
VpcId               : vpc-12345678
```
**예제 2: 이 예제에서는 EC2-Classic에 지정된 보안 그룹을 설명합니다. EC2-Classic의 보안 그룹으로 작업할 때 그룹 이름(-GroupName 파라미터) 또는 그룹 ID(-GroupId 파라미터)를 사용하여 보안 그룹을 참조할 수 있습니다.**  

```
Get-EC2SecurityGroup -GroupName my-security-group
```
**출력:**  

```
Description         : my security group
GroupId             : sg-45678901
GroupName           : my-security-group
IpPermissions       : {Amazon.EC2.Model.IpPermission, Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {}
OwnerId             : 123456789012
Tags                : {}
VpcId               :
```
**예제 3: 이 예제에서는 vpc-0fc1ff23456b789eb에 대한 모든 보안 그룹을 검색합니다.**  

```
Get-EC2SecurityGroup -Filter @{Name="vpc-id";Values="vpc-0fc1ff23456b789eb"}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class SecurityGroupWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions."""

    def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None):
        """
        Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param security_group: The ID of a security group to manage. This is a high-level identifier
                               that represents the security group.
        """
        self.ec2_client = ec2_client
        self.security_group = security_group

    @classmethod
    def from_client(cls) -> "SecurityGroupWrapper":
        """
        Creates a SecurityGroupWrapper instance with a default EC2 client.

        :return: An instance of SecurityGroupWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def describe(self, security_group_id: Optional[str] = None) -> bool:
        """
        Displays information about the specified security group or all security groups if no ID is provided.

        :param security_group_id: The ID of the security group to describe.
                                  If None, an open search is performed to describe all security groups.
        :returns: True if the description is successful.
        :raises ClientError: If there is an error describing the security group(s), such as an invalid security group ID.
        """
        try:
            paginator = self.ec2_client.get_paginator("describe_security_groups")

            if security_group_id is None:
                # If no ID is provided, return all security groups.
                page_iterator = paginator.paginate()
            else:
                page_iterator = paginator.paginate(GroupIds=[security_group_id])

            for page in page_iterator:
                for security_group in page["SecurityGroups"]:
                    print(f"Security group: {security_group['GroupName']}")
                    print(f"\tID: {security_group['GroupId']}")
                    print(f"\tVPC: {security_group['VpcId']}")
                    if security_group["IpPermissions"]:
                        print("Inbound permissions:")
                        pp(security_group["IpPermissions"])

            return True
        except ClientError as err:
            logger.error("Failed to describe security group(s).")
            if err.response["Error"]["Code"] == "InvalidGroup.NotFound":
                logger.error(
                    f"Security group {security_group_id} does not exist "
                    f"because the specified security group ID was not found."
                )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSecurityGroups)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
async fn show_security_groups(client: &aws_sdk_ec2::Client, group_ids: Vec<String>) {
    let response = client
        .describe_security_groups()
        .set_group_ids(Some(group_ids))
        .send()
        .await;

    match response {
        Ok(output) => {
            for group in output.security_groups() {
                println!(
                    "Found Security Group {} ({}), vpc id {} and description {}",
                    group.group_name().unwrap_or("unknown"),
                    group.group_id().unwrap_or("id-unknown"),
                    group.vpc_id().unwrap_or("vpcid-unknown"),
                    group.description().unwrap_or("(none)")
                );
            }
        }
        Err(err) => {
            let err = err.into_service_error();
            let meta = err.meta();
            let message = meta.message().unwrap_or("unknown");
            let code = meta.code().unwrap_or("unknown");
            eprintln!("Error listing EC2 Security Groups: ({code}) {message}");
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DescribeSecurityGroups](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_security_groups)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        DATA lt_group_ids TYPE /aws1/cl_ec2groupidstrlist_w=>tt_groupidstringlist.
        APPEND NEW /aws1/cl_ec2groupidstrlist_w( iv_value = iv_group_id ) TO lt_group_ids.
        oo_result = lo_ec2->describesecuritygroups( it_groupids = lt_group_ids ).         " oo_result is returned for testing purposes. "
        DATA(lt_security_groups) = oo_result->get_securitygroups( ).
        MESSAGE 'Retrieved information about security groups.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DescribeSecurityGroups](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
`describeSecurityGroupsPaginated()`로 페이지 매김을 사용합니다.  

```
import AWSEC2

    /// Return an array of strings giving the names of every security group
    /// the user is a member of.
    ///
    /// - Parameter ec2Client: The `EC2Client` to use when calling
    ///   `describeSecurityGroupsPaginated()`.
    ///
    /// - Returns: An array of strings giving the names of every security
    ///   group the user is a member of.
    func getSecurityGroupNames(ec2Client: EC2Client) async -> [String] {
        let pages = ec2Client.describeSecurityGroupsPaginated(
            input: DescribeSecurityGroupsInput()
        )

        var groupNames: [String] = []

        do {
            for try await page in pages {
                guard let groups = page.securityGroups else {
                    print("*** Error: No groups returned.")
                    continue
                }

                for group in groups {
                    groupNames.append(group.groupName ?? "<unknown>")
                }
            }
        } catch {
            print("*** Error: \(error.localizedDescription)")
        }

        return groupNames
    }
```
페이지 매김을 사용하지 않는 예제입니다.  

```
import AWSEC2

    func describeSecurityGroups(groupId: String) async -> Bool {
        do {
            let output = try await ec2Client.describeSecurityGroups(
                input: DescribeSecurityGroupsInput(
                    groupIds: [groupId]
                )
            )

            guard let securityGroups = output.securityGroups else {
                print("No security groups found.")
                return true
            }

            for group in securityGroups {
                print("Group \(group.groupId ?? "<unknown>") found with VPC \(group.vpcId ?? "<unknown>")")
            }
            return true
        } catch {
            print("*** Error getting security group details: \(error.localizedDescription)")
            return false
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DescribeSecurityGroups](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describesecuritygroups(input:))을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeSnapshotAttribute` 사용
<a name="example_ec2_DescribeSnapshotAttribute_section"></a>

다음 코드 예시는 `DescribeSnapshotAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스냅샷의 스냅샷 속성 설명**  
다음 `describe-snapshot-attribute` 예시에서는 스냅샷이 공유되는 계정을 나열합니다.  

```
aws ec2 describe-snapshot-attribute \
    --snapshot-id snap-01234567890abcedf \
    --attribute createVolumePermission
```
출력:  

```
{
    "SnapshotId": "snap-01234567890abcedf",
    "CreateVolumePermissions": [
        {
            "UserId": "123456789012"
        }
    ]
}
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*의 [Amazon EBS 스냅샷 공유](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html#share-unencrypted-snapshot)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeSnapshotAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-snapshot-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스냅샷의 지정된 속성을 설명합니다.**  

```
Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute ProductCodes
```
**출력:**  

```
CreateVolumePermissions    ProductCodes    SnapshotId
-----------------------    ------------    ----------
{}                         {}              snap-12345678
```
**예제 2: 이 예제에서는 지정된 스냅샷의 지정된 속성을 설명합니다.**  

```
(Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission).CreateVolumePermissions
```
**출력:**  

```
Group    UserId
-----    ------
all
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSnapshotAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스냅샷의 지정된 속성을 설명합니다.**  

```
Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute ProductCodes
```
**출력:**  

```
CreateVolumePermissions    ProductCodes    SnapshotId
-----------------------    ------------    ----------
{}                         {}              snap-12345678
```
**예제 2: 이 예제에서는 지정된 스냅샷의 지정된 속성을 설명합니다.**  

```
(Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission).CreateVolumePermissions
```
**출력:**  

```
Group    UserId
-----    ------
all
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeSnapshots` 함께 사용
<a name="example_ec2_DescribeSnapshots_section"></a>

다음 코드 예시는 `DescribeSnapshots`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 스냅샷을 설명하는 방법**  
다음 `describe-snapshots` 예제에서는 지정된 스냅샷을 설명합니다.  

```
aws ec2 describe-snapshots \
    --snapshot-ids snap-1234567890abcdef0
```
출력:  

```
{
    "Snapshots": [
        {
            "Description": "This is my snapshot",
            "Encrypted": false,
            "VolumeId": "vol-049df61146c4d7901",
            "State": "completed",
            "VolumeSize": 8,
            "StartTime": "2019-02-28T21:28:32.000Z",
            "Progress": "100%",
            "OwnerId": "012345678910",
            "SnapshotId": "snap-01234567890abcdef",
            "Tags": [
                {
                    "Key": "Stack",
                    "Value": "test"
                }
            ]
        }
    ]
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [Amazon EBS 스냅샷](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html)을 참조하세요.  
**예제 2: 필터를 기반으로 스냅샷을 설명하는 방법**  
다음 `describe-snapshots` 예제에서는 필터를 사용하여 `pending` 상태의 AWS 계정이 소유한 스냅샷으로 결과의 범위를 지정합니다. 이 예제에서는 `--query` 파라미터를 사용하여 스냅샷 ID 및 스냅샷이 시작된 시간만 표시합니다.  

```
aws ec2 describe-snapshots \
    --owner-ids self \
    --filters Name=status,Values=pending \
    --query "Snapshots[*].{ID:SnapshotId,Time:StartTime}"
```
출력:  

```
[
    {
        "ID": "snap-1234567890abcdef0",
        "Time": "2019-08-04T12:48:18.000Z"
    },
    {
        "ID": "snap-066877671789bd71b",
        "Time": "2019-08-04T02:45:16.000Z
    },
    ...
]
```
다음 `describe-snapshots` 예제에서는 필터를 사용하여 결과 범위를 지정된 리전에서 생성된 스냅샷으로 지정합니다. 이 예제에서는 `--query` 파라미터를 사용하여 스냅샷 ID만 표시합니다.  

```
aws ec2 describe-snapshots \
    --filters Name=volume-id,Values=049df61146c4d7901 \
    --query "Snapshots[*].[SnapshotId]" \
    --output text
```
출력:  

```
snap-1234567890abcdef0
snap-08637175a712c3fb9
...
```
필터를 사용하는 추가 예제는 *Amazon EC2 사용 설명서*에서 [리소스 나열 및 필터링](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)을 참조하세요.  
**예제 3: 태그를 기반으로 스냅샷을 설명하는 방법**  
다음 `describe-snapshots` 예제에서는 태그 필터를 사용하여 결과 범위를 `Stack=Prod` 태그가 있는 스냅샷으로 지정합니다.  

```
aws ec2 describe-snapshots \
    --filters Name=tag:Stack,Values=prod
```
`describe-snapshots` 출력 예제는 예제 1을 참조하세요.  
태그 필터를 사용하는 추가 예제는 *Amazon EC2 사용 설명서*에서 [태그 작업](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)을 참조하세요.  
**예제 4: 수명에 기반하여 스냅샷을 설명하는 방법**  
다음 `describe-snapshots` 예제에서는 JMESPath 표현식을 사용하여 지정된 날짜 이전에 AWS 계정에서 생성한 모든 스냅샷을 설명합니다. 스냅샷 ID만 표시합니다.  

```
aws ec2 describe-snapshots \
    --owner-ids 012345678910 \
    --query "Snapshots[?(StartTime<='2020-03-31')].[SnapshotId]"
```
필터를 사용하는 추가 예제는 *Amazon EC2 사용 설명서*에서 [리소스 나열 및 필터링](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)을 참조하세요.  
**예제 5: 아카이브된 스냅샷만 보는 방법**  
다음 `describe-snapshots` 예제에서는 아카이브 티어에 저장된 스냅샷만 나열합니다.  

```
aws ec2 describe-snapshots \
    --filters "Name=storage-tier,Values=archive"
```
출력:  

```
{
    "Snapshots": [
        {
            "Description": "Snap A",
            "Encrypted": false,
            "VolumeId": "vol-01234567890aaaaaa",
            "State": "completed",
            "VolumeSize": 8,
            "StartTime": "2021-09-07T21:00:00.000Z",
            "Progress": "100%",
            "OwnerId": "123456789012",
            "SnapshotId": "snap-01234567890aaaaaa",
            "StorageTier": "archive",
            "Tags": []
        },
    ]
}
```
자세한 내용을 알아보려면 *Amazon Elastic Compute Cloud 사용 설명서*에서 [인스턴스 유형](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-snapshot-archiving.html#view-archived-snapshot)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-snapshots.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스냅샷을 설명합니다.**  

```
Get-EC2Snapshot -SnapshotId snap-12345678
```
**출력:**  

```
DataEncryptionKeyId :
Description         : Created by CreateImage(i-1a2b3c4d) for ami-12345678 from vol-12345678
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            : 100%
SnapshotId          : snap-12345678
StartTime           : 10/23/2014 6:01:28 AM
State               : completed
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 8
```
**예제 2: 이 예제에서는 'Name' 태그가 있는 스냅샷을 설명합니다.**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" }
```
**예제 3: 이 예제에서는 값이 'TestValue'인 'Name' 태그가 있는 스냅샷을 설명합니다.**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" -and $_.Tags.Value -eq "TestValue" }
```
**예제 4: 이 예제에서는 모든 스냅샷을 설명합니다.**  

```
Get-EC2Snapshot -Owner self
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSnapshots](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스냅샷을 설명합니다.**  

```
Get-EC2Snapshot -SnapshotId snap-12345678
```
**출력:**  

```
DataEncryptionKeyId :
Description         : Created by CreateImage(i-1a2b3c4d) for ami-12345678 from vol-12345678
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            : 100%
SnapshotId          : snap-12345678
StartTime           : 10/23/2014 6:01:28 AM
State               : completed
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 8
```
**예제 2: 이 예제에서는 'Name' 태그가 있는 스냅샷을 설명합니다.**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" }
```
**예제 3: 이 예제에서는 값이 'TestValue'인 'Name' 태그가 있는 스냅샷을 설명합니다.**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" -and $_.Tags.Value -eq "TestValue" }
```
**예제 4: 이 예제에서는 모든 스냅샷을 설명합니다.**  

```
Get-EC2Snapshot -Owner self
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ebs#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
스냅샷의 상태를 보여 줍니다.  

```
async fn show_state(client: &Client, id: &str) -> Result<(), Error> {
    let resp = client
        .describe_snapshots()
        .filters(Filter::builder().name("snapshot-id").values(id).build())
        .send()
        .await?;

    println!(
        "State: {}",
        resp.snapshots().first().unwrap().state().unwrap().as_ref()
    );

    Ok(())
}
```

```
async fn show_snapshots(client: &Client) -> Result<(), Error> {
    // "self" represents your account ID.
    // You can list the snapshots for any account by replacing
    // "self" with that account ID.
    let resp = client.describe_snapshots().owner_ids("self").send().await?;
    let snapshots = resp.snapshots();
    let length = snapshots.len();

    for snapshot in snapshots {
        println!(
            "ID:          {}",
            snapshot.snapshot_id().unwrap_or_default()
        );
        println!(
            "Description: {}",
            snapshot.description().unwrap_or_default()
        );
        println!("State:       {}", snapshot.state().unwrap().as_ref());
        println!();
    }

    println!();
    println!("Found {} snapshot(s)", length);
    println!();

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DescribeSnapshots](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_snapshots)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeSpotDatafeedSubscription` 사용
<a name="example_ec2_DescribeSpotDatafeedSubscription_section"></a>

다음 코드 예시는 `DescribeSpotDatafeedSubscription`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**계정에 대한 스팟 인스턴스 데이터 피드 구독 설명**  
이 예시 명령은 계정에 대한 데이터 피드를 설명합니다.  
명령:  

```
aws ec2 describe-spot-datafeed-subscription
```
출력:  

```
{
    "SpotDatafeedSubscription": {
        "OwnerId": "123456789012",
        "Prefix": "spotdata",
        "Bucket": "amzn-s3-demo-bucket",
        "State": "Active"
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeSpotDatafeedSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-datafeed-subscription.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 스팟 인스턴스 데이터 피드를 설명합니다.**  

```
Get-EC2SpotDatafeedSubscription
```
**출력:**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 스팟 인스턴스 데이터 피드를 설명합니다.**  

```
Get-EC2SpotDatafeedSubscription
```
**출력:**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeSpotFleetInstances` 사용
<a name="example_ec2_DescribeSpotFleetInstances_section"></a>

다음 코드 예시는 `DescribeSpotFleetInstances`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스팟 플릿과 연결된 스팟 인스턴스 설명**  
이 예시 명령은 지정된 스팟 플릿과 연결된 스팟 인스턴스를 나열합니다.  
명령:  

```
aws ec2 describe-spot-fleet-instances --spot-fleet-request-id sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
출력:  

```
{
  "ActiveInstances": [
      {
          "InstanceId": "i-1234567890abcdef0",
          "InstanceType": "m3.medium",
          "SpotInstanceRequestId": "sir-08b93456"
      },
      ...
  ],
  "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeSpotFleetInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-fleet-instances.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스팟 플릿 요청과 연결된 인스턴스를 설명합니다.**  

```
Get-EC2SpotFleetInstance -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
**출력:**  

```
InstanceId    InstanceType    SpotInstanceRequestId
----------    ------------    ---------------------
i-f089262a    c3.large        sir-12345678
i-7e8b24a4    c3.large        sir-87654321
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSpotFleetInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스팟 플릿 요청과 연결된 인스턴스를 설명합니다.**  

```
Get-EC2SpotFleetInstance -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
**출력:**  

```
InstanceId    InstanceType    SpotInstanceRequestId
----------    ------------    ---------------------
i-f089262a    c3.large        sir-12345678
i-7e8b24a4    c3.large        sir-87654321
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSpotFleetInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeSpotFleetRequestHistory` 사용
<a name="example_ec2_DescribeSpotFleetRequestHistory_section"></a>

다음 코드 예시는 `DescribeSpotFleetRequestHistory`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스팟 플릿 기록 설명**  
이 예시 명령은 지정된 시간부터 시작하여 지정된 스팟 플릿에 대한 기록을 반환합니다.  
명령:  

```
aws ec2 describe-spot-fleet-request-history --spot-fleet-request-id sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE --start-time 2015-05-26T00:00:00Z
```
다음 예시에서는 스팟 플릿에 대한 스팟 인스턴스 두 개를 성공적으로 실행한 결과를 보여줍니다.  
출력:  

```
{
  "HistoryRecords": [
      {
          "Timestamp": "2015-05-26T23:17:20.697Z",
          "EventInformation": {
              "EventSubType": "submitted"
          },
          "EventType": "fleetRequestChange"
      },
      {
          "Timestamp": "2015-05-26T23:17:20.873Z",
          "EventInformation": {
              "EventSubType": "active"
          },
          "EventType": "fleetRequestChange"
      },
      {
          "Timestamp": "2015-05-26T23:21:21.712Z",
          "EventInformation": {
              "InstanceId": "i-1234567890abcdef0",
              "EventSubType": "launched"
          },
          "EventType": "instanceChange"
      },
      {
          "Timestamp": "2015-05-26T23:21:21.816Z",
          "EventInformation": {
              "InstanceId": "i-1234567890abcdef1",
              "EventSubType": "launched"
          },
          "EventType": "instanceChange"
      }
  ],
  "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
  "NextToken": "CpHNsscimcV5oH7bSbub03CI2Qms5+ypNpNm+53MNlR0YcXAkp0xFlfKf91yVxSExmbtma3awYxMFzNA663ZskT0AHtJ6TCb2Z8bQC2EnZgyELbymtWPfpZ1ZbauVg+P+TfGlWxWWB/Vr5dk5d4LfdgA/DRAHUrYgxzrEXAMPLE=",
  "StartTime": "2015-05-26T00:00:00Z"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeSpotFleetRequestHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-fleet-request-history.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스팟 플릿 요청의 기록을 설명합니다.**  

```
Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z
```
**출력:**  

```
HistoryRecords     : {Amazon.EC2.Model.HistoryRecord, Amazon.EC2.Model.HistoryRecord...}
LastEvaluatedTime  : 12/26/2015 8:29:11 AM
NextToken          :
SpotFleetRequestId : sfr-088bc5f1-7e7b-451a-bd13-757f10672b93
StartTime          : 12/25/2015 8:00:00 AM
```

```
(Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z).HistoryRecords
```
**출력:**  

```
EventInformation                     EventType             Timestamp
----------------                     ---------             ---------
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:34 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:05 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSpotFleetRequestHistory](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스팟 플릿 요청의 기록을 설명합니다.**  

```
Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z
```
**출력:**  

```
HistoryRecords     : {Amazon.EC2.Model.HistoryRecord, Amazon.EC2.Model.HistoryRecord...}
LastEvaluatedTime  : 12/26/2015 8:29:11 AM
NextToken          :
SpotFleetRequestId : sfr-088bc5f1-7e7b-451a-bd13-757f10672b93
StartTime          : 12/25/2015 8:00:00 AM
```

```
(Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z).HistoryRecords
```
**출력:**  

```
EventInformation                     EventType             Timestamp
----------------                     ---------             ---------
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:34 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:05 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSpotFleetRequestHistory](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeSpotFleetRequests` 사용
<a name="example_ec2_DescribeSpotFleetRequests_section"></a>

다음 코드 예시는 `DescribeSpotFleetRequests`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스팟 플릿 요청 설명**  
이 예시에서는 모든 스팟 플릿 요청을 설명합니다.  
명령:  

```
aws ec2 describe-spot-fleet-requests
```
출력:  

```
{
  "SpotFleetRequestConfigs": [
      {
          "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
          "SpotFleetRequestConfig": {
              "TargetCapacity": 20,
              "LaunchSpecifications": [
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-a61dafcf",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "cc2.8xlarge",
                      "ImageId": "ami-1a2b3c4d"
                  },
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-a61dafcf",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "r3.8xlarge",
                      "ImageId": "ami-1a2b3c4d"
                  }
              ],
              "SpotPrice": "0.05",
              "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role"
          },
          "SpotFleetRequestState": "active"
      },
      {
          "SpotFleetRequestId": "sfr-306341ed-9739-402e-881b-ce47bEXAMPLE",
          "SpotFleetRequestConfig": {
              "TargetCapacity": 20,
              "LaunchSpecifications": [
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-6e7f829e",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "m3.medium",
                      "ImageId": "ami-1a2b3c4d"
                  }
              ],
              "SpotPrice": "0.05",
              "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role"
          },
          "SpotFleetRequestState": "active"
      }
  ]
}
```
**스팟 플릿 요청 설명**  
이 예시에서는 지정된 스팟 플릿 요청을 설명합니다.  
명령:  

```
aws ec2 describe-spot-fleet-requests --spot-fleet-request-ids sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
출력:  

```
{
  "SpotFleetRequestConfigs": [
      {
          "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
          "SpotFleetRequestConfig": {
              "TargetCapacity": 20,
              "LaunchSpecifications": [
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-a61dafcf",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "cc2.8xlarge",
                      "ImageId": "ami-1a2b3c4d"
                  },
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-a61dafcf",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "r3.8xlarge",
                      "ImageId": "ami-1a2b3c4d"
                  }
              ],
              "SpotPrice": "0.05",
              "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role"
          },
          "SpotFleetRequestState": "active"
      }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeSpotFleetRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-fleet-requests.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스팟 플릿 요청을 설명합니다.**  

```
Get-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE | format-list
```
**출력:**  

```
ConfigData            : Amazon.EC2.Model.SpotFleetRequestConfigData
CreateTime            : 12/26/2015 8:23:33 AM
SpotFleetRequestId    : sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
SpotFleetRequestState : active
```
**예제 2: 이 예제에서는 모든 스팟 플릿 요청을 설명합니다.**  

```
Get-EC2SpotFleetRequest
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSpotFleetRequests](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스팟 플릿 요청을 설명합니다.**  

```
Get-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE | format-list
```
**출력:**  

```
ConfigData            : Amazon.EC2.Model.SpotFleetRequestConfigData
CreateTime            : 12/26/2015 8:23:33 AM
SpotFleetRequestId    : sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
SpotFleetRequestState : active
```
**예제 2: 이 예제에서는 모든 스팟 플릿 요청을 설명합니다.**  

```
Get-EC2SpotFleetRequest
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSpotFleetRequests](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeSpotInstanceRequests` 사용
<a name="example_ec2_DescribeSpotInstanceRequests_section"></a>

다음 코드 예시는 `DescribeSpotInstanceRequests`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 스팟 인스턴스 요청 설명**  
다음 `describe-spot-instance-requests` 예시에서는 지정된 스팟 인스턴스 요청을 설명합니다.  

```
aws ec2 describe-spot-instance-requests \
    --spot-instance-request-ids sir-08b93456
```
출력:  

```
{
    "SpotInstanceRequests": [
        {
            "CreateTime": "2018-04-30T18:14:55.000Z",
            "InstanceId": "i-1234567890abcdef1",
            "LaunchSpecification": {
                "InstanceType": "t2.micro",
                "ImageId": "ami-003634241a8fcdec0",
                "KeyName": "my-key-pair",
                "SecurityGroups": [
                    {
                        "GroupName": "default",
                        "GroupId": "sg-e38f24a7"
                    }
                ],
                "BlockDeviceMappings": [
                    {
                        "DeviceName": "/dev/sda1",
                        "Ebs": {
                            "DeleteOnTermination": true,
                            "SnapshotId": "snap-0e54a519c999adbbd",
                            "VolumeSize": 8,
                            "VolumeType": "standard",
                            "Encrypted": false
                        }
                    }
                ],
                "NetworkInterfaces": [
                    {
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "SubnetId": "subnet-049df61146c4d7901"
                    }
                ],
                "Placement": {
                    "AvailabilityZone": "us-east-2b",
                    "Tenancy": "default"
                },
                "Monitoring": {
                    "Enabled": false
                }
            },
            "LaunchedAvailabilityZone": "us-east-2b",
            "ProductDescription": "Linux/UNIX",
            "SpotInstanceRequestId": "sir-08b93456",
            "SpotPrice": "0.010000"
            "State": "active",
            "Status": {
                "Code": "fulfilled",
                "Message": "Your Spot request is fulfilled.",
                "UpdateTime": "2018-04-30T18:16:21.000Z"
            },
            "Tags": [],
            "Type": "one-time",
            "InstanceInterruptionBehavior": "terminate"
        }
    ]
}
```
**예시 2: 필터를 기반으로 스팟 인스턴스 요청 설명**  
다음 `describe-spot-instance-requests` 예시에서는 필터를 사용하여 지정된 가용 영역에서 지정된 인스턴스 유형을 가진 스팟 인스턴스 요청으로 결과 범위를 지정합니다. 이 예시에서는 `--query` 파라미터를 사용하여 인스턴스 ID만 표시합니다.  

```
aws ec2 describe-spot-instance-requests \
    --filters Name=launch.instance-type,Values=m3.medium Name=launched-availability-zone,Values=us-east-2a \
    --query "SpotInstanceRequests[*].[InstanceId]" \
    --output text
```
출력:  

```
i-057750d42936e468a
i-001efd250faaa6ffa
i-027552a73f021f3bd
...
```
필터를 사용하는 추가 예시에서는 *Amazon Elastic Compute Cloud 사용 설명서*의 [리소스 나열 및 필터링](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)을 참조하세요.  
**예시 3: 태그를 기반으로 스팟 인스턴스 요청 설명**  
다음 `describe-spot-instance-requests` 예시에서는 태그 필터를 사용하여 `cost-center=cc123` 태그가 있는 스팟 인스턴스 요청으로 결과 범위를 지정합니다.  

```
aws ec2 describe-spot-instance-requests \
    --filters Name=tag:cost-center,Values=cc123
```
`describe-spot-instance-requests` 출력 예제는 예제 1을 참조하세요.  
태그 필터를 사용하는 추가 예제는 *Amazon EC2 사용 설명서*에서 [태그 작업](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeSpotInstanceRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-instance-requests.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스팟 인스턴스 요청을 설명합니다.**  

```
Get-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**출력:**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 4/8/2015 2:51:33 PM
Fault                    :
InstanceId               : i-12345678
LaunchedAvailabilityZone : us-west-2b
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.020000
State                    : active
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {Name}
Type                     : one-time
```
**예제 2: 이 예제에서는 모든 스팟 인스턴스 요청을 설명합니다.**  

```
Get-EC2SpotInstanceRequest
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스팟 인스턴스 요청을 설명합니다.**  

```
Get-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**출력:**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 4/8/2015 2:51:33 PM
Fault                    :
InstanceId               : i-12345678
LaunchedAvailabilityZone : us-west-2b
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.020000
State                    : active
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {Name}
Type                     : one-time
```
**예제 2: 이 예제에서는 모든 스팟 인스턴스 요청을 설명합니다.**  

```
Get-EC2SpotInstanceRequest
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeSpotPriceHistory` 사용
<a name="example_ec2_DescribeSpotPriceHistory_section"></a>

다음 코드 예시는 `DescribeSpotPriceHistory`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스팟 가격 내역 설명**  
이 예시 명령은 1월의 특정 날짜에 대한 m1.xlarge 인스턴스의 스팟 가격 내역을 반환합니다.  
명령:  

```
aws ec2 describe-spot-price-history --instance-types m1.xlarge --start-time 2014-01-06T07:08:09 --end-time 2014-01-06T08:09:10
```
출력:  

```
{
  "SpotPriceHistory": [
          {
              "Timestamp": "2014-01-06T07:10:55.000Z",
              "ProductDescription": "SUSE Linux",
              "InstanceType": "m1.xlarge",
              "SpotPrice": "0.087000",
              "AvailabilityZone": "us-west-1b"
          },
          {
              "Timestamp": "2014-01-06T07:10:55.000Z",
              "ProductDescription": "SUSE Linux",
              "InstanceType": "m1.xlarge",
              "SpotPrice": "0.087000",
              "AvailabilityZone": "us-west-1c"
          },
          {
              "Timestamp": "2014-01-06T05:42:36.000Z",
              "ProductDescription": "SUSE Linux (Amazon VPC)",
              "InstanceType": "m1.xlarge",
              "SpotPrice": "0.087000",
              "AvailabilityZone": "us-west-1a"
      },
      ...
}
```
**Linux/UNIX Amazon VPC의 스팟 가격 기록 설명**  
이 예시 명령은 1월의 특정 날짜에 대한 m1.xlarge, Linux/UNIX Amazon VPC 인스턴스의 스팟 가격 내역을 반환합니다.  
명령:  

```
aws ec2 describe-spot-price-history --instance-types m1.xlarge --product-description "Linux/UNIX (Amazon VPC)" --start-time 2014-01-06T07:08:09 --end-time 2014-01-06T08:09:10
```
출력:  

```
{
  "SpotPriceHistory": [
      {
          "Timestamp": "2014-01-06T04:32:53.000Z",
          "ProductDescription": "Linux/UNIX (Amazon VPC)",
          "InstanceType": "m1.xlarge",
          "SpotPrice": "0.080000",
          "AvailabilityZone": "us-west-1a"
      },
      {
          "Timestamp": "2014-01-05T11:28:26.000Z",
          "ProductDescription": "Linux/UNIX (Amazon VPC)",
          "InstanceType": "m1.xlarge",
          "SpotPrice": "0.080000",
          "AvailabilityZone": "us-west-1c"
      }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeSpotPriceHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-price-history.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스 유형 및 가용 영역에 대한 스팟 가격 기록의 마지막 10개 항목을 가져옵니다. -AvailabilityZone 파라미터에 지정된 값은 cmdlet의 -Region 파라미터(예제에 표시되지 않음)에 제공되거나 쉘의 기본값으로 설정된 리전 값에 대해 유효해야 합니다. 이 예제 명령은 환경에서 기본 리전인 'us-west-2'가 설정되었다고 가정합니다.**  

```
Get-EC2SpotPriceHistory -InstanceType c3.large -AvailabilityZone us-west-2a -MaxResult 10
```
**출력:**  

```
AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:39:49 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017200
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:38:29 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 6:57:13 AM
...
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSpotPriceHistory](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스 유형 및 가용 영역에 대한 스팟 가격 기록의 마지막 10개 항목을 가져옵니다. -AvailabilityZone 파라미터에 지정된 값은 cmdlet의 -Region 파라미터(예제에 표시되지 않음)에 제공되거나 쉘의 기본값으로 설정된 리전 값에 대해 유효해야 합니다. 이 예제 명령은 환경에서 기본 리전인 'us-west-2'가 설정되었다고 가정합니다.**  

```
Get-EC2SpotPriceHistory -InstanceType c3.large -AvailabilityZone us-west-2a -MaxResult 10
```
**출력:**  

```
AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:39:49 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017200
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:38:29 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 6:57:13 AM
...
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSpotPriceHistory](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeSubnets` 함께 사용
<a name="example_ec2_DescribeSubnets_section"></a>

다음 코드 예시는 `DescribeSubnets`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](example_cross_ResilientService_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 
+  [Transit Gateway 시작하기](example_vpc_TransitGatewayGettingStarted_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Get all the subnets for a Vpc in a set of availability zones.
    /// </summary>
    /// <param name="vpcId">The Id of the Vpc.</param>
    /// <param name="availabilityZones">The list of availability zones.</param>
    /// <returns>The collection of subnet objects.</returns>
    public async Task<List<Subnet>> GetAllVpcSubnetsForZones(string vpcId, List<string> availabilityZones)
    {
        try
        {
            var subnets = new List<Subnet>();
            var subnetPaginator = _amazonEc2.Paginators.DescribeSubnets(
                new DescribeSubnetsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("vpc-id", new List<string>() { vpcId }),
                        new("availability-zone", availabilityZones),
                        new("default-for-az", new List<string>() { "true" })
                    }
                });

            // Get the entire list using the paginator.
            await foreach (var subnet in subnetPaginator.Subnets)
            {
                subnets.Add(subnet);
            }

            return subnets;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidVpcID.NotFound")
            {
                _logger.LogError(ec2Exception, $"The specified VPC ID {vpcId} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the subnets.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET  API 참조*의 [DescribeSubnets](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeSubnets)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 모든 서브넷을 설명하는 방법**  
다음 `describe-subnets` 예제에서는 서브넷의 세부 정보를 표시합니다.  

```
aws ec2 describe-subnets
```
출력:  

```
{
    "Subnets": [
        {
            "AvailabilityZone": "us-east-1d",
            "AvailabilityZoneId": "use1-az2",
            "AvailableIpAddressCount": 4089,
            "CidrBlock": "172.31.80.0/20",
            "DefaultForAz": true,
            "MapPublicIpOnLaunch": false,
            "MapCustomerOwnedIpOnLaunch": true,
            "State": "available",
            "SubnetId": "subnet-0bb1c79de3EXAMPLE",
            "VpcId": "vpc-0ee975135dEXAMPLE",
            "OwnerId": "111122223333",
            "AssignIpv6AddressOnCreation": false,
            "Ipv6CidrBlockAssociationSet": [],
            "CustomerOwnedIpv4Pool:": 'pool-2EXAMPLE',
            "SubnetArn": "arn:aws:ec2:us-east-2:111122223333:subnet/subnet-0bb1c79de3EXAMPLE",
            "EnableDns64": false,
            "Ipv6Native": false,
            "PrivateDnsNameOptionsOnLaunch": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            }
        },
        {
            "AvailabilityZone": "us-east-1d",
            "AvailabilityZoneId": "use1-az2",
            "AvailableIpAddressCount": 4089,
            "CidrBlock": "172.31.80.0/20",
            "DefaultForAz": true,
            "MapPublicIpOnLaunch": true,
            "MapCustomerOwnedIpOnLaunch": false,
            "State": "available",
            "SubnetId": "subnet-8EXAMPLE",
            "VpcId": "vpc-3EXAMPLE",
            "OwnerId": "1111222233333",
            "AssignIpv6AddressOnCreation": false,
            "Ipv6CidrBlockAssociationSet": [],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "MySubnet"
                }
            ],
            "SubnetArn": "arn:aws:ec2:us-east-1:111122223333:subnet/subnet-8EXAMPLE",
            "EnableDns64": false,
            "Ipv6Native": false,
            "PrivateDnsNameOptionsOnLaunch": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            }
        }
    ]
}
```
자세한 내용은 *AWS VPC 사용 설명서*에서 [VPC 및 서브넷 작업](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html)을 참조하세요.  
**예제 2: 특정 VPC의 서브넷을 설명하는 방법**  
다음 `describe-subnets` 예제에서는 필터를 사용하여 지정된 VPC의 서브넷에 대한 세부 정보를 검색합니다.  

```
aws ec2 describe-subnets \
    --filters "Name=vpc-id,Values=vpc-3EXAMPLE"
```
출력:  

```
{
    "Subnets": [
        {
            "AvailabilityZone": "us-east-1d",
            "AvailabilityZoneId": "use1-az2",
            "AvailableIpAddressCount": 4089,
            "CidrBlock": "172.31.80.0/20",
            "DefaultForAz": true,
            "MapPublicIpOnLaunch": true,
            "MapCustomerOwnedIpOnLaunch": false,
            "State": "available",
            "SubnetId": "subnet-8EXAMPLE",
            "VpcId": "vpc-3EXAMPLE",
            "OwnerId": "1111222233333",
            "AssignIpv6AddressOnCreation": false,
            "Ipv6CidrBlockAssociationSet": [],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "MySubnet"
                }
            ],
            "SubnetArn": "arn:aws:ec2:us-east-1:111122223333:subnet/subnet-8EXAMPLE",
            "EnableDns64": false,
            "Ipv6Native": false,
            "PrivateDnsNameOptionsOnLaunch": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            }
        }
    ]
}
```
자세한 내용은 *AWS VPC 사용 설명서*에서 [VPC 및 서브넷 작업](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html)을 참조하세요.  
**예제 3: 특정 태그의 서브넷을 설명하는 방법**  
다음 `describe-subnets` 예제에서는 필터를 사용하여 `CostCenter=123` 태그가 있는 해당 서브넷 세부 정보를 검색하고 `--query` 파라미터를 사용하여 이 태그가 있는 서브넷의 서브넷 ID를 표시합니다.  

```
aws ec2 describe-subnets \
    --filters "Name=tag:CostCenter,Values=123" \
    --query "Subnets[*].SubnetId" \
    --output text
```
출력:  

```
subnet-0987a87c8b37348ef
subnet-02a95061c45f372ee
subnet-03f720e7de2788d73
```
자세한 내용은 *Amazon VPC 사용 설명서*에서 [VPC 및 서브넷 작업](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeSubnets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-subnets.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    const client = new EC2Client({});
    const { Subnets } = await client.send(
      new DescribeSubnetsCommand({
        Filters: [
          { Name: "vpc-id", Values: [state.defaultVpc] },
          { Name: "availability-zone", Values: state.availabilityZoneNames },
          { Name: "default-for-az", Values: ["true"] },
        ],
      }),
    );
```
+  API 세부 정보는 *AWS SDK for JavaScript  API 참조*의 [DescribeSubnets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSubnetsCommand)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 서브넷을 설명합니다.**  

```
Get-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**출력:**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : available
SubnetId                : subnet-1a2b3c4d
Tags                    : {}
VpcId                   : vpc-12345678
```
**예제 2: 이 예제에서는 모든 서브넷을 설명합니다.**  

```
Get-EC2Subnet
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeSubnets](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 서브넷을 설명합니다.**  

```
Get-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**출력:**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : available
SubnetId                : subnet-1a2b3c4d
Tags                    : {}
VpcId                   : vpc-12345678
```
**예제 2: 이 예제에서는 모든 서브넷을 설명합니다.**  

```
Get-EC2Subnet
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeSubnets](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def get_subnets(self, vpc_id: str, zones: List[str] = None) -> List[Dict[str, Any]]:
        """
        Gets the default subnets in a VPC for a specified list of Availability Zones.

        :param vpc_id: The ID of the VPC to look up.
        :param zones: The list of Availability Zones to look up.
        :return: The list of subnets found.
        """
        # Ensure that 'zones' is a list, even if None is passed
        if zones is None:
            zones = []
        try:
            paginator = self.ec2_client.get_paginator("describe_subnets")
            page_iterator = paginator.paginate(
                Filters=[
                    {"Name": "vpc-id", "Values": [vpc_id]},
                    {"Name": "availability-zone", "Values": zones},
                    {"Name": "default-for-az", "Values": ["true"]},
                ]
            )

            subnets = []
            for page in page_iterator:
                subnets.extend(page["Subnets"])

            log.info("Found %s subnets for the specified zones.", len(subnets))
            return subnets
        except ClientError as err:
            log.error(
                f"Failed to retrieve subnets for VPC '{vpc_id}' in zones {zones}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    "The specified VPC ID does not exist. "
                    "Please check the VPC ID and try again."
                )
            # Add more error-specific handling as needed
            log.error(f"Full error:\n\t{err}")
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeSubnets](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSubnets)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeTags` 사용
<a name="example_ec2_DescribeTags_section"></a>

다음 코드 예시는 `DescribeTags`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 단일 리소스에 대한 모든 태그 설명**  
다음 `describe-tags` 예시에서는 지정된 인스턴스에 대한 태그를 설명합니다.  

```
aws ec2 describe-tags \
    --filters "Name=resource-id,Values=i-1234567890abcdef8"
```
출력:  

```
{
    "Tags": [
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef8",
            "Value": "Test",
            "Key": "Stack"
        },
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef8",
            "Value": "Beta Server",
            "Key": "Name"
        }
    ]
}
```
**예시 2: 리소스 유형에 대한 모든 태그 설명**  
다음 `describe-tags` 예시에서는 볼륨에 대한 태그를 설명합니다.  

```
aws ec2 describe-tags \
    --filters "Name=resource-type,Values=volume"
```
출력:  

```
{
    "Tags": [
        {
            "ResourceType": "volume",
            "ResourceId": "vol-1234567890abcdef0",
            "Value": "Project1",
            "Key": "Purpose"
        },
        {
            "ResourceType": "volume",
            "ResourceId": "vol-049df61146c4d7901",
            "Value": "Logs",
            "Key": "Purpose"
        }
    ]
}
```
**예시 3: 모든 태그 설명**  
다음 `describe-tags` 예시에서는 모든 리소스에 대한 태그를 설명합니다.  

```
aws ec2 describe-tags
```
**예시 4: 태그 키를 기반으로 리소스의 태그 설명**  
다음 `describe-tags` 예시에서는 키가 `Stack`로 시작하는 태그가 있는 리소스에 대한 태그를 설명합니다.  

```
aws ec2 describe-tags \
    --filters Name=key,Values=Stack
```
출력:  

```
{
    "Tags": [
        {
            "ResourceType": "volume",
            "ResourceId": "vol-027552a73f021f3b",
            "Value": "Production",
            "Key": "Stack"
        },
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef8",
            "Value": "Test",
            "Key": "Stack"
        }
    ]
}
```
**예시 5: 태그 키 및 태그 값을 기반으로 리소스의 태그 설명**  
다음 `describe-tags` 예시에서는 `Stack=Test` 태그가 있는 리소스의 태그를 설명합니다.  

```
aws ec2 describe-tags \
    --filters Name=key,Values=Stack Name=value,Values=Test
```
출력:  

```
{
    "Tags": [
        {
            "ResourceType": "image",
            "ResourceId": "ami-3ac336533f021f3bd",
            "Value": "Test",
            "Key": "Stack"
        },
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef8",
            "Value": "Test",
            "Key": "Stack"
        }
    ]
}
```
다음 `describe-tags` 예시에서는 대체 구문을 사용하여 `Stack=Test` 태그가 있는 리소스를 설명합니다.  

```
aws ec2 describe-tags \
    --filters "Name=tag:Stack,Values=Test"
```
다음 `describe-tags` 예시에서는 `Purpose` 키가 있고 값이 없는 태그가 있는 모든 인스턴스에 대한 태그를 설명합니다.  

```
aws ec2 describe-tags \
    --filters "Name=resource-type,Values=instance" "Name=key,Values=Purpose" "Name=value,Values="
```
출력:  

```
{
    "Tags": [
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef5",
            "Value": null,
            "Key": "Purpose"
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-tags.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 resource-type 'image'에 대한 태그를 가져옵니다.**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="image"}
```
**출력:**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
Name        ami-0a123b4ccb567a8ea image        Win7-Imported
auto-delete ami-0a123b4ccb567a8ea image        never
```
**예제 2: 이 예제에서는 모든 리소스에 대한 모든 태그를 가져와 리소스 유형별로 그룹화합니다.**  

```
Get-EC2Tag | Group-Object resourcetype
```
**출력:**  

```
Count Name                      Group
----- ----                      -----
    9 subnet                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   53 instance                  {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    3 route-table               {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    5 security-group            {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   30 volume                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    1 internet-gateway          {Amazon.EC2.Model.TagDescription}
    3 network-interface         {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    4 elastic-ip                {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    1 dhcp-options              {Amazon.EC2.Model.TagDescription}
    2 image                     {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    3 vpc                       {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
```
**예제 3: 이 예제에서는 지정된 리전에 대해 태그가 'auto-delete'이고 값이 'no'인 모든 리소스를 표시합니다.**  

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"}
```
**출력:**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
auto-delete i-0f1bce234d5dd678b   instance     no
auto-delete vol-01d234aa5678901a2 volume       no
auto-delete vol-01234bfb5def6f7b8 volume       no
auto-delete vol-01ccb23f4c5e67890 volume       no
```
**예제 4: 이 예제에서는 태그가 'auto-delete'이고 값이 'no'인 모든 리소스를 가져와서 다음 파이프에서 추가로 필터링하여 'instance' 리소스 유형만 구문 분석하고 최종적으로 값이 인스턴스 ID 자체인 각 인스턴스 리소스에 대해 'ThisInstance' 태그를 생성합니다. **   

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"} | Where-Object ResourceType -eq "instance" | ForEach-Object {New-EC2Tag -ResourceId $_.ResourceId -Tag @{Key="ThisInstance";Value=$_.ResourceId}}
```
**예제 5: 이 예제에서는 모든 인스턴스 리소스와 'Name' 키에 대한 태그를 가져와 테이블 형식으로 표시합니다.**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="instance"},@{Name="key";Values="Name"} | Select-Object ResourceId, @{Name="Name-Tag";Expression={$PSItem.Value}} | Format-Table -AutoSize
```
**출력:**  

```
ResourceId          Name-Tag
----------          --------
i-012e3cb4df567e1aa jump1
i-01c23a45d6fc7a89f repro-3
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 resource-type 'image'에 대한 태그를 가져옵니다.**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="image"}
```
**출력:**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
Name        ami-0a123b4ccb567a8ea image        Win7-Imported
auto-delete ami-0a123b4ccb567a8ea image        never
```
**예제 2: 이 예제에서는 모든 리소스에 대한 모든 태그를 가져와 리소스 유형별로 그룹화합니다.**  

```
Get-EC2Tag | Group-Object resourcetype
```
**출력:**  

```
Count Name                      Group
----- ----                      -----
    9 subnet                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   53 instance                  {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    3 route-table               {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    5 security-group            {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   30 volume                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    1 internet-gateway          {Amazon.EC2.Model.TagDescription}
    3 network-interface         {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    4 elastic-ip                {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    1 dhcp-options              {Amazon.EC2.Model.TagDescription}
    2 image                     {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    3 vpc                       {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
```
**예제 3: 이 예제에서는 지정된 리전에 대해 태그가 'auto-delete'이고 값이 'no'인 모든 리소스를 표시합니다.**  

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"}
```
**출력:**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
auto-delete i-0f1bce234d5dd678b   instance     no
auto-delete vol-01d234aa5678901a2 volume       no
auto-delete vol-01234bfb5def6f7b8 volume       no
auto-delete vol-01ccb23f4c5e67890 volume       no
```
**예제 4: 이 예제에서는 태그가 'auto-delete'이고 값이 'no'인 모든 리소스를 가져와서 다음 파이프에서 추가로 필터링하여 'instance' 리소스 유형만 구문 분석하고 최종적으로 값이 인스턴스 ID 자체인 각 인스턴스 리소스에 대해 'ThisInstance' 태그를 생성합니다. **   

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"} | Where-Object ResourceType -eq "instance" | ForEach-Object {New-EC2Tag -ResourceId $_.ResourceId -Tag @{Key="ThisInstance";Value=$_.ResourceId}}
```
**예제 5: 이 예제에서는 모든 인스턴스 리소스와 'Name' 키에 대한 태그를 가져와 테이블 형식으로 표시합니다.**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="instance"},@{Name="key";Values="Name"} | Select-Object ResourceId, @{Name="Name-Tag";Expression={$PSItem.Value}} | Format-Table -AutoSize
```
**출력:**  

```
ResourceId          Name-Tag
----------          --------
i-012e3cb4df567e1aa jump1
i-01c23a45d6fc7a89f repro-3
```
**예제 6: 이 예제에서는 태그를 실제로 가져오지 않고 DryRun 파라미터를 사용하여 EC2 태그를 가져올 수 있는 권한을 검증합니다. 참고: 작업이 성공하면 예외가 발생하며 이는 정상적인 동작입니다.**  

```
Get-EC2Tag -DryRun $true
```
**출력:**  

```
Get-EC2Tag: Request would have succeeded, but DryRun flag is set.
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVolumeAttribute` 사용
<a name="example_ec2_DescribeVolumeAttribute_section"></a>

다음 코드 예시는 `DescribeVolumeAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**볼륨 속성 설명**  
이 예시 명령은 ID가 `vol-049df61146c4d7901`인 볼륨의 `autoEnableIo` 속성을 설명합니다.  
명령:  

```
aws ec2 describe-volume-attribute --volume-id vol-049df61146c4d7901 --attribute autoEnableIO
```
출력:  

```
{
    "AutoEnableIO": {
        "Value": false
    },
    "VolumeId": "vol-049df61146c4d7901"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVolumeAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-volume-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 볼륨의 지정된 속성을 설명합니다.**  

```
Get-EC2VolumeAttribute -VolumeId vol-12345678 -Attribute AutoEnableIO
```
**출력:**  

```
AutoEnableIO    ProductCodes    VolumeId
------------    ------------    --------
False           {}              vol-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVolumeAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 볼륨의 지정된 속성을 설명합니다.**  

```
Get-EC2VolumeAttribute -VolumeId vol-12345678 -Attribute AutoEnableIO
```
**출력:**  

```
AutoEnableIO    ProductCodes    VolumeId
------------    ------------    --------
False           {}              vol-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVolumeAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVolumeStatus` 사용
<a name="example_ec2_DescribeVolumeStatus_section"></a>

다음 코드 예시는 `DescribeVolumeStatus`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**단일 볼륨의 상태 설명**  
이 예시 명령은 볼륨 `vol-1234567890abcdef0`의 상태를 설명합니다.  
명령:  

```
aws ec2 describe-volume-status --volume-ids vol-1234567890abcdef0
```
출력:  

```
{
    "VolumeStatuses": [
        {
            "VolumeStatus": {
                "Status": "ok",
                "Details": [
                    {
                        "Status": "passed",
                        "Name": "io-enabled"
                    },
                    {
                        "Status": "not-applicable",
                        "Name": "io-performance"
                    }
                ]
            },
            "AvailabilityZone": "us-east-1a",
            "VolumeId": "vol-1234567890abcdef0",
            "Actions": [],
            "Events": []
        }
    ]
}
```
**손상된 볼륨의 상태 설명**  
이 예시 명령은 손상된 모든 볼륨의 상태를 설명합니다. 이 예시 출력에서는 손상된 볼륨이 없습니다.  
명령:  

```
aws ec2 describe-volume-status --filters Name=volume-status.status,Values=impaired
```
출력:  

```
{
    "VolumeStatuses": []
}
```
상태 확인에 실패한 볼륨이 있는 경우(상태가 손상됨) *Amazon EC2 사용 설명서*의 손상된 볼륨 작업을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVolumeStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-volume-status.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 볼륨의 상태를 설명합니다.**  

```
Get-EC2VolumeStatus -VolumeId vol-12345678
```
**출력:**  

```
Actions          : {}
AvailabilityZone : us-west-2a
Events           : {}
VolumeId         : vol-12345678
VolumeStatus     : Amazon.EC2.Model.VolumeStatusInfo
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus
```
**출력:**  

```
Details                         Status
-------                         ------
{io-enabled, io-performance}    ok
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus.Details
```
**출력:**  

```
Name                            Status
----                            ------
io-enabled                      passed
io-performance                  not-applicable
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVolumeStatus](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 볼륨의 상태를 설명합니다.**  

```
Get-EC2VolumeStatus -VolumeId vol-12345678
```
**출력:**  

```
Actions          : {}
AvailabilityZone : us-west-2a
Events           : {}
VolumeId         : vol-12345678
VolumeStatus     : Amazon.EC2.Model.VolumeStatusInfo
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus
```
**출력:**  

```
Details                         Status
-------                         ------
{io-enabled, io-performance}    ok
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus.Details
```
**출력:**  

```
Name                            Status
----                            ------
io-enabled                      passed
io-performance                  not-applicable
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVolumeStatus](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVolumes` 사용
<a name="example_ec2_DescribeVolumes_section"></a>

다음 코드 예시는 `DescribeVolumes`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 볼륨 설명**  
다음 `describe-volumes` 예시에서는 현재 리전 내 지정된 볼륨을 설명합니다.  

```
aws ec2 describe-volumes \
    --volume-ids vol-049df61146c4d7901 vol-1234567890abcdef0
```
출력:  

```
{
    "Volumes": [
        {
            "AvailabilityZone": "us-east-1a",
            "Attachments": [
                {
                    "AttachTime": "2013-12-18T22:35:00.000Z",
                    "InstanceId": "i-1234567890abcdef0",
                    "VolumeId": "vol-049df61146c4d7901",
                    "State": "attached",
                    "DeleteOnTermination": true,
                    "Device": "/dev/sda1"
                }
            ],
            "Encrypted": true,
            "KmsKeyId": "arn:aws:kms:us-east-2a:123456789012:key/8c5b2c63-b9bc-45a3-a87a-5513eEXAMPLE,
            "VolumeType": "gp2",
            "VolumeId": "vol-049df61146c4d7901",
            "State": "in-use",
            "Iops": 100,
            "SnapshotId": "snap-1234567890abcdef0",
            "CreateTime": "2019-12-18T22:35:00.084Z",
            "Size": 8
        },
        {
            "AvailabilityZone": "us-east-1a",
            "Attachments": [],
            "Encrypted": false,
            "VolumeType": "gp2",
            "VolumeId": "vol-1234567890abcdef0",
            "State": "available",
            "Iops": 300,
            "SnapshotId": "",
            "CreateTime": "2020-02-27T00:02:41.791Z",
            "Size": 100
        }
    ]
}
```
**예시 2: 특정 인스턴스에 연결된 볼륨 설명**  
다음 `describe-volumes` 예시에서는 지정된 인스턴스에 연결되어 있고 인스턴스가 종료될 때 삭제되도록 설정된 모든 볼륨을 설명합니다.  

```
aws ec2 describe-volumes \
    --region us-east-1 \
    --filters Name=attachment.instance-id,Values=i-1234567890abcdef0 Name=attachment.delete-on-termination,Values=true
```
`describe-volumes` 출력 예제는 예제 1을 참조하세요.  
**예시 3: 특정 가용 영역에서 사용 가능한 볼륨 설명**  
다음 `describe-volumes` 예시에서는 지정된 가용 영역에 있고 상태가 `available`인 모든 볼륨을 설명합니다.  

```
aws ec2 describe-volumes \
    --filters Name=status,Values=available Name=availability-zone,Values=us-east-1a
```
`describe-volumes` 출력 예제는 예제 1을 참조하세요.  
**예시 4: 태그를 기반으로 볼륨 설명**  
다음 `describe-volumes` 예시에서는 태그 키가 `Name`이고 값이 `Test`로 시작하는 모든 볼륨을 설명합니다. 그런 다음 출력은 볼륨의 태그와 ID만 표시하는 쿼리로 필터링됩니다.  

```
aws ec2 describe-volumes \
    --filters Name=tag:Name,Values=Test* \
    --query "Volumes[*].{ID:VolumeId,Tag:Tags}"
```
출력:  

```
[
    {
       "Tag": [
           {
               "Value": "Test2",
               "Key": "Name"
           }
       ],
       "ID": "vol-1234567890abcdef0"
   },
   {
       "Tag": [
           {
               "Value": "Test1",
               "Key": "Name"
           }
       ],
       "ID": "vol-049df61146c4d7901"
    }
]
```
태그 필터를 사용하는 추가 예제는 *Amazon EC2 사용 설명서*에서 [태그 작업](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVolumes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-volumes.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 EBS 볼륨을 설명합니다.**  

```
Get-EC2Volume -VolumeId vol-12345678
```
**출력:**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 7/17/2015 4:35:19 PM
Encrypted        : False
Iops             : 90
KmsKeyId         :
Size             : 30
SnapshotId       : snap-12345678
State            : in-use
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : standard
```
**예제 2: 이 예제에서는 상태가 'available'인 EBS 볼륨을 설명합니다.**  

```
Get-EC2Volume -Filter @{ Name="status"; Values="available" }
```
**출력:**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 12/21/2015 2:31:29 PM
Encrypted        : False
Iops             : 60
KmsKeyId         :
Size             : 20
SnapshotId       : snap-12345678
State            : available
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
...
```
**예제 3: 이 예제에서는 모든 EBS 볼륨을 설명합니다.**  

```
Get-EC2Volume
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVolumes](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 EBS 볼륨을 설명합니다.**  

```
Get-EC2Volume -VolumeId vol-12345678
```
**출력:**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 7/17/2015 4:35:19 PM
Encrypted        : False
Iops             : 90
KmsKeyId         :
Size             : 30
SnapshotId       : snap-12345678
State            : in-use
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : standard
```
**예제 2: 이 예제에서는 상태가 'available'인 EBS 볼륨을 설명합니다.**  

```
Get-EC2Volume -Filter @{ Name="status"; Values="available" }
```
**출력:**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 12/21/2015 2:31:29 PM
Encrypted        : False
Iops             : 60
KmsKeyId         :
Size             : 20
SnapshotId       : snap-12345678
State            : available
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
...
```
**예제 3: 이 예제에서는 모든 EBS 볼륨을 설명합니다.**  

```
Get-EC2Volume
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVolumes](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVpcAttribute` 사용
<a name="example_ec2_DescribeVpcAttribute_section"></a>

다음 코드 예시는 `DescribeVpcAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**enableDnsSupport 속성 설명**  
이 예시에서는 `enableDnsSupport` 속성을 설명합니다. 이 속성은 VPC에 DNS 확인이 활성화되어 있는지 여부를 나타냅니다. 이 속성이 `true`인 경우 Amazon DNS 서버는 인스턴스의 DNS 호스트 이름을 해당 IP 주소로 확인하지만, 그렇지 않으면 확인하지 않습니다.  
명령:  

```
aws ec2 describe-vpc-attribute --vpc-id vpc-a01106c2 --attribute enableDnsSupport
```
출력:  

```
{
    "VpcId": "vpc-a01106c2",
    "EnableDnsSupport": {
        "Value": true
    }
}
```
**enableDnsHostnames 속성 설명**  
이 예시에서는 `enableDnsHostnames` 속성을 설명합니다. 이 속성은 VPC에서 시작된 인스턴스가 DNS 호스트 이름을 가져오는지 나타냅니다. 이 속성이 `true`인 경우 VPC의 인스턴스가 DNS 호스트 이름을 가져오고, 그렇지 않으면 가져오지 않습니다.  
명령:  

```
aws ec2 describe-vpc-attribute --vpc-id vpc-a01106c2 --attribute enableDnsHostnames
```
출력:  

```
{
    "VpcId": "vpc-a01106c2",
    "EnableDnsHostnames": {
        "Value": true
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVpcAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 'enableDnsSupport' 속성을 설명합니다.**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsSupport
```
**출력:**  

```
EnableDnsSupport
----------------
True
```
**예제 2: 이 예제에서는 'enableDnsHostnames' 속성을 설명합니다.**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsHostnames
```
**출력:**  

```
EnableDnsHostnames
------------------
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVpcAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 'enableDnsSupport' 속성을 설명합니다.**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsSupport
```
**출력:**  

```
EnableDnsSupport
----------------
True
```
**예제 2: 이 예제에서는 'enableDnsHostnames' 속성을 설명합니다.**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsHostnames
```
**출력:**  

```
EnableDnsHostnames
------------------
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVpcAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVpcClassicLink` 사용
<a name="example_ec2_DescribeVpcClassicLink_section"></a>

다음 코드 예시는 `DescribeVpcClassicLink`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPCs의 ClassicLink 상태 설명**  
이 예시에서는 vpc-88888888의 ClassicLink 상태를 나열합니다.  
명령:  

```
aws ec2 describe-vpc-classic-link --vpc-id vpc-88888888
```
출력:  

```
{
  "Vpcs": [
    {
      "ClassicLinkEnabled": true,
      "VpcId": "vpc-88888888",
      "Tags": [
        {
          "Value": "classiclinkvpc",
          "Key": "Name"
        }
      ]
    }
  ]
}
```
이 예시에서는 Classiclink에 대해 사용하도록 설정된 VPC만 나열합니다(`is-classic-link-enabled` 필터 값이 `true`로 설정되어 있음).  
명령:  

```
aws ec2 describe-vpc-classic-link --filter "Name=is-classic-link-enabled,Values=true"
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVpcClassicLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-classic-link.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 위 예제에서는 리전에 대해 ClassicLinkEnabled 상태의 모든 VPC를 반환합니다.**  

```
Get-EC2VpcClassicLink -Region eu-west-1
```
**출력:**  

```
ClassicLinkEnabled Tags   VpcId
------------------ ----   -----
False              {Name} vpc-0fc1ff23f45b678eb
False              {}     vpc-01e23c4a5d6db78e9
False              {Name} vpc-0123456b078b9d01f
False              {}     vpc-12cf3b4f
False              {Name} vpc-0b12d3456a7e8901d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVpcClassicLink](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 위 예제에서는 리전에 대해 ClassicLinkEnabled 상태의 모든 VPC를 반환합니다.**  

```
Get-EC2VpcClassicLink -Region eu-west-1
```
**출력:**  

```
ClassicLinkEnabled Tags   VpcId
------------------ ----   -----
False              {Name} vpc-0fc1ff23f45b678eb
False              {}     vpc-01e23c4a5d6db78e9
False              {Name} vpc-0123456b078b9d01f
False              {}     vpc-12cf3b4f
False              {Name} vpc-0b12d3456a7e8901d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVpcClassicLinkDnsSupport` 사용
<a name="example_ec2_DescribeVpcClassicLinkDnsSupport_section"></a>

다음 코드 예시는 `DescribeVpcClassicLinkDnsSupport`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPCs에 대한 ClassicLink DNS 지원 설명**  
이 예시에서는 모든 VPC의 ClassicLink DNS 지원 상태를 설명합니다.  
명령:  

```
aws ec2 describe-vpc-classic-link-dns-support
```
출력:  

```
{
  "Vpcs": [
    {
      "VpcId": "vpc-88888888",
      "ClassicLinkDnsSupported": true
    },
    {
      "VpcId": "vpc-1a2b3c4d",
      "ClassicLinkDnsSupported": false
    }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVpcClassicLinkDnsSupport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-classic-link-dns-support.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 eu-west-1 리전에 대한 VPC의 ClassicLink DNS 지원 상태를 설명합니다.**  

```
Get-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
**출력:**  

```
ClassicLinkDnsSupported VpcId
----------------------- -----
False                   vpc-0b12d3456a7e8910d
False                   vpc-12cf3b4f
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 eu-west-1 리전에 대한 VPC의 ClassicLink DNS 지원 상태를 설명합니다.**  

```
Get-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
**출력:**  

```
ClassicLinkDnsSupported VpcId
----------------------- -----
False                   vpc-0b12d3456a7e8910d
False                   vpc-12cf3b4f
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVpcEndpointServices` 사용
<a name="example_ec2_DescribeVpcEndpointServices_section"></a>

다음 코드 예시는 `DescribeVpcEndpointServices`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 모든 VPC 엔드포인트 서비스 설명**  
다음 `describe-vpc-endpoint-services` 예시에서는 AWS 리전에 대한 모든 VPC 엔드포인트 서비스를 나열합니다.  

```
aws ec2 describe-vpc-endpoint-services
```
출력:  

```
{
    "ServiceDetails": [
        {
            "ServiceType": [
                {
                    "ServiceType": "Gateway"
                }
            ],
            "AcceptanceRequired": false,
            "ServiceName": "com.amazonaws.us-east-1.dynamodb",
            "VpcEndpointPolicySupported": true,
            "Owner": "amazon",
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e",
                "us-east-1f"
            ],
            "BaseEndpointDnsNames": [
                "dynamodb.us-east-1.amazonaws.com"
            ]
        },
        {
            "ServiceType": [
                {
                    "ServiceType": "Interface"
                }
            ],
            "PrivateDnsName": "ec2.us-east-1.amazonaws.com",
            "ServiceName": "com.amazonaws.us-east-1.ec2",
            "VpcEndpointPolicySupported": false,
            "Owner": "amazon",
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e",
                "us-east-1f"
            ],
            "AcceptanceRequired": false,
            "BaseEndpointDnsNames": [
                "ec2.us-east-1.vpce.amazonaws.com"
            ]
        },
        {
            "ServiceType": [
                {
                    "ServiceType": "Interface"
                }
            ],
            "PrivateDnsName": "ssm.us-east-1.amazonaws.com",
            "ServiceName": "com.amazonaws.us-east-1.ssm",
            "VpcEndpointPolicySupported": true,
            "Owner": "amazon",
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e"
            ],
            "AcceptanceRequired": false,
            "BaseEndpointDnsNames": [
                "ssm.us-east-1.vpce.amazonaws.com"
            ]
        }
    ],
    "ServiceNames": [
        "com.amazonaws.us-east-1.dynamodb",
        "com.amazonaws.us-east-1.ec2",
        "com.amazonaws.us-east-1.ec2messages",
        "com.amazonaws.us-east-1.elasticloadbalancing",
        "com.amazonaws.us-east-1.kinesis-streams",
        "com.amazonaws.us-east-1.s3",
        "com.amazonaws.us-east-1.ssm"
    ]
}
```
**예시 2: 엔드포인트 서비스에 대한 세부 정보 설명**  
다음 `describe-vpc-endpoint-services` 예제에서는 Amazon S3 인터페이스 엔드포인트 서비스의 세부 정보를 나열합니다.  

```
aws ec2 describe-vpc-endpoint-services \
    --filter 'Name=service-type,Values=Interface' Name=service-name,Values=com.amazonaws.us-east-1.s3
```
출력:  

```
{
    "ServiceDetails": [
        {
            "ServiceName": "com.amazonaws.us-east-1.s3",
            "ServiceId": "vpce-svc-081d84efcdEXAMPLE",
            "ServiceType": [
                {
                    "ServiceType": "Interface"
                }
            ],
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e",
            "us-east-1f"
            ],
            "Owner": "amazon",
            "BaseEndpointDnsNames": [
                "s3.us-east-1.vpce.amazonaws.com"
            ],
            "VpcEndpointPolicySupported": true,
            "AcceptanceRequired": false,
            "ManagesVpcEndpoints": false,
            "Tags": []
        }
    ],
    "ServiceNames": [
        "com.amazonaws.us-east-1.s3"
    ]
}
```
자세한 내용은 *AWS PrivateLink 사용 설명서*의 [사용 가능한 AWS 서비스 이름 보기를](https://docs.aws.amazon.com/vpc/latest/privatelink/aws-services-privatelink-support.html#vpce-view-available-services) 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVpcEndpointServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoint-services.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 필터를 사용하여 EC2 VPC 엔드포인트 서비스를 설명합니다. 이 경우 필터는 com.amazonaws.eu-west-1.ecs입니다. 그리고 ServiceDetails 속성을 확장하고 세부 정보를 표시합니다.**  

```
Get-EC2VpcEndpointService -Region eu-west-1 -MaxResult 5 -Filter @{Name="service-name";Values="com.amazonaws.eu-west-1.ecs"} | Select-Object -ExpandProperty ServiceDetails
```
**출력:**  

```
AcceptanceRequired         : False
AvailabilityZones          : {eu-west-1a, eu-west-1b, eu-west-1c}
BaseEndpointDnsNames       : {ecs.eu-west-1.vpce.amazonaws.com}
Owner                      : amazon
PrivateDnsName             : ecs.eu-west-1.amazonaws.com
ServiceName                : com.amazonaws.eu-west-1.ecs
ServiceType                : {Amazon.EC2.Model.ServiceTypeDetail}
VpcEndpointPolicySupported : False
```
**예제 2: 이 예제에서는 모든 EC2 VPC 엔드포인트 서비스를 검색하고 'ssm'과 일치하는 ServiceName을 반환합니다.**  

```
Get-EC2VpcEndpointService -Region eu-west-1 | Select-Object -ExpandProperty Servicenames | Where-Object { -match "ssm"}
```
**출력:**  

```
com.amazonaws.eu-west-1.ssm
com.amazonaws.eu-west-1.ssmmessages
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVpcEndpointServices](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 필터를 사용하여 EC2 VPC 엔드포인트 서비스를 설명합니다. 이 경우 필터는 com.amazonaws.eu-west-1.ecs입니다. 그리고 ServiceDetails 속성을 확장하고 세부 정보를 표시합니다.**  

```
Get-EC2VpcEndpointService -Region eu-west-1 -MaxResult 5 -Filter @{Name="service-name";Values="com.amazonaws.eu-west-1.ecs"} | Select-Object -ExpandProperty ServiceDetails
```
**출력:**  

```
AcceptanceRequired         : False
AvailabilityZones          : {eu-west-1a, eu-west-1b, eu-west-1c}
BaseEndpointDnsNames       : {ecs.eu-west-1.vpce.amazonaws.com}
Owner                      : amazon
PrivateDnsName             : ecs.eu-west-1.amazonaws.com
ServiceName                : com.amazonaws.eu-west-1.ecs
ServiceType                : {Amazon.EC2.Model.ServiceTypeDetail}
VpcEndpointPolicySupported : False
```
**예제 2: 이 예제에서는 모든 EC2 VPC 엔드포인트 서비스를 검색하고 'ssm'과 일치하는 ServiceName을 반환합니다.**  

```
Get-EC2VpcEndpointService -Region eu-west-1 | Select-Object -ExpandProperty Servicenames | Where-Object { -match "ssm"}
```
**출력:**  

```
com.amazonaws.eu-west-1.ssm
com.amazonaws.eu-west-1.ssmmessages
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVpcEndpointServices](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVpcEndpoints` 사용
<a name="example_ec2_DescribeVpcEndpoints_section"></a>

다음 코드 예시는 `DescribeVpcEndpoints`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPC 엔드포인트 설명**  
다음 `describe-vpc-endpoints` 예시에서는 모든 VPC 엔드포인트에 대한 세부 정보를 표시합니다.  

```
aws ec2 describe-vpc-endpoints
```
출력:  

```
{
    "VpcEndpoints": [
        {
            "PolicyDocument": "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"*\",\"Resource\":\"*\"}]}",
            "VpcId": "vpc-aabb1122",
            "NetworkInterfaceIds": [],
            "SubnetIds": [],
            "PrivateDnsEnabled": true,
            "State": "available",
            "ServiceName": "com.amazonaws.us-east-1.dynamodb",
            "RouteTableIds": [
                "rtb-3d560345"
            ],
            "Groups": [],
            "VpcEndpointId": "vpce-032a826a",
            "VpcEndpointType": "Gateway",
            "CreationTimestamp": "2017-09-05T20:41:28Z",
            "DnsEntries": [],
            "OwnerId": "123456789012"
        },
        {
            "PolicyDocument": "{\n  \"Statement\": [\n    {\n      \"Action\": \"*\", \n      \"Effect\": \"Allow\", \n      \"Principal\": \"*\", \n      \"Resource\": \"*\"\n    }\n  ]\n}",
            "VpcId": "vpc-1a2b3c4d",
            "NetworkInterfaceIds": [
                "eni-2ec2b084",
                "eni-1b4a65cf"
            ],
            "SubnetIds": [
                "subnet-d6fcaa8d",
                "subnet-7b16de0c"
            ],
            "PrivateDnsEnabled": false,
            "State": "available",
            "ServiceName": "com.amazonaws.us-east-1.elasticloadbalancing",
            "RouteTableIds": [],
            "Groups": [
                {
                    "GroupName": "default",
                    "GroupId": "sg-54e8bf31"
                }
            ],
            "VpcEndpointId": "vpce-0f89a33420c1931d7",
            "VpcEndpointType": "Interface",
            "CreationTimestamp": "2017-09-05T17:55:27.583Z",
            "DnsEntries": [
                {
                    "HostedZoneId": "Z7HUB22UULQXV",
                    "DnsName": "vpce-0f89a33420c1931d7-bluzidnv.elasticloadbalancing.us-east-1.vpce.amazonaws.com"
                },
                {
                    "HostedZoneId": "Z7HUB22UULQXV",
                    "DnsName": "vpce-0f89a33420c1931d7-bluzidnv-us-east-1b.elasticloadbalancing.us-east-1.vpce.amazonaws.com"
                },
                {
                    "HostedZoneId": "Z7HUB22UULQXV",
                    "DnsName": "vpce-0f89a33420c1931d7-bluzidnv-us-east-1a.elasticloadbalancing.us-east-1.vpce.amazonaws.com"
                }
            ],
            "OwnerId": "123456789012"
        },
        {
            "VpcEndpointId": "vpce-aabbaabbaabbaabba",
            "VpcEndpointType": "GatewayLoadBalancer",
            "VpcId": "vpc-111122223333aabbc",
            "ServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-123123a1c43abc123",
            "State": "available",
            "SubnetIds": [
                "subnet-0011aabbcc2233445"
            ],
            "RequesterManaged": false,
            "NetworkInterfaceIds": [
                "eni-01010120203030405"
            ],
            "CreationTimestamp": "2020-11-11T08:06:03.522Z",
            "Tags": [],
            "OwnerId": "123456789012"
        }
    ]
}
```
자세한 내용은 *AWS PrivateLink 사용 설명서*의 [개념](https://docs.aws.amazon.com/vpc/latest/privatelink/concepts.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVpcEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoints.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 eu-west-1 리전에 대한 하나 이상의 VPC 엔드포인트를 설명합니다. 그런 다음 출력을 다음 명령으로 파이프하여 VpcEndpointId 속성을 선택하고 배열 VPC ID를 문자열 배열로 반환합니다.**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object -ExpandProperty VpcEndpointId
```
**출력:**  

```
vpce-01a2ab3f4f5cc6f7d
vpce-01d2b345a6787890b
vpce-0012e34d567890e12
vpce-0c123db4567890123
```
**예제 2: 이 예제에서는 eu-west-1 리전의 모든 VPC 엔드포인트를 설명하고 VpcEndpointId, VpcId, ServiceName, PrivateDnsEnabled 속성을 선택하여 테이블 형식으로 표시합니다.**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object VpcEndpointId, VpcId, ServiceName, PrivateDnsEnabled | Format-Table -AutoSize
```
**출력:**  

```
VpcEndpointId          VpcId                 ServiceName                         PrivateDnsEnabled
-------------          -----                 -----------                         -----------------
vpce-02a2ab2f2f2cc2f2d vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssm                      True
vpce-01d1b111a1114561b vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2                      True
vpce-0011e23d45167e838 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2messages              True
vpce-0c123db4567890123 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssmmessages              True
```
**예제 3: 이 예제에서는 VPC 엔드포인트 vpce-01a2ab3f4f5cc6f7d에 대한 정책 문서를 json 파일로 내보냅니다.**  

```
Get-EC2VpcEndpoint -Region eu-west-1 -VpcEndpointId vpce-01a2ab3f4f5cc6f7d | Select-Object -expand PolicyDocument | Out-File vpce_policyDocument.json
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVpcEndpoints](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 eu-west-1 리전에 대한 하나 이상의 VPC 엔드포인트를 설명합니다. 그런 다음 출력을 다음 명령으로 파이프하여 VpcEndpointId 속성을 선택하고 배열 VPC ID를 문자열 배열로 반환합니다.**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object -ExpandProperty VpcEndpointId
```
**출력:**  

```
vpce-01a2ab3f4f5cc6f7d
vpce-01d2b345a6787890b
vpce-0012e34d567890e12
vpce-0c123db4567890123
```
**예제 2: 이 예제에서는 eu-west-1 리전의 모든 VPC 엔드포인트를 설명하고 VpcEndpointId, VpcId, ServiceName, PrivateDnsEnabled 속성을 선택하여 테이블 형식으로 표시합니다.**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object VpcEndpointId, VpcId, ServiceName, PrivateDnsEnabled | Format-Table -AutoSize
```
**출력:**  

```
VpcEndpointId          VpcId                 ServiceName                         PrivateDnsEnabled
-------------          -----                 -----------                         -----------------
vpce-02a2ab2f2f2cc2f2d vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssm                      True
vpce-01d1b111a1114561b vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2                      True
vpce-0011e23d45167e838 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2messages              True
vpce-0c123db4567890123 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssmmessages              True
```
**예제 3: 이 예제에서는 VPC 엔드포인트 vpce-01a2ab3f4f5cc6f7d에 대한 정책 문서를 json 파일로 내보냅니다.**  

```
Get-EC2VpcEndpoint -Region eu-west-1 -VpcEndpointId vpce-01a2ab3f4f5cc6f7d | Select-Object -expand PolicyDocument | Out-File vpce_policyDocument.json
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVpcEndpoints](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DescribeVpcs` 함께 사용
<a name="example_ec2_DescribeVpcs_section"></a>

다음 코드 예시는 `DescribeVpcs`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](example_cross_ResilientService_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 
+  [Transit Gateway 시작하기](example_vpc_TransitGatewayGettingStarted_section.md) 
+  [VPC IPAM 시작하기](example_vpc_GettingStartedIpam_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Get the default VPC for the account.
    /// </summary>
    /// <returns>The default VPC object.</returns>
    public async Task<Vpc> GetDefaultVpc()
    {
        try
        {
            var vpcResponse = await _amazonEc2.DescribeVpcsAsync(
                new DescribeVpcsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("is-default", new List<string>() { "true" })
                    }
                });
            return vpcResponse.Vpcs[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "UnauthorizedOperation")
            {
                _logger.LogError(ec2Exception, $"You do not have the necessary permissions to describe VPCs.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the vpcs.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 **AWS SDK for .NET API 참조의 [DescribeVpcs](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeVpcs)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 모든 VPC를 설명하는 방법**  
다음 `describe-vpcs` 예제에서는 VPC에 대한 세부 정보를 검색합니다.  

```
aws ec2 describe-vpcs
```
출력:  

```
{
    "Vpcs": [
        {
            "CidrBlock": "30.1.0.0/16",
            "DhcpOptionsId": "dopt-19edf471",
            "State": "available",
            "VpcId": "vpc-0e9801d129EXAMPLE",
            "OwnerId": "111122223333",
            "InstanceTenancy": "default",
            "CidrBlockAssociationSet": [
                {
                    "AssociationId": "vpc-cidr-assoc-062c64cfafEXAMPLE",
                    "CidrBlock": "30.1.0.0/16",
                    "CidrBlockState": {
                        "State": "associated"
                    }
                }
            ],
            "IsDefault": false,
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Not Shared"
                }
            ]
        },
        {
            "CidrBlock": "10.0.0.0/16",
            "DhcpOptionsId": "dopt-19edf471",
            "State": "available",
            "VpcId": "vpc-06e4ab6c6cEXAMPLE",
            "OwnerId": "222222222222",
            "InstanceTenancy": "default",
            "CidrBlockAssociationSet": [
                {
                    "AssociationId": "vpc-cidr-assoc-00b17b4eddEXAMPLE",
                    "CidrBlock": "10.0.0.0/16",
                    "CidrBlockState": {
                        "State": "associated"
                    }
                }
            ],
            "IsDefault": false,
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Shared VPC"
                }
            ]
        }
    ]
}
```
**예제 2: 지정된 VPC를 설명하는 방법**  
다음 `describe-vpcs` 예제에서는 지정된 VPC에 대한 세부 정보를 검색합니다.  

```
aws ec2 describe-vpcs \
    --vpc-ids vpc-06e4ab6c6cEXAMPLE
```
출력:  

```
{
    "Vpcs": [
        {
            "CidrBlock": "10.0.0.0/16",
            "DhcpOptionsId": "dopt-19edf471",
            "State": "available",
            "VpcId": "vpc-06e4ab6c6cEXAMPLE",
            "OwnerId": "111122223333",
            "InstanceTenancy": "default",
            "CidrBlockAssociationSet": [
                {
                    "AssociationId": "vpc-cidr-assoc-00b17b4eddEXAMPLE",
                    "CidrBlock": "10.0.0.0/16",
                    "CidrBlockState": {
                        "State": "associated"
                    }
                }
            ],
            "IsDefault": false,
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Shared VPC"
                }
            ]
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DescribeVpcs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpcs.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    const client = new EC2Client({});
    const { Vpcs } = await client.send(
      new DescribeVpcsCommand({
        Filters: [{ Name: "is-default", Values: ["true"] }],
      }),
    );
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [DescribeVpcs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeVpcsCommand)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPC를 설명합니다.**  

```
Get-EC2Vpc -VpcId vpc-12345678
```
**출력:**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : available
Tags            : {Name}
VpcId           : vpc-12345678
```
**예제 2: 이 예제에서는 기본 VPC를 설명합니다(리전당 VPC 하나만 있을 수 있음). 계정이 이 리전에서 EC2-Classic을 지원하는 경우 기본 VPC는 존재하지 않습니다.**  

```
Get-EC2Vpc -Filter @{Name="isDefault"; Values="true"}
```
**출력:**  

```
CidrBlock       : 172.31.0.0/16
DhcpOptionsId   : dopt-12345678
InstanceTenancy : default
IsDefault       : True
State           : available
Tags            : {}
VpcId           : vpc-45678901
```
**예제 3: 이 예제에서는 지정된 필터와 일치하는 VPC를 설명합니다(즉, 값이 '10.0.0.0/16'이고 'available' 상태인 CIDR이 있음).**  

```
Get-EC2Vpc -Filter @{Name="cidr"; Values="10.0.0.0/16"},@{Name="state";Values="available"}
```
**예제 4: 이 예제에서는 모든 VPC를 설명합니다.**  

```
Get-EC2Vpc
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVpcs](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPC를 설명합니다.**  

```
Get-EC2Vpc -VpcId vpc-12345678
```
**출력:**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : available
Tags            : {Name}
VpcId           : vpc-12345678
```
**예제 2: 이 예제에서는 기본 VPC를 설명합니다(리전당 VPC 하나만 있을 수 있음). 계정이 이 리전에서 EC2-Classic을 지원하는 경우 기본 VPC는 존재하지 않습니다.**  

```
Get-EC2Vpc -Filter @{Name="isDefault"; Values="true"}
```
**출력:**  

```
CidrBlock       : 172.31.0.0/16
DhcpOptionsId   : dopt-12345678
InstanceTenancy : default
IsDefault       : True
State           : available
Tags            : {}
VpcId           : vpc-45678901
```
**예제 3: 이 예제에서는 지정된 필터와 일치하는 VPC를 설명합니다(즉, 값이 '10.0.0.0/16'이고 'available' 상태인 CIDR이 있음).**  

```
Get-EC2Vpc -Filter @{Name="cidr"; Values="10.0.0.0/16"},@{Name="state";Values="available"}
```
**예제 4: 이 예제에서는 모든 VPC를 설명합니다.**  

```
Get-EC2Vpc
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVpcs](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def get_default_vpc(self) -> Dict[str, Any]:
        """
        Gets the default VPC for the account.

        :return: Data about the default VPC.
        """
        try:
            response = self.ec2_client.describe_vpcs(
                Filters=[{"Name": "is-default", "Values": ["true"]}]
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error("Failed to retrieve the default VPC.")
            if error_code == "UnauthorizedOperation":
                log.error(
                    "You do not have the necessary permissions to describe VPCs. "
                    "Ensure that your AWS IAM user or role has the correct permissions."
                )
            elif error_code == "InvalidParameterValue":
                log.error(
                    "One or more parameters are invalid. Check the request parameters."
                )

            log.error(f"Full error:\n\t{err}")
        else:
            if "Vpcs" in response and response["Vpcs"]:
                log.info(f"Retrieved default VPC: {response['Vpcs'][0]['VpcId']}")
                return response["Vpcs"][0]
            else:
                pass
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeVpcs](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeVpcs)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVpnConnections` 사용
<a name="example_ec2_DescribeVpnConnections_section"></a>

다음 코드 예시는 `DescribeVpnConnections`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: VPN 연결 설명**  
다음 `describe-vpn-connections` 예시에서는 모든 Site-to-Site VPN 연결을 설명합니다.  

```
aws ec2 describe-vpn-connections
```
출력:  

```
{
    "VpnConnections": [
        {
            "CustomerGatewayConfiguration": "...configuration information...",
            "CustomerGatewayId": "cgw-01234567abcde1234",
            "Category": "VPN",
            "State": "available",
            "Type": "ipsec.1",
            "VpnConnectionId": "vpn-1122334455aabbccd",
            "TransitGatewayId": "tgw-00112233445566aab",
            "Options": {
                "EnableAcceleration": false,
                "StaticRoutesOnly": true,
                "LocalIpv4NetworkCidr": "0.0.0.0/0",
                "RemoteIpv4NetworkCidr": "0.0.0.0/0",
                "TunnelInsideIpVersion": "ipv4"
            },
            "Routes": [],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "CanadaVPN"
                }
            ],
            "VgwTelemetry": [
                {
                    "AcceptedRouteCount": 0,
                    "LastStatusChange": "2020-07-29T10:35:11.000Z",
                    "OutsideIpAddress": "203.0.113.3",
                    "Status": "DOWN",
                    "StatusMessage": ""
                },
                {
                    "AcceptedRouteCount": 0,
                    "LastStatusChange": "2020-09-02T09:09:33.000Z",
                    "OutsideIpAddress": "203.0.113.5",
                    "Status": "UP",
                    "StatusMessage": ""
                }
            ]
        }
    ]
}
```
자세한 내용은 Site[AWS Site-to-Site VPN 사용 설명서의 HowSite-to-Site VPN 작동](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html) 방식을 참조하세요. *AWS Site-to-Site *  
**예시 2: 사용 가능한 VPN 연결 설명**  
다음 `describe-vpn-connections` 예시에서는 상태가 `available`인 Site-to-Site VPN 연결을 설명합니다.  

```
aws ec2 describe-vpn-connections \
    --filters "Name=state,Values=available"
```
자세한 내용은 Site[AWS Site-to-Site VPN 사용 설명서의 HowSite-to-Site VPN 작동](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html) 방식을 참조하세요. *AWS Site-to-Site *  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVpnConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpn-connections.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPN 연결을 설명합니다.**  

```
Get-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**출력:**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      : Amazon.EC2.Model.VpnConnectionOptions
Routes                       : {Amazon.EC2.Model.VpnStaticRoute}
State                        : available
Tags                         : {}
Type                         : ipsec.1
VgwTelemetry                 : {Amazon.EC2.Model.VgwTelemetry, Amazon.EC2.Model.VgwTelemetry}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**예제 2: 이 예제에서는 상태가 pending 또는 available인 모든 VPN 연결을 설명합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnConnection -Filter $filter
```
**예제 3: 이 예제에서는 모든 VPN 연결을 설명합니다.**  

```
Get-EC2VpnConnection
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVpnConnections](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPN 연결을 설명합니다.**  

```
Get-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**출력:**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      : Amazon.EC2.Model.VpnConnectionOptions
Routes                       : {Amazon.EC2.Model.VpnStaticRoute}
State                        : available
Tags                         : {}
Type                         : ipsec.1
VgwTelemetry                 : {Amazon.EC2.Model.VgwTelemetry, Amazon.EC2.Model.VgwTelemetry}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**예제 2: 이 예제에서는 상태가 pending 또는 available인 모든 VPN 연결을 설명합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnConnection -Filter $filter
```
**예제 3: 이 예제에서는 모든 VPN 연결을 설명합니다.**  

```
Get-EC2VpnConnection
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVpnConnections](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DescribeVpnGateways` 사용
<a name="example_ec2_DescribeVpnGateways_section"></a>

다음 코드 예시는 `DescribeVpnGateways`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**가상 프라이빗 게이트웨이 설명**  
이 예시에서는 가상 프라이빗 게이트웨이를 설명합니다.  
명령:  

```
aws ec2 describe-vpn-gateways
```
출력:  

```
{
    "VpnGateways": [
        {
            "State": "available",
            "Type": "ipsec.1",
            "VpnGatewayId": "vgw-f211f09b",
            "VpcAttachments": [
                {
                    "State": "attached",
                    "VpcId": "vpc-98eb5ef5"
                }
            ]
        },
        {
            "State": "available",
            "Type": "ipsec.1",
            "VpnGatewayId": "vgw-9a4cacf3",
            "VpcAttachments": [
                {
                    "State": "attaching",
                    "VpcId": "vpc-a01106c2"
                }
            ]
        }
    ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DescribeVpnGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpn-gateways.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 설명합니다.**  

```
Get-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**출력:**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {vpc-12345678}
VpnGatewayId     : vgw-1a2b3c4d
```
**예제 2: 이 예제에서는 상태가 pending 또는 available인 모든 가상 프라이빗 게이트웨이를 설명합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnGateway -Filter $filter
```
**예제 3: 이 예제에서는 모든 가상 프라이빗 게이트웨이를 설명합니다.**  

```
Get-EC2VpnGateway
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeVpnGateways](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 설명합니다.**  

```
Get-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**출력:**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {vpc-12345678}
VpnGatewayId     : vgw-1a2b3c4d
```
**예제 2: 이 예제에서는 상태가 pending 또는 available인 모든 가상 프라이빗 게이트웨이를 설명합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnGateway -Filter $filter
```
**예제 3: 이 예제에서는 모든 가상 프라이빗 게이트웨이를 설명합니다.**  

```
Get-EC2VpnGateway
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeVpnGateways](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DetachInternetGateway` 사용
<a name="example_ec2_DetachInternetGateway_section"></a>

다음 코드 예시는 `DetachInternetGateway`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**VPC에서 인터넷 게이트웨이 분리**  
다음 `detach-internet-gateway` 예시에서는 지정된 인터넷 게이트웨이를 특정 VPC에서 분리합니다.  

```
aws ec2 detach-internet-gateway \
    --internet-gateway-id igw-0d0fb496b3EXAMPLE \
    --vpc-id vpc-0a60eb65b4EXAMPLE
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *Amazon VPC 사용 설명서*의 [인터넷 게이트웨이](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DetachInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-internet-gateway.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인터넷 게이트웨이를 지정된 VPC에서 분리합니다.**  

```
Dismount-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DetachInternetGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인터넷 게이트웨이를 지정된 VPC에서 분리합니다.**  

```
Dismount-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DetachInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DetachNetworkInterface` 사용
<a name="example_ec2_DetachNetworkInterface_section"></a>

다음 코드 예시는 `DetachNetworkInterface`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스에서 네트워크 인터페이스 분리**  
이 예시에서는 지정된 인스턴스에서 지정된 네트워크 인터페이스를 분리합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 detach-network-interface --attachment-id eni-attach-66c4350a
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DetachNetworkInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-network-interface.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 네트워크 인터페이스와 인스턴스 간에 지정된 연결을 제거합니다.**  

```
Dismount-EC2NetworkInterface -AttachmentId eni-attach-1a2b3c4d -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DetachNetworkInterface](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 네트워크 인터페이스와 인스턴스 간에 지정된 연결을 제거합니다.**  

```
Dismount-EC2NetworkInterface -AttachmentId eni-attach-1a2b3c4d -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DetachNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DetachVolume` 사용
<a name="example_ec2_DetachVolume_section"></a>

다음 코드 예시는 `DetachVolume`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스에서 볼륨 분리**  
이 예시 명령은 볼륨(`vol-049df61146c4d7901`)이 연결된 인스턴스에서 볼륨을 분리합니다.  
명령:  

```
aws ec2 detach-volume --volume-id vol-1234567890abcdef0
```
출력:  

```
{
    "AttachTime": "2014-02-27T19:23:06.000Z",
    "InstanceId": "i-1234567890abcdef0",
    "VolumeId": "vol-049df61146c4d7901",
    "State": "detaching",
    "Device": "/dev/sdb"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DetachVolume](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-volume.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 볼륨을 분리합니다.**  

```
Dismount-EC2Volume -VolumeId vol-12345678
```
**출력:**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : detaching
VolumeId            : vol-12345678
```
**예제 2: 인스턴스 ID와 디바이스 이름을 지정하여 올바른 볼륨을 분리할 수도 있습니다.**  

```
Dismount-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DetachVolume](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 볼륨을 분리합니다.**  

```
Dismount-EC2Volume -VolumeId vol-12345678
```
**출력:**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : detaching
VolumeId            : vol-12345678
```
**예제 2: 인스턴스 ID와 디바이스 이름을 지정하여 올바른 볼륨을 분리할 수도 있습니다.**  

```
Dismount-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DetachVolume](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DetachVpnGateway` 사용
<a name="example_ec2_DetachVpnGateway_section"></a>

다음 코드 예시는 `DetachVpnGateway`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPC에서 가상 프라이빗 게이트웨이 분리**  
이 예시에서는 지정한 가상 프라이빗 게이트웨이를 지정한 VPC에서 분리합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 detach-vpn-gateway --vpn-gateway-id vgw-9a4cacf3 --vpc-id vpc-a01106c2
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DetachVpnGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-vpn-gateway.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 지정된 VPC에서 분리합니다.**  

```
Dismount-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DetachVpnGateway](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 가상 프라이빗 게이트웨이를 지정된 VPC에서 분리합니다.**  

```
Dismount-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DetachVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DisableVgwRoutePropagation` 사용
<a name="example_ec2_DisableVgwRoutePropagation_section"></a>

다음 코드 예시는 `DisableVgwRoutePropagation`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**라우팅 전파 비활성화**  
이 예시에서는 지정된 가상 프라이빗 게이트웨이가 지정된 라우팅 테이블로 정적 경로를 전파하지 못하도록 합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 disable-vgw-route-propagation --route-table-id rtb-22574640 --gateway-id vgw-9a4cacf3
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DisableVgwRoutePropagation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-vgw-route-propagation.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 VGW가 지정된 라우팅 테이블에 경로를 자동으로 전파하지 못하도록 합니다.**  

```
Disable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DisableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 VGW가 지정된 라우팅 테이블에 경로를 자동으로 전파하지 못하도록 합니다.**  

```
Disable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DisableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DisableVpcClassicLink` 사용
<a name="example_ec2_DisableVpcClassicLink_section"></a>

다음 코드 예시는 `DisableVpcClassicLink`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPC의 ClassicLink 비활성화**  
이 예시에서는 vpc-8888888용 ClassicLink를 비활성화합니다.  
명령:  

```
aws ec2 disable-vpc-classic-link --vpc-id vpc-88888888
```
출력:  

```
{
  "Return": true
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DisableVpcClassicLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-vpc-classic-link.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 vpc-01e23c4a5d6db78e9에 대한 EC2VpcClassicLink를 비활성화합니다. 그러면 True 또는 False가 반환됩니다.**  

```
Disable-EC2VpcClassicLink -VpcId vpc-01e23c4a5d6db78e9
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DisableVpcClassicLink](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 vpc-01e23c4a5d6db78e9에 대한 EC2VpcClassicLink를 비활성화합니다. 그러면 True 또는 False가 반환됩니다.**  

```
Disable-EC2VpcClassicLink -VpcId vpc-01e23c4a5d6db78e9
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DisableVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DisableVpcClassicLinkDnsSupport` 사용
<a name="example_ec2_DisableVpcClassicLinkDnsSupport_section"></a>

다음 코드 예시는 `DisableVpcClassicLinkDnsSupport`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPC에 대한 ClassicLink DNS 지원 비활성화**  
이 예시에서는 `vpc-88888888`에 대한 ClassicLink DNS 지원을 비활성화합니다.  
명령:  

```
aws ec2 disable-vpc-classic-link-dns-support --vpc-id vpc-88888888
```
출력:  

```
{
  "Return": true
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DisableVpcClassicLinkDnsSupport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-vpc-classic-link-dns-support.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 vpc-0b12d3456a7e8910d에 대한 ClassicLink DNS 지원을 비활성화합니다.**  

```
Disable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DisableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 vpc-0b12d3456a7e8910d에 대한 ClassicLink DNS 지원을 비활성화합니다.**  

```
Disable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DisableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `DisassociateAddress` 함께 사용
<a name="example_ec2_DisassociateAddress_section"></a>

다음 코드 예시는 `DisassociateAddress`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Disassociate an Elastic IP address from an EC2 instance.
    /// </summary>
    /// <param name="associationId">The association Id.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DisassociateIp(string associationId)
    {
        try
        {
            var response = await _amazonEC2.DisassociateAddressAsync(
                new DisassociateAddressRequest { AssociationId = associationId });
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidAssociationID.NotFound")
            {
                _logger.LogError(
                    $"AssociationId is invalid, unable to disassociate address. {ec2Exception.Message}");
            }

            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while disassociating the Elastic IP.: {ex.Message}");
            return false;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DisassociateAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DisassociateAddress)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_disassociate_address
#
# This function disassociates an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       -a association_id - The association ID that represents the association of the Elastic IP address with an instance.
#
# And:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_disassociate_address() {
  local association_id response

  # Function to display usage information
  function usage() {
    echo "function ec2_disassociate_address"
    echo "Disassociates an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance."
    echo "  -a association_id - The association ID that represents the association of the Elastic IP address with an instance."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "a:h" option; do
    case "${option}" in
      a) association_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$association_id" ]]; then
    errecho "ERROR: You must provide an association ID with the -a parameter."
    return 1
  fi

  response=$(aws ec2 disassociate-address \
    --association-id "$association_id") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports disassociate-address operation failed."
    errecho "$response"
    return 1
  }

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DisassociateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DisassociateAddress)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**EC2-Classic에서 탄력적 IP 주소를 연결 해제하는 방법**  
이 예제에서는 EC2-Classic의 인스턴스에서 탄력적 IP 주소를 연결 해제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 disassociate-address --public-ip 198.51.100.0
```
**EC2-VPC에서 탄력적 IP 주소를 연결 해제하는 방법**  
이 예제에서는 VPC의 인스턴스에서 탄력적 IP 주소를 연결 해제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 disassociate-address --association-id eipassoc-2bebb745
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [DisassociateAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-address.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Disassociates an Elastic IP address from an instance asynchronously.
     *
     * @param associationId The ID of the association you want to disassociate.
     * @return a {@link CompletableFuture} representing the asynchronous operation of disassociating the address. The
     *         {@link CompletableFuture} will complete with a {@link DisassociateAddressResponse} when the operation is
     *         finished.
     * @throws RuntimeException if the disassociation of the address fails.
     */
    public CompletableFuture<DisassociateAddressResponse> disassociateAddressAsync(String associationId) {
        Ec2AsyncClient ec2 = getAsyncClient();
        DisassociateAddressRequest addressRequest = DisassociateAddressRequest.builder()
            .associationId(associationId)
            .build();

        // Disassociate the address asynchronously.
        CompletableFuture<DisassociateAddressResponse> response = ec2.disassociateAddress(addressRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
               throw new RuntimeException("Failed to disassociate address", ex);
            }
        });

        return response;
    }
```
+  API 세부 정보는  *AWS SDK for Java 2.x API 참조*의 [DisassociateAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DisassociateAddress)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { DisassociateAddressCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Disassociate an Elastic IP address from an instance.
 * @param {{ associationId: string }} options
 */
export const main = async ({ associationId }) => {
  const client = new EC2Client({});
  const command = new DisassociateAddressCommand({
    // You can also use PublicIp, but that is for EC2 classic which is being retired.
    AssociationId: associationId,
  });

  try {
    await client.send(command);
    console.log("Successfully disassociated address");
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidAssociationID.NotFound"
    ) {
      console.warn(`${caught.message}.`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는  *AWS SDK for JavaScript API 참조*의 [DisassociateAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DisassociateAddressCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun disassociateAddressSc(associationIdVal: String?) {
    val addressRequest =
        DisassociateAddressRequest {
            associationId = associationIdVal
        }
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.disassociateAddress(addressRequest)
        println("You successfully disassociated the address!")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DisassociateAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 VPC의 지정된 인스턴스에서 지정된 탄력적 IP 주소의 연결을 해제합니다.**  

```
Unregister-EC2Address -AssociationId eipassoc-12345678
```
**예제 2: 이 예제에서는 EC2-Classic의 지정된 인스턴스에서 지정된 탄력적 IP 주소의 연결을 해제합니다.**  

```
Unregister-EC2Address -PublicIp 203.0.113.17
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DisassociateAddress](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 VPC의 지정된 인스턴스에서 지정된 탄력적 IP 주소의 연결을 해제합니다.**  

```
Unregister-EC2Address -AssociationId eipassoc-12345678
```
**예제 2: 이 예제에서는 EC2-Classic의 지정된 인스턴스에서 지정된 탄력적 IP 주소의 연결을 해제합니다.**  

```
Unregister-EC2Address -PublicIp 203.0.113.17
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DisassociateAddress](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class ElasticIpWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface."""

    class ElasticIp:
        """Represents an Elastic IP and its associated instance."""

        def __init__(
            self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None
        ) -> None:
            """
            Initializes the ElasticIp object.

            :param allocation_id: The allocation ID of the Elastic IP.
            :param public_ip: The public IP address of the Elastic IP.
            :param instance_id: The ID of the associated EC2 instance, if any.
            """
            self.allocation_id = allocation_id
            self.public_ip = public_ip
            self.instance_id = instance_id

    def __init__(self, ec2_client: Any) -> None:
        """
        Initializes the ElasticIpWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client
        self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = []

    @classmethod
    def from_client(cls) -> "ElasticIpWrapper":
        """
        Creates an ElasticIpWrapper instance with a default EC2 client.

        :return: An instance of ElasticIpWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def disassociate(self, allocation_id: str) -> None:
        """
        Removes an association between an Elastic IP address and an instance. When the
        association is removed, the instance is assigned a new public IP address.

        :param allocation_id: The allocation ID of the Elastic IP to disassociate.
        :raises ClientError: If the disassociation fails, such as when the association ID is not found.
        """
        elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id)
        if elastic_ip is None or elastic_ip.instance_id is None:
            logger.info(
                f"No association found for Elastic IP with allocation ID {allocation_id}."
            )
            return

        try:
            # Retrieve the association ID before disassociating
            response = self.ec2_client.describe_addresses(AllocationIds=[allocation_id])
            association_id = response["Addresses"][0].get("AssociationId")

            if association_id:
                self.ec2_client.disassociate_address(AssociationId=association_id)
                elastic_ip.instance_id = None  # Remove the instance association
            else:
                logger.info(
                    f"No Association ID found for Elastic IP with allocation ID {allocation_id}."
                )

        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidAssociationID.NotFound":
                logger.error(
                    f"Failed to disassociate Elastic IP {allocation_id} "
                    "because the specified association ID for the Elastic IP address was not found. "
                    "Verify the association ID and ensure the Elastic IP is currently associated with a "
                    "resource before attempting to disassociate it."
                )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DisassociateAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DisassociateAddress)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn disassociate_ip_address(&self, association_id: &str) -> Result<(), EC2Error> {
        self.client
            .disassociate_address()
            .association_id(association_id)
            .send()
            .await?;
        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DisassociateAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.disassociate_address)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Disassociate an Elastic IP.
    /// 
    /// - Parameter associationId: The ID of the association to end.
    func disassociateAddress(associationId: String?) async {
        do {
            _ = try await ec2Client.disassociateAddress(
                input: DisassociateAddressInput(
                    associationId: associationId
                )
            )
        } catch {
            print("*** Unable to disassociate the IP address: \(error.localizedDescription)")
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DisassociateAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/disassociateaddress(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `DisassociateRouteTable` 사용
<a name="example_ec2_DisassociateRouteTable_section"></a>

다음 코드 예시는 `DisassociateRouteTable`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**라우팅 테이블의 연결 해제**  
이 예시에서는 지정한 라우팅 테이블을 지정한 서브넷에서 연결 해제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 disassociate-route-table --association-id rtbassoc-781d0d1a
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DisassociateRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-route-table.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 라우팅 테이블과 서브넷 간의 지정된 연결을 제거합니다.**  

```
Unregister-EC2RouteTable -AssociationId rtbassoc-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DisassociateRouteTable](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 라우팅 테이블과 서브넷 간의 지정된 연결을 제거합니다.**  

```
Unregister-EC2RouteTable -AssociationId rtbassoc-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DisassociateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `EnableVgwRoutePropagation` 사용
<a name="example_ec2_EnableVgwRoutePropagation_section"></a>

다음 코드 예시는 `EnableVgwRoutePropagation`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**라우팅 전파 활성화**  
이 예시에서는 지정된 가상 프라이빗 게이트웨이가 지정된 라우팅 테이블로 정적 경로를 전파하도록 설정합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 enable-vgw-route-propagation --route-table-id rtb-22574640 --gateway-id vgw-9a4cacf3
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [EnableVgwRoutePropagation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-vgw-route-propagation.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VGW가 지정된 라우팅 테이블에 경로를 자동으로 전파할 수 있도록 합니다.**  

```
Enable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [EnableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VGW가 지정된 라우팅 테이블에 경로를 자동으로 전파할 수 있도록 합니다.**  

```
Enable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [EnableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `EnableVolumeIo` 사용
<a name="example_ec2_EnableVolumeIo_section"></a>

다음 코드 예시는 `EnableVolumeIo`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**볼륨에 대한 I/O 활성화**  
이 예시에서는 `vol-1234567890abcdef0` 볼륨에서 I/O를 활성화합니다.  
명령:  

```
aws ec2 enable-volume-io --volume-id vol-1234567890abcdef0
```
출력:  

```
{
  "Return": true
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [EnableVolumeIo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-volume-io.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 I/O 작업이 비활성화된 경우 지정된 볼륨에 대한 I/O 작업을 활성화합니다.**  

```
Enable-EC2VolumeIO -VolumeId vol-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [EnableVolumeIo](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 I/O 작업이 비활성화된 경우 지정된 볼륨에 대한 I/O 작업을 활성화합니다.**  

```
Enable-EC2VolumeIO -VolumeId vol-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [EnableVolumeIo](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `EnableVpcClassicLink` 사용
<a name="example_ec2_EnableVpcClassicLink_section"></a>

다음 코드 예시는 `EnableVpcClassicLink`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPC에서 ClassicLink 활성화**  
이 예시에서는 ClassicLink에 vpc-8888888을 활성화합니다.  
명령:  

```
aws ec2 enable-vpc-classic-link --vpc-id vpc-88888888
```
출력:  

```
{
  "Return": true
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [EnableVpcClassicLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-vpc-classic-link.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 ClassicLink에 대해 VPC vpc-0123456b789b0d12f를 활성화합니다.**  

```
Enable-EC2VpcClassicLink -VpcId vpc-0123456b789b0d12f
```
**출력:**  

```
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [EnableVpcClassicLink](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 ClassicLink에 대해 VPC vpc-0123456b789b0d12f를 활성화합니다.**  

```
Enable-EC2VpcClassicLink -VpcId vpc-0123456b789b0d12f
```
**출력:**  

```
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [EnableVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `EnableVpcClassicLinkDnsSupport` 사용
<a name="example_ec2_EnableVpcClassicLinkDnsSupport_section"></a>

다음 코드 예시는 `EnableVpcClassicLinkDnsSupport`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**ClassicLink DNS 지원 활성화**  
이 예시에서는 `vpc-88888888`에 대한 ClassicLink DNS 지원을 활성화합니다.  
명령:  

```
aws ec2 enable-vpc-classic-link-dns-support --vpc-id vpc-88888888
```
출력:  

```
{
  "Return": true
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [EnableVpcClassicLinkDnsSupport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-vpc-classic-link-dns-support.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 vpc-0b12d3456a7e8910d가 ClassicLink에 대한 DNS 호스트 이름 해석 지원을 활성화합니다.**  

```
Enable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [EnableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 vpc-0b12d3456a7e8910d가 ClassicLink에 대한 DNS 호스트 이름 해석 지원을 활성화합니다.**  

```
Enable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [EnableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `GetConsoleOutput` 사용
<a name="example_ec2_GetConsoleOutput_section"></a>

다음 코드 예시는 `GetConsoleOutput`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 콘솔 출력을 가져오는 방법**  
다음 `get-console-output` 예시에서는 지정된 Linux 인스턴스에 대한 콘솔 출력을 가져옵니다.  

```
aws ec2 get-console-output \
    --instance-id i-1234567890abcdef0
```
출력:  

```
{
    "InstanceId": "i-1234567890abcdef0",
    "Timestamp": "2013-07-25T21:23:53.000Z",
    "Output": "..."
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [인스턴스 콘솔 출력](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html#instance-console-console-output)을 참조하세요.  
**예시 2: 최신 콘솔 출력을 가져오는 방법**  
다음 `get-console-output` 예시에서는 지정된 Linux 인스턴스에 대한 최신 콘솔 출력을 가져옵니다.  

```
aws ec2 get-console-output \
    --instance-id i-1234567890abcdef0 \
    --latest \
    --output text
```
출력:  

```
i-1234567890abcdef0 [    0.000000] Command line: root=LABEL=/ console=tty1 console=ttyS0 selinux=0 nvme_core.io_timeout=4294967295
[    0.000000] x86/fpu: Supporting XSAVE feature 0x001: 'x87 floating point registers'
[    0.000000] x86/fpu: Supporting XSAVE feature 0x002: 'SSE registers'
[    0.000000] x86/fpu: Supporting XSAVE feature 0x004: 'AVX registers'
...
Cloud-init v. 0.7.6 finished at Wed, 09 May 2018 19:01:13 +0000. Datasource DataSourceEc2.  Up 21.50 seconds
Amazon Linux AMI release 2018.03
Kernel 4.14.26-46.32.amzn1.x
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [인스턴스 콘솔 출력](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html#instance-console-console-output)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [GetConsoleOutput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-console-output.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 Linux 인스턴스에 대한 콘솔 출력을 가져옵니다. 콘솔 출력이 인코딩됩니다.**  

```
Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456
```
**출력:**  

```
InstanceId          Output
----------          ------
i-0e194d3c47c123637 WyAgICAwLjAwMDAwMF0gQ29tbW...bGU9dHR5UzAgc2Vs
```
**예제 2: 이 예제에서는 인코딩된 콘솔 출력을 변수에 저장한 다음 디코딩합니다.**  

```
$Output_encoded = (Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456).Output
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Output_encoded))
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetConsoleOutput](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 Linux 인스턴스에 대한 콘솔 출력을 가져옵니다. 콘솔 출력이 인코딩됩니다.**  

```
Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456
```
**출력:**  

```
InstanceId          Output
----------          ------
i-0e194d3c47c123637 WyAgICAwLjAwMDAwMF0gQ29tbW...bGU9dHR5UzAgc2Vs
```
**예제 2: 이 예제에서는 인코딩된 콘솔 출력을 변수에 저장한 다음 디코딩합니다.**  

```
$Output_encoded = (Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456).Output
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Output_encoded))
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetConsoleOutput](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `GetHostReservationPurchasePreview` 사용
<a name="example_ec2_GetHostReservationPurchasePreview_section"></a>

다음 코드 예시는 `GetHostReservationPurchasePreview`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**전용 호스트 예약에 대한 구매 미리 보기를 가져오는 방법**  
이 예시에서는 계정에서 지정한 전용 호스트에 대한 지정 전용 호스트 예약의 비용을 미리 볼 수 있습니다.  
명령:  

```
aws ec2 get-host-reservation-purchase-preview --offering-id hro-03f707bf363b6b324 --host-id-set h-013abcd2a00cbd123
```
출력:  

```
{
  "TotalHourlyPrice": "1.499",
  "Purchase": [
      {
          "HourlyPrice": "1.499",
          "InstanceFamily": "m4",
          "PaymentOption": "NoUpfront",
          "HostIdSet": [
              "h-013abcd2a00cbd123"
          ],
          "UpfrontPrice": "0.000",
          "Duration": 31536000
      }
  ],
  "TotalUpfrontPrice": "0.000"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [GetHostReservationPurchasePreview](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-host-reservation-purchase-preview.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 전용 호스트 h-01e23f4cd567890f1의 구성과 일치하는 구성의 예약 구매를 미리 봅니다.**  

```
Get-EC2HostReservationPurchasePreview -OfferingId hro-0c1f23456789d0ab -HostIdSet h-01e23f4cd567890f1
```
**출력:**  

```
CurrencyCode Purchase TotalHourlyPrice TotalUpfrontPrice
------------ -------- ---------------- -----------------
             {}       1.307            0.000
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetHostReservationPurchasePreview](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 전용 호스트 h-01e23f4cd567890f1의 구성과 일치하는 구성의 예약 구매를 미리 봅니다.**  

```
Get-EC2HostReservationPurchasePreview -OfferingId hro-0c1f23456789d0ab -HostIdSet h-01e23f4cd567890f1
```
**출력:**  

```
CurrencyCode Purchase TotalHourlyPrice TotalUpfrontPrice
------------ -------- ---------------- -----------------
             {}       1.307            0.000
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetHostReservationPurchasePreview](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `GetPasswordData` 함께 사용
<a name="example_ec2_GetPasswordData_section"></a>

다음 코드 예시는 `GetPasswordData`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**암호화된 암호를 가져오는 방법**  
이 예시에서는 암호화된 암호를 가져옵니다.  
명령:  

```
aws ec2 get-password-data --instance-id i-1234567890abcdef0
```
출력:  

```
{
    "InstanceId": "i-1234567890abcdef0",
    "Timestamp": "2013-08-07T22:18:38.000Z",
    "PasswordData": "gSlJFq+VpcZXqy+iktxMF6NyxQ4qCrT4+gaOuNOenX1MmgXPTj7XEXAMPLE
UQ+YeFfb+L1U4C4AKv652Ux1iRB3CPTYP7WmU3TUnhsuBd+p6LVk7T2lKUml6OXbk6WPW1VYYm/TRPB1
e1DQ7PY4an/DgZT4mwcpRFigzhniQgDDeO1InvSDcwoUTwNs0Y1S8ouri2W4n5GNlriM3Q0AnNVelVz/
53TkDtxbNoU606M1gK9zUWSxqEgwvbV2j8c5rP0WCuaMWSFl4ziDu4bd7q+4RSyi8NUsVWnKZ4aEZffu
DPGzKrF5yLlf3etP2L4ZR6CvG7K1hx7VKOQVN32Dajw=="
}
```
**복호화된 암호를 가져오는 방법**  
이 예시에서는 해독된 암호를 가져옵니다.  
명령:  

```
aws ec2 get-password-data --instance-id  i-1234567890abcdef0 --priv-launch-key C:\Keys\MyKeyPair.pem
```
출력:  

```
{
    "InstanceId": "i-1234567890abcdef0",
    "Timestamp": "2013-08-30T23:18:05.000Z",
    "PasswordData": "&ViJ652e*u"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [GetPasswordData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-password-data.html) 섹션을 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2AsyncClient;
import software.amazon.awssdk.services.ec2.model.*;
import java.util.concurrent.CompletableFuture;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class GetPasswordData {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                   <instanceId> 

                Where:
                   instanceId - An instance id value that you can obtain from the AWS Management Console.\s
             """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }
        String instanceId = args[0];
        Ec2AsyncClient ec2AsyncClient = Ec2AsyncClient.builder()
            .region(Region.US_EAST_1)
            .build();

        try {
            CompletableFuture<Void> future = getPasswordDataAsync(ec2AsyncClient, instanceId);
            future.join();
        } catch (RuntimeException rte) {
            System.err.println("An exception occurred: " + (rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage()));
        }
    }

    /**
     * Fetches the password data for the specified EC2 instance asynchronously.
     *
     * @param ec2AsyncClient the EC2 asynchronous client to use for the request
     * @param instanceId instanceId the ID of the EC2 instance for which you want to fetch the password data
     * @return a {@link CompletableFuture} that completes when the password data has been fetched
     * @throws RuntimeException if there was a failure in fetching the password data
     */
    public static CompletableFuture<Void> getPasswordDataAsync(Ec2AsyncClient ec2AsyncClient, String instanceId) {
        GetPasswordDataRequest getPasswordDataRequest = GetPasswordDataRequest.builder()
            .instanceId(instanceId)
            .build();


        CompletableFuture<GetPasswordDataResponse> response = ec2AsyncClient.getPasswordData(getPasswordDataRequest);
        response.whenComplete((getPasswordDataResponse, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to get password data for instance: " + instanceId, ex);
            } else if (getPasswordDataResponse == null || getPasswordDataResponse.passwordData().isEmpty()) {
                throw new RuntimeException("No password data found for instance: " + instanceId);
            } else {
                String encryptedPasswordData = getPasswordDataResponse.passwordData();
                System.out.println("Encrypted Password Data: " + encryptedPasswordData);
            }
        });

        return response.thenApply(resp -> null);
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [GetPasswordData](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/GetPasswordData)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 Amazon EC2가 지정된 Windows 인스턴스의 관리자 계정에 할당한 암호를 해독합니다. pem 파일이 지정되면 -Decrypt 스위치의 설정이 자동으로 수임됩니다.**  

```
Get-EC2PasswordData -InstanceId i-12345678 -PemFile C:\path\my-key-pair.pem
```
**출력:**  

```
mYZ(PA9?C)Q
```
**예제 2: (Windows PowerShell만 해당) 인스턴스를 검사하여 인스턴스를 시작하는 데 사용되는 키 페어의 이름을 확인한 다음 AWS Toolkit for Visual Studio의 구성 스토어에서 해당 키 페어 데이터를 찾으려고 시도합니다. 키 페어 데이터가 발견되면 암호가 해독됩니다.**  

```
Get-EC2PasswordData -InstanceId i-12345678 -Decrypt
```
**출력:**  

```
mYZ(PA9?C)Q
```
**예제 3: 인스턴스에 대해 암호화된 암호 데이터를 반환합니다.**  

```
Get-EC2PasswordData -InstanceId i-12345678
```
**출력:**  

```
iVz3BAK/WAXV.....dqt8WeMA==
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetPasswordData](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 Amazon EC2가 지정된 Windows 인스턴스의 관리자 계정에 할당한 암호를 해독합니다. pem 파일이 지정되면 -Decrypt 스위치의 설정이 자동으로 수임됩니다.**  

```
Get-EC2PasswordData -InstanceId i-12345678 -PemFile C:\path\my-key-pair.pem
```
**출력:**  

```
mYZ(PA9?C)Q
```
**예제 2: (Windows PowerShell만 해당) 인스턴스를 검사하여 인스턴스를 시작하는 데 사용되는 키 페어의 이름을 확인한 다음 AWS Toolkit for Visual Studio의 구성 스토어에서 해당 키 페어 데이터를 찾으려고 시도합니다. 키 페어 데이터가 발견되면 암호가 해독됩니다.**  

```
Get-EC2PasswordData -InstanceId i-12345678 -Decrypt
```
**출력:**  

```
mYZ(PA9?C)Q
```
**예제 3: 인스턴스에 대해 암호화된 암호 데이터를 반환합니다.**  

```
Get-EC2PasswordData -InstanceId i-12345678
```
**출력:**  

```
iVz3BAK/WAXV.....dqt8WeMA==
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetPasswordData](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ImportImage` 사용
<a name="example_ec2_ImportImage_section"></a>

다음 코드 예시는 `ImportImage`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VM 이미지 파일을 AMI로 가져오는 방법**  
다음 `import-image` 예시에서는 지정된 OVA를 가져옵니다.  

```
aws ec2 import-image \
  --disk-containers Format=ova,UserBucket="{S3Bucket=my-import-bucket,S3Key=vms/my-server-vm.ova}"
```
출력:  

```
{
    "ImportTaskId": "import-ami-1234567890abcdef0",
    "Progress": "2",
    "SnapshotDetails": [
        {
            "DiskImageSize": 0.0,
            "Format": "ova",
            "UserBucket": {
                "S3Bucket": "my-import-bucket",
                "S3Key": "vms/my-server-vm.ova"
            }
        }
    ],
    "Status": "active",
    "StatusMessage": "pending"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ImportImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/import-image.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 멱등성 토큰을 사용하여 지정된 Amazon S3 버킷에서 Amazon EC2로 단일 디스크 가상 머신 이미지를 가져옵니다. 이 예제에서는 기본 이름이 'vmimport'인 VM Import 서비스 역할이 있어야 하며, VM Import 사전 조건 주제에 설명된 대로 지정된 버킷에 대한 Amazon EC2 액세스를 허용하는 정책이 있어야 합니다. 사용자 지정 역할을 사용하려면 `-RoleName` 파라미터를 사용하여 역할 이름을 지정합니다.**  

```
$container = New-Object Amazon.EC2.Model.ImageDiskContainer
$container.Format="VMDK"
$container.UserBucket = New-Object Amazon.EC2.Model.UserBucket
$container.UserBucket.S3Bucket = "amzn-s3-demo-bucket"
$container.UserBucket.S3Key = "Win_2008_Server_Standard_SP2_64-bit-disk1.vmdk"

$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Windows 2008 Standard Image Import"
    "Platform"="Windows"
    "LicenseType"="AWS"
}

Import-EC2Image -DiskContainer $container @parms
```
**출력:**  

```
Architecture    : 
Description     : Windows 2008 Standard Image
Hypervisor      : 
ImageId         : 
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        : 2
SnapshotDetails : {}
Status          : active
StatusMessage   : pending
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ImportImage](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 멱등성 토큰을 사용하여 지정된 Amazon S3 버킷에서 Amazon EC2로 단일 디스크 가상 머신 이미지를 가져옵니다. 이 예제에서는 기본 이름이 'vmimport'인 VM Import 서비스 역할이 있어야 하며, VM Import 사전 조건 주제에 설명된 대로 지정된 버킷에 대한 Amazon EC2 액세스를 허용하는 정책이 있어야 합니다. 사용자 지정 역할을 사용하려면 `-RoleName` 파라미터를 사용하여 역할 이름을 지정합니다.**  

```
$container = New-Object Amazon.EC2.Model.ImageDiskContainer
$container.Format="VMDK"
$container.UserBucket = New-Object Amazon.EC2.Model.UserBucket
$container.UserBucket.S3Bucket = "amzn-s3-demo-bucket"
$container.UserBucket.S3Key = "Win_2008_Server_Standard_SP2_64-bit-disk1.vmdk"

$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Windows 2008 Standard Image Import"
    "Platform"="Windows"
    "LicenseType"="AWS"
}

Import-EC2Image -DiskContainer $container @parms
```
**출력:**  

```
Architecture    : 
Description     : Windows 2008 Standard Image
Hypervisor      : 
ImageId         : 
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        : 2
SnapshotDetails : {}
Status          : active
StatusMessage   : pending
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ImportImage](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ImportKeyPair` 사용
<a name="example_ec2_ImportKeyPair_section"></a>

다음 코드 예시는 `ImportKeyPair`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**퍼블릭 키 가져오기**  
먼저 원하는 도구로 키 쌍을 생성합니다. 예를 들어 다음 ssh-keygen 명령을 사용합니다.  
명령:  

```
ssh-keygen -t rsa -C "my-key" -f ~/.ssh/my-key
```
출력:  

```
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ec2-user/.ssh/my-key.
Your public key has been saved in /home/ec2-user/.ssh/my-key.pub.
...
```
이 예시 명령은 지정된 퍼블릭 키를 가져옵니다.  
명령:  

```
aws ec2 import-key-pair --key-name "my-key" --public-key-material fileb://~/.ssh/my-key.pub
```
출력:  

```
{
  "KeyName": "my-key",
  "KeyFingerprint": "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ImportKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/import-key-pair.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 퍼블릭 키를 EC2로 가져옵니다. 첫 번째 줄은 퍼블릭 키 파일(\$1.pub)의 내용을 변수 `$publickey`에 저장합니다. 다음 예제에서는 퍼블릭 키 파일의 UTF8 형식을 Base64-encoded 문자열로 변환하고, 변환된 문자열을 `$pkbase64` 변수에 저장합니다. 마지막 줄에서는 변환된 퍼블릭 키를 EC2로 가져옵니다. cmdlet은 키 지문과 이름을 결과로 반환합니다.**  

```
$publickey=[Io.File]::ReadAllText("C:\Users\TestUser\.ssh\id_rsa.pub")
$pkbase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($publickey))
Import-EC2KeyPair -KeyName Example-user-key -PublicKey $pkbase64
```
**출력:**  

```
KeyFingerprint                                  KeyName
--------------                                  -------
do:d0:15:8f:79:97:12:be:00:fd:df:31:z3:b1:42:z1 Example-user-key
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ImportKeyPair](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 퍼블릭 키를 EC2로 가져옵니다. 첫 번째 줄은 퍼블릭 키 파일(\$1.pub)의 내용을 변수 `$publickey`에 저장합니다. 다음 예제에서는 퍼블릭 키 파일의 UTF8 형식을 Base64-encoded 문자열로 변환하고, 변환된 문자열을 `$pkbase64` 변수에 저장합니다. 마지막 줄에서는 변환된 퍼블릭 키를 EC2로 가져옵니다. cmdlet은 키 지문과 이름을 결과로 반환합니다.**  

```
$publickey=[Io.File]::ReadAllText("C:\Users\TestUser\.ssh\id_rsa.pub")
$pkbase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($publickey))
Import-EC2KeyPair -KeyName Example-user-key -PublicKey $pkbase64
```
**출력:**  

```
KeyFingerprint                                  KeyName
--------------                                  -------
do:d0:15:8f:79:97:12:be:00:fd:df:31:z3:b1:42:z1 Example-user-key
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ImportKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ImportSnapshot` 사용
<a name="example_ec2_ImportSnapshot_section"></a>

다음 코드 예시는 `ImportSnapshot`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스냅샷을 가져오는 방법**  
다음 `import-snapshot` 예시에서는 지정된 디스크를 스냅샷으로 가져옵니다.  

```
aws ec2 import-snapshot \
    --description "My server VMDK" \
    --disk-container Format=VMDK,UserBucket={'S3Bucket=my-import-bucket,S3Key=vms/my-server-vm.vmdk'}
```
출력:  

```
{
    "Description": "My server VMDK",
    "ImportTaskId": "import-snap-1234567890abcdef0",
    "SnapshotTaskDetail": {
        "Description": "My server VMDK",
        "DiskImageSize": "0.0",
        "Format": "VMDK",
        "Progress": "3",
        "Status": "active",
        "StatusMessage": "pending"
        "UserBucket": {
            "S3Bucket": "my-import-bucket",
            "S3Key": "vms/my-server-vm.vmdk"
        }
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ImportSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/import-snapshot.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 'VMDK' 형식의 VM 디스크 이미지를 Amazon EBS 스냅샷으로 가져옵니다. 이 예제에서는 http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/VMImportPrerequisites.html 페이지의 `VM Import Prequisites` 주제에 설명된 대로 지정된 버킷에 대한 Amazon EC2 액세스를 허용하는 정책과 함께 기본 이름이 'vmimport'인 VM Import 서비스 역할이 필요합니다. 사용자 지정 역할을 사용하려면 `-RoleName` 파라미터를 사용하여 역할 이름을 지정합니다.**  

```
$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Disk Image Import"
    "DiskContainer_Description" = "Data disk"
    "DiskContainer_Format" = "VMDK"
    "DiskContainer_S3Bucket" = "amzn-s3-demo-bucket"
    "DiskContainer_S3Key" = "datadiskimage.vmdk"
}

Import-EC2Snapshot @parms
```
**출력:**  

```
Description            ImportTaskId               SnapshotTaskDetail                                                          
-----------------      --------------------       ------------------                                                          
Disk Image Import      import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ImportSnapshot](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 'VMDK' 형식의 VM 디스크 이미지를 Amazon EBS 스냅샷으로 가져옵니다. 이 예제에서는 http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/VMImportPrerequisites.html 페이지의 `VM Import Prequisites` 주제에 설명된 대로 지정된 버킷에 대한 Amazon EC2 액세스를 허용하는 정책과 함께 기본 이름이 'vmimport'인 VM Import 서비스 역할이 필요합니다. 사용자 지정 역할을 사용하려면 `-RoleName` 파라미터를 사용하여 역할 이름을 지정합니다.**  

```
$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Disk Image Import"
    "DiskContainer_Description" = "Data disk"
    "DiskContainer_Format" = "VMDK"
    "DiskContainer_S3Bucket" = "amzn-s3-demo-bucket"
    "DiskContainer_S3Key" = "datadiskimage.vmdk"
}

Import-EC2Snapshot @parms
```
**출력:**  

```
Description            ImportTaskId               SnapshotTaskDetail                                                          
-----------------      --------------------       ------------------                                                          
Disk Image Import      import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ImportSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyCapacityReservation` 사용
<a name="example_ec2_ModifyCapacityReservation_section"></a>

다음 코드 예시는 `ModifyCapacityReservation`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 기존 용량 예약에서 예약한 인스턴스 수 변경**  
다음 `modify-capacity-reservation` 예시에서는 용량 예약이 용량을 예약하는 인스턴스 수를 변경합니다.  

```
aws ec2 modify-capacity-reservation \
    --capacity-reservation-id cr-1234abcd56EXAMPLE \
    --instance-count 5
```
출력:  

```
{
    "Return": true
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [용량 예약 수정](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-modify.html)을 참조하세요.  
**예시 2: 기존 용량 예약의 종료 날짜 및 시간 변경**  
다음 `modify-capacity-reservation` 예시에서는 지정된 날짜 및 시간에 종료되도록 기존 용량 예약을 수정합니다.  

```
aws ec2 modify-capacity-reservation \
    --capacity-reservation-id cr-1234abcd56EXAMPLE \
    --end-date-type limited \
    --end-date 2019-08-31T23:59:59Z
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [용량 예약 수정](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-modify.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyCapacityReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-capacity-reservation.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스 수를 1로 변경하여 CapacityReservationId cr-0c1f2345db6f7cdba를 수정합니다.**  

```
Edit-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba -InstanceCount 1
```
**출력:**  

```
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyCapacityReservation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스 수를 1로 변경하여 CapacityReservationId cr-0c1f2345db6f7cdba를 수정합니다.**  

```
Edit-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba -InstanceCount 1
```
**출력:**  

```
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyHosts` 사용
<a name="example_ec2_ModifyHosts_section"></a>

다음 코드 예시는 `ModifyHosts`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 전용 호스트에 대한 자동 배치 활성화**  
다음 `modify-hosts` 예시에서는 전용 호스트에 대한 자동 배치를 활성화하여 인스턴스 유형 구성과 일치하는 모든 타겟팅되지 않은 인스턴스 시작을 허용합니다.  

```
aws ec2 modify-hosts \
    --host-id h-06c2f189b4EXAMPLE \
    --auto-placement on
```
출력:  

```
{
    "Successful": [
        "h-06c2f189b4EXAMPLE"
    ],
    "Unsuccessful": []
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [전용 호스트의 자동 배치 설정 수정](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/modify-host-auto-placement.html)을 참조하세요.  
**예시 2: 전용 호스트에 대한 호스트 복구 활성화**  
다음 `modify-hosts` 예시에서는 지정된 전용 호스트에 대한 호스트 복구를 활성화합니다.  

```
aws ec2 modify-hosts \
    --host-id h-06c2f189b4EXAMPLE \
    --host-recovery on
```
출력:  

```
{
    "Successful": [
        "h-06c2f189b4EXAMPLE"
    ],
    "Unsuccessful": []
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [전용 호스트의 자동 배치 설정 수정](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/modify-host-auto-placement.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyHosts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-hosts.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 전용 호스트 h-01e23f4cd567890f3에 대한 AutoPlacement 설정을 off로 수정합니다.**  

```
Edit-EC2Host -HostId h-03e09f8cd681609f3 -AutoPlacement off
```
**출력:**  

```
Successful            Unsuccessful
----------            ------------
{h-01e23f4cd567890f3} {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyHosts](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 전용 호스트 h-01e23f4cd567890f3에 대한 AutoPlacement 설정을 off로 수정합니다.**  

```
Edit-EC2Host -HostId h-03e09f8cd681609f3 -AutoPlacement off
```
**출력:**  

```
Successful            Unsuccessful
----------            ------------
{h-01e23f4cd567890f3} {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyHosts](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyIdFormat` 사용
<a name="example_ec2_ModifyIdFormat_section"></a>

다음 코드 예시는 `ModifyIdFormat`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**리소스에 더 긴 ID 형식 활성화**  
다음 `modify-id-format` 예시에서는 `instance` 리소스 유형에 대해 더 긴 ID 형식을 활성화합니다.  

```
aws ec2 modify-id-format \
    --resource instance \
    --use-long-ids
```
**리소스의 더 긴 ID 형식 비활성화**  
다음 `modify-id-format` 예시에서는 `instance` 리소스 유형에 대해 더 긴 ID 형식을 비활성화합니다.  

```
aws ec2 modify-id-format \
    --resource instance \
    --no-use-long-ids
```
다음 `modify-id-format` 예시에서는 옵트인 기간 내에 있는 지원되는 모든 리소스 유형에 대해 더 긴 ID 형식을 사용하도록 설정합니다.  

```
aws ec2 modify-id-format \
    --resource all-current \
    --use-long-ids
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyIdFormat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-id-format.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 리소스 유형에 대해 더 긴 ID 형식을 활성화합니다.**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $true
```
**예제 2: 이 예제에서는 지정된 리소스 유형에 대해 더 긴 ID 형식을 비활성화합니다.**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyIdFormat](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 리소스 유형에 대해 더 긴 ID 형식을 활성화합니다.**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $true
```
**예제 2: 이 예제에서는 지정된 리소스 유형에 대해 더 긴 ID 형식을 비활성화합니다.**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyImageAttribute` 사용
<a name="example_ec2_ModifyImageAttribute_section"></a>

다음 코드 예시는 `ModifyImageAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 퍼블릭 AMI로 설정**  
다음 `modify-instance-attribute` 예시에서는 지정된 AMI를 퍼블릭으로 설정합니다.  

```
aws ec2 modify-image-attribute \
    --image-id ami-5731123e \
    --launch-permission "Add=[{Group=all}]"
```
이 명령은 출력을 생성하지 않습니다.  
**예시 2: 프라이빗 AMI로 설정**  
다음 `modify-instance-attribute` 예시에서는 지정된 AMI를 프라이빗으로 설정합니다.  

```
aws ec2 modify-image-attribute \
    --image-id ami-5731123e \
    --launch-permission "Remove=[{Group=all}]"
```
이 명령은 출력을 생성하지 않습니다.  
**예제 3: AWS 계정에 시작 권한 부여**  
다음 `modify-instance-attribute` 예시에서는 지정된 AWS 계정에 시작 권한을 부여합니다.  

```
aws ec2 modify-image-attribute \
    --image-id ami-5731123e \
    --launch-permission "Add=[{UserId=123456789012}]"
```
이 명령은 출력을 생성하지 않습니다.  
**예제 4: AWS 계정에서 시작 권한 제거**  
다음 `modify-instance-attribute` 예시에서는 지정된 AWS 계정에서 시작 권한을 제거합니다.  

```
aws ec2 modify-image-attribute \
    --image-id ami-5731123e \
    --launch-permission "Remove=[{UserId=123456789012}]"
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyImageAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-image-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 AMI에 대한 설명을 업데이트합니다.**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Description "New description"
```
**예제 2:이 예제에서는 AMI를 퍼블릭으로 설정합니다(예: 누구나 사용할 AWS 계정 수 있도록).**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserGroup all
```
**예제 3: 이 예제에서는 AMI를 프라이빗으로 설정합니다(예를 들어, 소유자만 사용할 수 있도록).**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserGroup all
```
**예제 4:이 예제에서는 지정된에 시작 권한을 부여합니다 AWS 계정.**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserId 111122223333
```
**예제 5:이 예제는 지정된에서 시작 권한을 제거합니다 AWS 계정.**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserId 111122223333
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyImageAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 AMI에 대한 설명을 업데이트합니다.**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Description "New description"
```
**예제 2:이 예제에서는 AMI를 퍼블릭으로 설정합니다(예: 누구나 사용할 AWS 계정 수 있도록).**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserGroup all
```
**예제 3: 이 예제에서는 AMI를 프라이빗으로 설정합니다(예를 들어, 소유자만 사용할 수 있도록).**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserGroup all
```
**예제 4:이 예제에서는 지정된에 시작 권한을 부여합니다 AWS 계정.**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserId 111122223333
```
**예제 5:이 예제는 지정된에서 시작 권한을 제거합니다 AWS 계정.**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserId 111122223333
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyInstanceAttribute` 사용
<a name="example_ec2_ModifyInstanceAttribute_section"></a>

다음 코드 예시는 `ModifyInstanceAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 인스턴스 유형 수정**  
다음 `modify-instance-attribute` 예시에서는 지정된 인스턴스의 인스턴스 유형을 수정합니다. 인스턴스는 `stopped` 상태여야 합니다.  

```
aws ec2 modify-instance-attribute \
    --instance-id i-1234567890abcdef0 \
    --instance-type "{\"Value\": \"m1.small\"}"
```
이 명령은 출력을 생성하지 않습니다.  
**예시 2: 인스턴스에서 향상된 네트워킹 활성화**  
다음 `modify-instance-attribute` 예시에서는 지정된 인스턴스에 대해 향상된 네트워킹을 활성화합니다. 인스턴스는 `stopped` 상태여야 합니다.  

```
aws ec2 modify-instance-attribute \
    --instance-id i-1234567890abcdef0 \
    --sriov-net-support simple
```
이 명령은 출력을 생성하지 않습니다.  
**예시 3: sourceDestCheck 속성 수정**  
다음 `modify-instance-attribute` 예시에서는 지정된 인스턴스의 `sourceDestCheck` 속성을 `true`로 설정합니다. 인스턴스가 VPC에 있어야 합니다.  

```
aws ec2 modify-instance-attribute --instance-id i-1234567890abcdef0 --source-dest-check "{\"Value\": true}"
```
이 명령은 출력을 생성하지 않습니다.  
**예시 4: 루트 볼륨의 deleteOnTermination 속성 수정법**  
다음 `modify-instance-attribute` 예시에서는 지정된 Amazon EBS 지원 인스턴스의 루트 볼륨에 대한 `deleteOnTermination` 속성을 `false`로 설정합니다. 기본적으로 이 속성은 루트 볼륨의 경우 `true`입니다.  
명령:  

```
aws ec2 modify-instance-attribute \
  --instance-id i-1234567890abcdef0 \
  --block-device-mappings "[{\"DeviceName\": \"/dev/sda1\",\"Ebs\":{\"DeleteOnTermination\":false}}]"
```
이 명령은 출력을 생성하지 않습니다.  
**예시 5: 인스턴스에 연결된 사용자 데이터 수정**  
다음 `modify-instance-attribute` 예시에서는 `UserData.txt` 파일의 콘텐츠를 지정된 인스턴스에 대한 UserData로 추가합니다.  
원본 파일 `UserData.txt`의 콘텐츠:  

```
#!/bin/bash
yum update -y
service httpd start
chkconfig httpd on
```
파일의 콘텐츠는 base64로 인코딩되어야 합니다. 첫 번째 명령은 텍스트 파일을 base64로 변환하여 새 파일로 저장합니다.  
명령의 Linux/macOS 버전:  

```
base64 UserData.txt > UserData.base64.txt
```
이 명령은 출력을 생성하지 않습니다.  
명령의 Windows 버전:  

```
certutil -encode UserData.txt tmp.b64 && findstr /v /c:- tmp.b64 > UserData.base64.txt
```
출력:  

```
Input Length = 67
Output Length = 152
CertUtil: -encode command completed successfully.
```
이제 다음 CLI 명령에서 해당 파일을 참조할 수 있습니다.  

```
aws ec2 modify-instance-attribute \
    --instance-id=i-09b5a14dbca622e76 \
    --attribute userData --value file://UserData.base64.txt
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *EC2 사용 설명서*[의 사용자 데이터 및 AWS CLI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html#user-data-api-cli)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyInstanceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스의 인스턴스 유형을 수정합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceType m3.medium
```
**예제 2: 이 예제에서는 'simple'을 단일 루트 I/O 가상화(SR-IOV) 네트워크 지원 파라미터인 -SriovNetSupport 값으로 지정하여 지정된 인스턴스에 대해 향상된 네트워킹을 활성화합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SriovNetSupport "simple"
```
**예제 3: 이 예제에서는 지정된 인스턴스의 보안 그룹을 수정합니다. 인스턴스가 VPC에 있어야 합니다. 이름이 아닌 각 보안 그룹의 ID를 지정해야 합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -Group @( "sg-12345678", "sg-45678901" )
```
**예제 4: 이 예제에서는 지정된 인스턴스에 대해 EBS I/O 최적화를 활성화합니다. 이 기능은 일부 인스턴스 유형에서는 사용할 수 없습니다. EBS 최적화 인스턴스를 사용할 때 추가 사용 요금이 적용됩니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -EbsOptimized $true
```
**예제 5: 이 예제에서는 지정된 인스턴스에 대한 소스/대상 확인을 활성화합니다. NAT를 수행하는 NAT 인스턴스의 경우 값이 'false'여야 합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SourceDestCheck $true
```
**예제 6: 이 예제에서는 지정된 인스턴스에 대한 종료를 비활성화합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -DisableApiTermination $true
```
**예제 7: 이 예제에서는 인스턴스 내부에서 종료가 시작될 때 인스턴스 자체를 종료하도록 지정된 인스턴스를 변경합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceInitiatedShutdownBehavior terminate
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyInstanceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스의 인스턴스 유형을 수정합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceType m3.medium
```
**예제 2: 이 예제에서는 'simple'을 단일 루트 I/O 가상화(SR-IOV) 네트워크 지원 파라미터인 -SriovNetSupport 값으로 지정하여 지정된 인스턴스에 대해 향상된 네트워킹을 활성화합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SriovNetSupport "simple"
```
**예제 3: 이 예제에서는 지정된 인스턴스의 보안 그룹을 수정합니다. 인스턴스가 VPC에 있어야 합니다. 이름이 아닌 각 보안 그룹의 ID를 지정해야 합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -Group @( "sg-12345678", "sg-45678901" )
```
**예제 4: 이 예제에서는 지정된 인스턴스에 대해 EBS I/O 최적화를 활성화합니다. 이 기능은 일부 인스턴스 유형에서는 사용할 수 없습니다. EBS 최적화 인스턴스를 사용할 때 추가 사용 요금이 적용됩니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -EbsOptimized $true
```
**예제 5: 이 예제에서는 지정된 인스턴스에 대한 소스/대상 확인을 활성화합니다. NAT를 수행하는 NAT 인스턴스의 경우 값이 'false'여야 합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SourceDestCheck $true
```
**예제 6: 이 예제에서는 지정된 인스턴스에 대한 종료를 비활성화합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -DisableApiTermination $true
```
**예제 7: 이 예제에서는 인스턴스 내부에서 종료가 시작될 때 인스턴스 자체를 종료하도록 지정된 인스턴스를 변경합니다.**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceInitiatedShutdownBehavior terminate
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyInstanceCreditSpecification` 사용
<a name="example_ec2_ModifyInstanceCreditSpecification_section"></a>

다음 코드 예시는 `ModifyInstanceCreditSpecification`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스의 CPU 사용량에 대한 크레딧 옵션 수정**  
이 예시에서는 지정된 리전에서 지정된 인스턴스의 CPU 사용량에 대한 크레딧 옵션을 '무제한'으로 수정합니다. 유효한 크레딧 옵션은 '표준' 및 '무제한'입니다.  
명령:  

```
aws ec2 modify-instance-credit-specification --instance-credit-specification "InstanceId=i-1234567890abcdef0,CpuCredits=unlimited"
```
출력:  

```
{
  "SuccessfulInstanceCreditSpecifications": [
    {
      "InstanceId": "i-1234567890abcdef0"
    }
  ],
  "UnsuccessfulInstanceCreditSpecifications": []
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyInstanceCreditSpecification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-credit-specification.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스 i-01234567890abcdef에 대한 T2 무제한 크레딧을 활성화합니다.**  

```
$Credit = New-Object -TypeName Amazon.EC2.Model.InstanceCreditSpecificationRequest
$Credit.InstanceId = "i-01234567890abcdef"
$Credit.CpuCredits = "unlimited"
Edit-EC2InstanceCreditSpecification -InstanceCreditSpecification $Credit
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스 i-01234567890abcdef에 대한 T2 무제한 크레딧을 활성화합니다.**  

```
$Credit = New-Object -TypeName Amazon.EC2.Model.InstanceCreditSpecificationRequest
$Credit.InstanceId = "i-01234567890abcdef"
$Credit.CpuCredits = "unlimited"
Edit-EC2InstanceCreditSpecification -InstanceCreditSpecification $Credit
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyNetworkInterfaceAttribute` 사용
<a name="example_ec2_ModifyNetworkInterfaceAttribute_section"></a>

다음 코드 예시는 `ModifyNetworkInterfaceAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 인터페이스의 연결 속성 수정**  
이 예시 명령은 지정된 네트워크 인터페이스의 `attachment` 속성을 수정합니다.  
명령:  

```
aws ec2 modify-network-interface-attribute --network-interface-id eni-686ea200 --attachment AttachmentId=eni-attach-43348162,DeleteOnTermination=false
```
**네트워크 인터페이스의 설명 속성 수정**  
이 예시 명령은 지정된 네트워크 인터페이스의 `description` 속성을 수정합니다.  
명령:  

```
aws ec2 modify-network-interface-attribute --network-interface-id eni-686ea200 --description "My description"
```
**네트워크 인터페이스의 groupSet 속성 수정**  
이 예시 명령은 지정된 네트워크 인터페이스의 `groupSet` 속성을 수정합니다.  
명령:  

```
aws ec2 modify-network-interface-attribute --network-interface-id eni-686ea200 --groups sg-903004f8 sg-1a2b3c4d
```
**네트워크 인터페이스의 sourceDestCheck 속성 수정**  
이 예시 명령은 지정된 네트워크 인터페이스의 `sourceDestCheck` 속성을 수정합니다.  
명령:  

```
aws ec2 modify-network-interface-attribute --network-interface-id eni-686ea200 --no-source-dest-check
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyNetworkInterfaceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-network-interface-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 종료 시 지정된 연결이 삭제되도록 지정된 네트워크 인터페이스를 수정합니다.**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Attachment_AttachmentId eni-attach-1a2b3c4d -Attachment_DeleteOnTermination $true
```
**예제 2: 이 예제에서는 지정된 네트워크 인터페이스의 설명을 수정합니다.**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Description "my description"
```
**예제 3: 이 예제에서는 지정된 네트워크 인터페이스의 보안 그룹을 수정합니다.**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Groups sg-1a2b3c4d
```
**예제 4: 이 예제에서는 지정된 네트워크 인터페이스에 대한 소스/대상 확인을 비활성화합니다.**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 종료 시 지정된 연결이 삭제되도록 지정된 네트워크 인터페이스를 수정합니다.**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Attachment_AttachmentId eni-attach-1a2b3c4d -Attachment_DeleteOnTermination $true
```
**예제 2: 이 예제에서는 지정된 네트워크 인터페이스의 설명을 수정합니다.**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Description "my description"
```
**예제 3: 이 예제에서는 지정된 네트워크 인터페이스의 보안 그룹을 수정합니다.**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Groups sg-1a2b3c4d
```
**예제 4: 이 예제에서는 지정된 네트워크 인터페이스에 대한 소스/대상 확인을 비활성화합니다.**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyReservedInstances` 사용
<a name="example_ec2_ModifyReservedInstances_section"></a>

다음 코드 예시는 `ModifyReservedInstances`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예약 인스턴스 수정**  
이 예시 명령은 예약 인스턴스를 같은 리전 내의 다른 가용 영역으로 이동합니다.  
명령:  

```
aws ec2 modify-reserved-instances --reserved-instances-ids b847fa93-e282-4f55-b59a-1342f5bd7c02 --target-configurations AvailabilityZone=us-west-1c,Platform=EC2-Classic,InstanceCount=10
```
출력:  

```
{
  "ReservedInstancesModificationId": "rimod-d3ed4335-b1d3-4de6-ab31-0f13aaf46687"
}
```
**예약 인스턴스의 네트워크 플랫폼 수정**  
이 예시 명령은 EC2-Classic 예약 인스턴스를 EC2-VPC로 변환합니다.  
명령:  

```
aws ec2 modify-reserved-instances --reserved-instances-ids f127bd27-edb7-44c9-a0eb-0d7e09259af0 --target-configurations AvailabilityZone=us-west-1c,Platform=EC2-VPC,InstanceCount=5
```
출력:  

```
{
  "ReservedInstancesModificationId": "rimod-82fa9020-668f-4fb6-945d-61537009d291"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 예약 인스턴스 수정을 참조하세요.  
**예약 인스턴스의 인스턴스 크기 수정**  
이 예시 명령은 us-west-1c에 10개의 m1.small Linux/UNIX 인스턴스가 있는 예약 인스턴스를 수정하여 8개의 m1.small 인스턴스는 2개의 m1.large 인스턴스가 되고 나머지 2개의 m1.small 인스턴스는 동일한 가용 영역에서 1개의 m1.medium 인스턴스가 되도록 합니다. 명령:  

```
aws ec2 modify-reserved-instances --reserved-instances-ids 1ba8e2e3-3556-4264-949e-63ee671405a9 --target-configurations AvailabilityZone=us-west-1c,Platform=EC2-Classic,InstanceCount=2,InstanceType=m1.large AvailabilityZone=us-west-1c,Platform=EC2-Classic,InstanceCount=1,InstanceType=m1.medium
```
출력:  

```
{
    "ReservedInstancesModificationId": "rimod-acc5f240-080d-4717-b3e3-1c6b11fa00b6"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 예약 인스턴스 크기 수정을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyReservedInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-reserved-instances.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 예약 인스턴스의 가용 영역, 인스턴스 수, 플랫폼을 수정합니다.**  

```
$config = New-Object Amazon.EC2.Model.ReservedInstancesConfiguration
$config.AvailabilityZone = "us-west-2a"
$config.InstanceCount = 1
$config.Platform = "EC2-VPC"

Edit-EC2ReservedInstance `
-ReservedInstancesId @("FE32132D-70D5-4795-B400-AE435EXAMPLE", "0CC556F3-7AB8-4C00-B0E5-98666EXAMPLE") `
-TargetConfiguration $config
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyReservedInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 예약 인스턴스의 가용 영역, 인스턴스 수, 플랫폼을 수정합니다.**  

```
$config = New-Object Amazon.EC2.Model.ReservedInstancesConfiguration
$config.AvailabilityZone = "us-west-2a"
$config.InstanceCount = 1
$config.Platform = "EC2-VPC"

Edit-EC2ReservedInstance `
-ReservedInstancesId @("FE32132D-70D5-4795-B400-AE435EXAMPLE", "0CC556F3-7AB8-4C00-B0E5-98666EXAMPLE") `
-TargetConfiguration $config
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyReservedInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifySnapshotAttribute` 사용
<a name="example_ec2_ModifySnapshotAttribute_section"></a>

다음 코드 예시는 `ModifySnapshotAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 스냅샷 속성 수정**  
다음 `modify-snapshot-attribute` 예시에서는 지정된 스냅샷의 `createVolumePermission` 속성을 업데이트하여 지정된 사용자의 볼륨 권한을 제거합니다.  

```
aws ec2 modify-snapshot-attribute \
    --snapshot-id snap-1234567890abcdef0 \
    --attribute createVolumePermission \
    --operation-type remove \
    --user-ids 123456789012
```
**예시 2: 스냅샷을 퍼블릭으로 설정**  
다음 `modify-snapshot-attribute` 예시에서는 지정된 스냅샷을 퍼블릭으로 설정합니다.  

```
aws ec2 modify-snapshot-attribute \
    --snapshot-id snap-1234567890abcdef0 \
    --attribute createVolumePermission \
    --operation-type add \
    --group-names all
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifySnapshotAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-snapshot-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 CreateVolumePermission 속성을 설정하여 지정된 스냅샷을 퍼블릭으로 만듭니다.**  

```
Edit-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission -OperationType Add -GroupName all
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifySnapshotAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 CreateVolumePermission 속성을 설정하여 지정된 스냅샷을 퍼블릭으로 만듭니다.**  

```
Edit-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission -OperationType Add -GroupName all
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifySnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifySpotFleetRequest` 사용
<a name="example_ec2_ModifySpotFleetRequest_section"></a>

다음 코드 예시는 `ModifySpotFleetRequest`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스팟 플릿 요청 수정**  
이 예시 명령은 지정된 스팟 플릿 요청의 목표 용량을 업데이트합니다.  
명령:  

```
aws ec2 modify-spot-fleet-request --target-capacity 20 --spot-fleet-request-id sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
출력:  

```
{
    "Return": true
}
```
이 예시 명령은 결과적으로 스팟 인스턴스를 종료하지 않고 지정된 스팟 플릿 요청의 목표 용량을 줄입니다.  
명령:  

```
aws ec2 modify-spot-fleet-request --target-capacity 10 --excess-capacity-termination-policy NoTermination --spot-fleet-request-ids sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
출력:  

```
{
    "Return": true
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifySpotFleetRequest](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-spot-fleet-request.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스팟 플릿 요청의 목표 용량을 업데이트합니다.**  

```
Edit-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TargetCapacity 10
```
**출력:**  

```
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifySpotFleetRequest](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스팟 플릿 요청의 목표 용량을 업데이트합니다.**  

```
Edit-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TargetCapacity 10
```
**출력:**  

```
True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifySpotFleetRequest](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifySubnetAttribute` 사용
<a name="example_ec2_ModifySubnetAttribute_section"></a>

다음 코드 예시는 `ModifySubnetAttribute`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**서브넷의 퍼블릭 IPv4 주소 지정 동작 변경**  
이 예시에서는 서브넷-1a2b3c4d를 수정하여 이 서브넷으로 시작된 모든 인스턴스에 공용 IPv4 주소가 할당되도록 지정합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 modify-subnet-attribute --subnet-id subnet-1a2b3c4d --map-public-ip-on-launch
```
**서브넷의 IPv6 주소 지정 동작 변경**  
이 예시에서는 이 서브넷으로 시작된 모든 인스턴스에 해당 서브넷 범위의 IPv6 주소가 할당되도록 subnet-1a2b3c4d를 수정합니다.  
명령:  

```
aws ec2 modify-subnet-attribute --subnet-id subnet-1a2b3c4d --assign-ipv6-address-on-creation
```
자세한 내용은 *AWS Virtual Private Cloud 사용 설명서*에서 VPC의 IP 주소 지정을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifySubnetAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-subnet-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 서브넷에 대한 퍼블릭 IP 주소 지정을 활성화합니다.**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $true
```
**예제 2: 이 예제에서는 지정된 서브넷에 대한 퍼블릭 IP 주소 지정을 비활성화합니다.**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifySubnetAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 서브넷에 대한 퍼블릭 IP 주소 지정을 활성화합니다.**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $true
```
**예제 2: 이 예제에서는 지정된 서브넷에 대한 퍼블릭 IP 주소 지정을 비활성화합니다.**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifySubnetAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyVolumeAttribute` 사용
<a name="example_ec2_ModifyVolumeAttribute_section"></a>

다음 코드 예시는 `ModifyVolumeAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**볼륨 속성 수정**  
이 예시에서는 ID가 `vol-1234567890abcdef0`인 볼륨의 `autoEnableIo` 속성을 `true`로 설정합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 modify-volume-attribute --volume-id vol-1234567890abcdef0 --auto-enable-io
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyVolumeAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-volume-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 볼륨의 지정된 속성을 수정합니다. 일관성이 떨어질 수 있는 데이터로 인해 일시 중지된 후 볼륨에 대한 I/O 작업이 자동으로 재개됩니다.**  

```
Edit-EC2VolumeAttribute -VolumeId vol-12345678 -AutoEnableIO $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyVolumeAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 볼륨의 지정된 속성을 수정합니다. 일관성이 떨어질 수 있는 데이터로 인해 일시 중지된 후 볼륨에 대한 I/O 작업이 자동으로 재개됩니다.**  

```
Edit-EC2VolumeAttribute -VolumeId vol-12345678 -AutoEnableIO $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyVolumeAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ModifyVpcAttribute` 사용
<a name="example_ec2_ModifyVpcAttribute_section"></a>

다음 코드 예시는 `ModifyVpcAttribute`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**enableDnsSupport 속성 수정**  
다음 예시에서는 `enableDnsSupport` 속성을 수정합니다. 이 속성은 VPC에 DNS 확인이 활성화되어 있는지 여부를 나타냅니다. 이 속성이 `true`인 경우 Amazon DNS 서버는 인스턴스의 DNS 호스트 이름을 해당 IP 주소로 확인하지만, 그렇지 않으면 확인하지 않습니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 modify-vpc-attribute --vpc-id vpc-a01106c2 --enable-dns-support "{\"Value\":false}"
```
**enableDnsHostnames 속성 수정**  
다음 예시에서는 `enableDnsHostnames` 속성을 수정합니다. 이 속성은 VPC에서 시작된 인스턴스가 DNS 호스트 이름을 가져오는지 나타냅니다. 이 속성이 `true`인 경우 VPC의 인스턴스가 DNS 호스트 이름을 가져오고, 그렇지 않으면 가져오지 않습니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 modify-vpc-attribute --vpc-id vpc-a01106c2 --enable-dns-hostnames "{\"Value\":false}"
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ModifyVpcAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpc-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 VPC에 대해 DNS 호스트 이름 지원을 활성화합니다.**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $true
```
**예제 2: 이 예제에서는 지정된 VPC에 대해 DNS 호스트 이름 지원을 비활성화합니다.**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $false
```
**예제 3: 이 예제에서는 지정된 VPC에 대해 DNS 해석 지원을 활성화합니다.**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $true
```
**예제 4: 이 예제에서는 지정된 VPC에 대해 DNS 해석 지원을 비활성화합니다.**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyVpcAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 VPC에 대해 DNS 호스트 이름 지원을 활성화합니다.**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $true
```
**예제 2: 이 예제에서는 지정된 VPC에 대해 DNS 호스트 이름 지원을 비활성화합니다.**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $false
```
**예제 3: 이 예제에서는 지정된 VPC에 대해 DNS 해석 지원을 활성화합니다.**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $true
```
**예제 4: 이 예제에서는 지정된 VPC에 대해 DNS 해석 지원을 비활성화합니다.**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $false
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyVpcAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `MonitorInstances` 함께 사용
<a name="example_ec2_MonitorInstances_section"></a>

다음 코드 예시는 `MonitorInstances`의 사용 방법을 보여 줍니다.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Enable detailed monitoring for an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceId: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::enableMonitoring(const Aws::String &instanceId,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return monitorInstancesOutcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1  API 참조*의 [MonitorInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/MonitorInstances)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스에 대한 세부 모니터링을 활성화하는 방법**  
이 예제 명령은 지정된 인스턴스에 대한 세부 모니터링을 활성화합니다.  
명령:  

```
aws ec2 monitor-instances --instance-ids i-1234567890abcdef0
```
출력:  

```
{
  "InstanceMonitorings": [
      {
          "InstanceId": "i-1234567890abcdef0",
          "Monitoring": {
              "State": "pending"
          }
      }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [MonitorInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/monitor-instances.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, MonitorInstancesCommand } from "@aws-sdk/client-ec2";

/**
 * Turn on detailed monitoring for the selected instance.
 * By default, metrics are sent to Amazon CloudWatch every 5 minutes.
 * For a cost you can enable detailed monitoring which sends metrics every minute.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new MonitorInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { InstanceMonitorings } = await client.send(command);
    const instancesBeingMonitored = InstanceMonitorings.map(
      (im) =>
        ` • Detailed monitoring state for ${im.InstanceId} is ${im.Monitoring.State}.`,
    );
    console.log("Monitoring status:");
    console.log(instancesBeingMonitored.join("\n"));
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript  API 참조*의 [MonitorInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/MonitorInstancesCommand)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스에 대한 세부 모니터링을 활성화합니다.**  

```
Start-EC2InstanceMonitoring -InstanceId i-12345678
```
**출력:**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [MonitorInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스에 대한 세부 모니터링을 활성화합니다.**  

```
Start-EC2InstanceMonitoring -InstanceId i-12345678
```
**출력:**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [MonitorInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist.
    APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids.

    "Perform dry run"
    TRY.
        " DryRun is set to true. This checks for the required permissions to monitor the instance without actually making the request. "
        lo_ec2->monitorinstances(
          it_instanceids = lt_instance_ids
          iv_dryrun = abap_true ).
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        " If the error code returned is `DryRunOperation`, then you have the required permissions to monitor this instance. "
        IF lo_exception->av_err_code = 'DryRunOperation'.
          MESSAGE 'Dry run to enable detailed monitoring completed.' TYPE 'I'.
          " DryRun is set to false to enable detailed monitoring. "
          lo_ec2->monitorinstances(
            it_instanceids = lt_instance_ids
            iv_dryrun = abap_false ).
          MESSAGE 'Detailed monitoring enabled.' TYPE 'I'.
          " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to monitor this instance. "
        ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'.
          MESSAGE 'Dry run to enable detailed monitoring failed. User does not have the permissions to monitor the instance.' TYPE 'E'.
        ELSE.
          DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
          MESSAGE lv_error TYPE 'E'.
        ENDIF.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [MonitorInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `MoveAddressToVpc` 사용
<a name="example_ec2_MoveAddressToVpc_section"></a>

다음 코드 예시는 `MoveAddressToVpc`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**주소를 EC2-VPC로 이동**  
이 예시에서는 탄력적 IP 주소 54.123.4.56을 EC2-VPC 플랫폼으로 이동합니다.  
명령:  

```
aws ec2 move-address-to-vpc --public-ip 54.123.4.56
```
출력:  

```
{
  "Status": "MoveInProgress"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [MoveAddressToVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/move-address-to-vpc.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 퍼블릭 IP 주소가 12.345.67.89인 EC2 인스턴스를 미국 동부(버지니아 북부) 리전의 EC2-VPC 플랫폼으로 이동합니다.**  

```
Move-EC2AddressToVpc -PublicIp 12.345.67.89 -Region us-east-1
```
**예제 2: 이 예제에서는 Get-EC2Instance 명령의 결과를 Move-EC2AddressToVpc cmdlet으로 파이프합니다. Get-EC2Instance 명령은 인스턴스 ID로 지정된 인스턴스를 가져온 다음 인스턴스의 퍼블릭 IP 주소 속성을 반환합니다.**  

```
(Get-EC2Instance -Instance i-12345678).Instances.PublicIpAddress | Move-EC2AddressToVpc
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [MoveAddressToVpc](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 퍼블릭 IP 주소가 12.345.67.89인 EC2 인스턴스를 미국 동부(버지니아 북부) 리전의 EC2-VPC 플랫폼으로 이동합니다.**  

```
Move-EC2AddressToVpc -PublicIp 12.345.67.89 -Region us-east-1
```
**예제 2: 이 예제에서는 Get-EC2Instance 명령의 결과를 Move-EC2AddressToVpc cmdlet으로 파이프합니다. Get-EC2Instance 명령은 인스턴스 ID로 지정된 인스턴스를 가져온 다음 인스턴스의 퍼블릭 IP 주소 속성을 반환합니다.**  

```
(Get-EC2Instance -Instance i-12345678).Instances.PublicIpAddress | Move-EC2AddressToVpc
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [MoveAddressToVpc](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `PurchaseHostReservation` 사용
<a name="example_ec2_PurchaseHostReservation_section"></a>

다음 코드 예시는 `PurchaseHostReservation`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**전용 호스트 예약 구매**  
이 예시에서는 계정에서 지정한 전용 호스트에 대해 지정된 전용 호스트 예약 상품을 구매합니다.  
명령:  

```
aws ec2 purchase-host-reservation --offering-id hro-03f707bf363b6b324 --host-id-set h-013abcd2a00cbd123
```
출력:  

```
{
  "TotalHourlyPrice": "1.499",
  "Purchase": [
      {
          "HourlyPrice": "1.499",
          "InstanceFamily": "m4",
          "PaymentOption": "NoUpfront",
          "HostIdSet": [
              "h-013abcd2a00cbd123"
          ],
          "HostReservationId": "hr-0d418a3a4ffc669ae",
          "UpfrontPrice": "0.000",
          "Duration": 31536000
      }
  ],
  "TotalUpfrontPrice": "0.000"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [PurchaseHostReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/purchase-host-reservation.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 전용 호스트 h-01e23f4cd567890f1의 구성과 일치하는 구성으로 hro-0c1f23456789d0ab를 제공하는 예약을 구매합니다.**  

```
New-EC2HostReservation -OfferingId hro-0c1f23456789d0ab HostIdSet h-01e23f4cd567890f1
```
**출력:**  

```
ClientToken       :
CurrencyCode      :
Purchase          : {hr-0123f4b5d67bedc89}
TotalHourlyPrice  : 1.307
TotalUpfrontPrice : 0.000
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [PurchaseHostReservation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 전용 호스트 h-01e23f4cd567890f1의 구성과 일치하는 구성으로 hro-0c1f23456789d0ab를 제공하는 예약을 구매합니다.**  

```
New-EC2HostReservation -OfferingId hro-0c1f23456789d0ab HostIdSet h-01e23f4cd567890f1
```
**출력:**  

```
ClientToken       :
CurrencyCode      :
Purchase          : {hr-0123f4b5d67bedc89}
TotalHourlyPrice  : 1.307
TotalUpfrontPrice : 0.000
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PurchaseHostReservation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `PurchaseScheduledInstances` 사용
<a name="example_ec2_PurchaseScheduledInstances_section"></a>

다음 코드 예시는 `PurchaseScheduledInstances`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**정기 인스턴스 구매**  
이 예시에서는 정기 인스턴스를 구매합니다.  
명령:  

```
aws ec2 purchase-scheduled-instances --purchase-requests file://purchase-request.json
```
Purchase-request.json:  

```
[
    {
        "PurchaseToken": "eyJ2IjoiMSIsInMiOjEsImMiOi...",
        "InstanceCount": 1
    }
]
```
출력:  

```
{
  "ScheduledInstanceSet": [
      {
          "AvailabilityZone": "us-west-2b",
          "ScheduledInstanceId": "sci-1234-1234-1234-1234-123456789012",
          "HourlyPrice": "0.095",
          "CreateDate": "2016-01-25T21:43:38.612Z",
          "Recurrence": {
              "OccurrenceDaySet": [
                  1
              ],
              "Interval": 1,
              "Frequency": "Weekly",
              "OccurrenceRelativeToEnd": false,
              "OccurrenceUnit": ""
          },
          "Platform": "Linux/UNIX",
          "TermEndDate": "2017-01-31T09:00:00Z",
          "InstanceCount": 1,
          "SlotDurationInHours": 32,
          "TermStartDate": "2016-01-31T09:00:00Z",
          "NetworkPlatform": "EC2-VPC",
          "TotalScheduledInstanceHours": 1696,
          "NextSlotStartTime": "2016-01-31T09:00:00Z",
          "InstanceType": "c4.large"
      }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [PurchaseScheduledInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/purchase-scheduled-instances.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 일정이 예약된 인스턴스를 구매합니다.**  

```
$request = New-Object Amazon.EC2.Model.PurchaseRequest
$request.InstanceCount = 1
$request.PurchaseToken = "eyJ2IjoiMSIsInMiOjEsImMiOi..."
New-EC2ScheduledInstancePurchase -PurchaseRequest $request
```
**출력:**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [PurchaseScheduledInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 일정이 예약된 인스턴스를 구매합니다.**  

```
$request = New-Object Amazon.EC2.Model.PurchaseRequest
$request.InstanceCount = 1
$request.PurchaseToken = "eyJ2IjoiMSIsInMiOjEsImMiOi..."
New-EC2ScheduledInstancePurchase -PurchaseRequest $request
```
**출력:**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PurchaseScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `RebootInstances` 함께 사용
<a name="example_ec2_RebootInstances_section"></a>

다음 코드 예시는 `RebootInstances`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](example_cross_ResilientService_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
ID로 인스턴스를 재부팅합니다.  

```
    /// <summary>
    /// Reboot a specific EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the instance that will be rebooted.</param>
    /// <returns>Async Task.</returns>
    public async Task<bool> RebootInstances(string ec2InstanceId)
    {
        try
        {
            var request = new RebootInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId },
            };

            await _amazonEC2.RebootInstancesAsync(request);

            // Wait for the instance to be running.
            Console.Write("Waiting for the instance to start.");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Running);

            return true;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId {ec2InstanceId} is invalid, unable to reboot. {ec2Exception.Message}");
            }
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while rebooting the instance {ec2InstanceId}.: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEC2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
```
인스턴스의 프로파일을 바꾸고, 재부팅하며, 웹 서버를 다시 시작합니다.  

```
    /// <summary>
    /// Replace the profile associated with a running instance. After the profile is replaced, the instance
    /// is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is
    /// used to restart the Python web server.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to update.</param>
    /// <param name="credsProfileName">The name of the new profile to associate with the specified instance.</param>
    /// <param name="associationId">The Id of the existing profile association for the instance.</param>
    /// <returns>Async task.</returns>
    public async Task ReplaceInstanceProfile(string instanceId, string credsProfileName, string associationId)
    {
        try
        {
            await _amazonEc2.ReplaceIamInstanceProfileAssociationAsync(
                new ReplaceIamInstanceProfileAssociationRequest()
                {
                    AssociationId = associationId,
                    IamInstanceProfile = new IamInstanceProfileSpecification()
                    {
                        Name = credsProfileName
                    }
                });
            // Allow time before resetting.
            Thread.Sleep(25000);

            await _amazonEc2.RebootInstancesAsync(
                new RebootInstancesRequest(new List<string>() { instanceId }));
            Thread.Sleep(25000);
            var instanceReady = false;
            var retries = 5;
            while (retries-- > 0 && !instanceReady)
            {
                var instancesPaginator =
                    _amazonSsm.Paginators.DescribeInstanceInformation(
                        new DescribeInstanceInformationRequest());
                // Get the entire list using the paginator.
                await foreach (var instance in instancesPaginator.InstanceInformationList)
                {
                    instanceReady = instance.InstanceId == instanceId;
                    if (instanceReady)
                    {
                        break;
                    }
                }
            }
            Console.WriteLine("Waiting for instance to be running.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);
            Console.WriteLine("Instance ready.");
            Console.WriteLine($"Sending restart command to instance {instanceId}");
            await _amazonSsm.SendCommandAsync(
                new SendCommandRequest()
                {
                    InstanceIds = new List<string>() { instanceId },
                    DocumentName = "AWS-RunShellScript",
                    Parameters = new Dictionary<string, List<string>>()
                    {
                        {
                            "commands",
                            new List<string>() { "cd / && sudo python3 server.py 80" }
                        }
                    }
                });
            Console.WriteLine($"Restarted the web server on instance {instanceId}");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while replacing the template.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET  API 참조*의 [RebootInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/RebootInstances)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Reboot an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::rebootInstance(const Aws::String &instanceId,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1  API 참조*의 [RebootInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/RebootInstances)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**Amazon EC2 인스턴스를 재부팅하는 방법**  
이 예제에서는 지정된 인스턴스를 재부팅합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 reboot-instances --instance-ids i-1234567890abcdef5
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*에서 인스턴스 재부팅을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [RebootInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reboot-instances.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, RebootInstancesCommand } from "@aws-sdk/client-ec2";

/**
 * Requests a reboot of the specified instances. This operation is asynchronous;
 * it only queues a request to reboot the specified instances.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new RebootInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    await client.send(command);
    console.log("Instance rebooted successfully.");
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(
        `${caught.message}. Please provide the InstanceId of a valid instance to reboot.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript  API 참조*의 [RebootInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/RebootInstancesCommand)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스를 재부팅합니다.**  

```
Restart-EC2Instance -InstanceId i-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RebootInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스를 재부팅합니다.**  

```
Restart-EC2Instance -InstanceId i-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RebootInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def replace_instance_profile(
        self,
        instance_id: str,
        new_instance_profile_name: str,
        profile_association_id: str,
    ) -> None:
        """
        Replaces the profile associated with a running instance. After the profile is
        replaced, the instance is rebooted to ensure that it uses the new profile. When
        the instance is ready, Systems Manager is used to restart the Python web server.

        :param instance_id: The ID of the instance to restart.
        :param new_instance_profile_name: The name of the new profile to associate with
                                          the specified instance.
        :param profile_association_id: The ID of the existing profile association for the
                                       instance.
        """
        try:
            self.ec2_client.replace_iam_instance_profile_association(
                IamInstanceProfile={"Name": new_instance_profile_name},
                AssociationId=profile_association_id,
            )
            log.info(
                "Replaced instance profile for association %s with profile %s.",
                profile_association_id,
                new_instance_profile_name,
            )
            time.sleep(5)

            self.ec2_client.reboot_instances(InstanceIds=[instance_id])
            log.info("Rebooting instance %s.", instance_id)
            waiter = self.ec2_client.get_waiter("instance_running")
            log.info("Waiting for instance %s to be running.", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info("Instance %s is now running.", instance_id)

            self.ssm_client.send_command(
                InstanceIds=[instance_id],
                DocumentName="AWS-RunShellScript",
                Parameters={"commands": ["cd / && sudo python3 server.py 80"]},
            )
            log.info(f"Restarted the Python web server on instance '{instance_id}'.")
        except ClientError as err:
            log.error("Failed to replace instance profile.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAssociationID.NotFound":
                log.error(
                    f"Association ID '{profile_association_id}' does not exist."
                    "Please check the association ID and try again."
                )
            if error_code == "InvalidInstanceId":
                log.error(
                    f"The specified instance ID '{instance_id}' does not exist or is not available for SSM. "
                    f"Please verify the instance ID and try again."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [RebootInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/RebootInstances)를 참조하십시오.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn reboot(&self, ec2: &EC2) -> Result<(), EC2Error> {
        if self.instance.is_some() {
            ec2.reboot_instance(self.instance_id()).await?;
            ec2.wait_for_instance_stopped(self.instance_id(), None)
                .await?;
            ec2.wait_for_instance_ready(self.instance_id(), None)
                .await?;
        }
        Ok(())
    }
```

```
    pub async fn reboot_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Rebooting instance {instance_id}");

        self.client
            .reboot_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        Ok(())
    }
```
Waiters API를 사용하여 인스턴스가 중지 및 준비 상태가 될 때까지 기다립니다. Waiters API를 사용하려면 rust 파일에 'use aws\$1sdk\$1ec2::client::Waiters'가 필요합니다.  

```
    /// Wait for an instance to be ready and status ok (default wait 60 seconds)
    pub async fn wait_for_instance_ready(
        &self,
        instance_id: &str,
        duration: Option<Duration>,
    ) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_status_ok()
            .instance_ids(instance_id)
            .wait(duration.unwrap_or(Duration::from_secs(60)))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to start.",
                    exceeded.max_wait().as_secs()
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }

    pub async fn wait_for_instance_stopped(
        &self,
        instance_id: &str,
        duration: Option<Duration>,
    ) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_stopped()
            .instance_ids(instance_id)
            .wait(duration.unwrap_or(Duration::from_secs(60)))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to stop.",
                    exceeded.max_wait().as_secs(),
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [RebootInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.reboot_instances)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist.
    APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids.

    "Perform dry run"
    TRY.
        " DryRun is set to true. This checks for the required permissions to reboot the instance without actually making the request. "
        lo_ec2->rebootinstances(
          it_instanceids = lt_instance_ids
          iv_dryrun = abap_true ).
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        " If the error code returned is `DryRunOperation`, then you have the required permissions to reboot this instance. "
        IF lo_exception->av_err_code = 'DryRunOperation'.
          MESSAGE 'Dry run to reboot instance completed.' TYPE 'I'.
          " DryRun is set to false to make a reboot request. "
          lo_ec2->rebootinstances(
             it_instanceids = lt_instance_ids
             iv_dryrun = abap_false ).
          MESSAGE 'Instance rebooted.' TYPE 'I'.
          " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to reboot this instance. "
        ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'.
          MESSAGE 'Dry run to reboot instance failed. User does not have permissions to reboot the instance.' TYPE 'E'.
        ELSE.
          DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
          MESSAGE lv_error TYPE 'E'.
        ENDIF.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [RebootInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `RegisterImage` 사용
<a name="example_ec2_RegisterImage_section"></a>

다음 코드 예시는 `RegisterImage`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 매니페스트 파일을 사용하여 AMI 등록**  
다음 `register-image` 예시에서는 Amazon S3에서 지정된 매니페스트 파일을 사용하여 AMI를 등록합니다.  

```
aws ec2 register-image \
    --name my-image \
    --image-location amzn-s3-demo-bucket/myimage/image.manifest.xml
```
출력:  

```
{
    "ImageId": "ami-1234567890EXAMPLE"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [Amazon Machine Image(AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)를 참조하세요.  
**예시 2: 루트 디바이스의 스냅샷을 사용하여 AMI 등록**  
다음 `register-image` 예시에서는 EBS 루트 볼륨의 지정된 스냅샷을 디바이스 `/dev/xvda`로 사용하여 AMI를 등록합니다. 블록 디바이스 매핑에는 빈 100기가바이트 EBS 볼륨도 디바이스 `/dev/xvdf`로 포함됩니다.  

```
aws ec2 register-image \
    --name my-image \
    --root-device-name /dev/xvda \
    --block-device-mappings DeviceName=/dev/xvda,Ebs={SnapshotId=snap-0db2cf683925d191f} DeviceName=/dev/xvdf,Ebs={VolumeSize=100}
```
출력:  

```
{
    "ImageId": "ami-1a2b3c4d5eEXAMPLE"
}
```
자세한 내용은 *Amazon EC2 사용 설명서*에서 [Amazon Machine Image(AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [RegisterImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/register-image.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 Amazon S3에 있는 지정된 매니페스트 파일을 사용하여 AMI를 등록합니다.**  

```
Register-EC2Image -ImageLocation amzn-s3-demo-bucket/my-web-server-ami/image.manifest.xml -Name my-web-server-ami
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RegisterImage](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 Amazon S3에 있는 지정된 매니페스트 파일을 사용하여 AMI를 등록합니다.**  

```
Register-EC2Image -ImageLocation amzn-s3-demo-bucket/my-web-server-ami/image.manifest.xml -Name my-web-server-ami
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RegisterImage](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `RejectVpcPeeringConnection` 사용
<a name="example_ec2_RejectVpcPeeringConnection_section"></a>

다음 코드 예시는 `RejectVpcPeeringConnection`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**VPC 피어링 연결 거부**  
이 예시에서는 지정된 VPC 피어링 연결 요청을 거부합니다.  
명령:  

```
aws ec2 reject-vpc-peering-connection --vpc-peering-connection-id pcx-1a2b3c4d
```
출력:  

```
{
    "Return": true
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [RejectVpcPeeringConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reject-vpc-peering-connection.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 위 예제에서는 VpcPeering request id pcx-01a2b3ce45fe67eb8에 대한 요청을 거부합니다.**  

```
Deny-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-01a2b3ce45fe67eb8
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RejectVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 위 예제에서는 VpcPeering request id pcx-01a2b3ce45fe67eb8에 대한 요청을 거부합니다.**  

```
Deny-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-01a2b3ce45fe67eb8
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RejectVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `ReleaseAddress` 함께 사용
<a name="example_ec2_ReleaseAddress_section"></a>

다음 코드 예시는 `ReleaseAddress`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [프라이빗 서브넷과 NAT 게이트웨이가 포함된 VPC 생성](example_vpc_GettingStartedPrivate_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Release an Elastic IP address. After the Elastic IP address is released,
    /// it can no longer be used.
    /// </summary>
    /// <param name="allocationId">The allocation Id of the Elastic IP address.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ReleaseAddress(string allocationId)
    {
        try
        {
            var request = new ReleaseAddressRequest { AllocationId = allocationId };

            var response = await _amazonEC2.ReleaseAddressAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidAllocationID.NotFound")
            {
                _logger.LogError(
                    $"AllocationId {allocationId} was not found. {ec2Exception.Message}");
            }

            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while releasing the AllocationId {allocationId}.: {ex.Message}");
            return false;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [ReleaseAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/ReleaseAddress)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_release_address
#
# This function releases an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       -a allocation_id - The allocation ID of the Elastic IP address to release.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_release_address() {
  local allocation_id response

  # Function to display usage information
  function usage() {
    echo "function ec2_release_address"
    echo "Releases an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance."
    echo "  -a allocation_id - The allocation ID of the Elastic IP address to release."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "a:h" option; do
    case "${option}" in
      a) allocation_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$allocation_id" ]]; then
    errecho "ERROR: You must provide an allocation ID with the -a parameter."
    return 1
  fi

  response=$(aws ec2 release-address \
    --allocation-id "$allocation_id") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports release-address operation failed."
    errecho "$response"
    return 1
  }

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [ReleaseAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/ReleaseAddress)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Release an Elastic IP address.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::releaseAddress(const Aws::String &allocationID,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [ReleaseAddress](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/ReleaseAddress)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**EC2-Classic의 탄력적 IP 주소를 해제하는 방법**  
자세한 내용은 EC2-Classic의 인스턴스에서 사용할 탄력적 IP 주소를 해제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 release-address --public-ip 198.51.100.0
```
**EC2-VPC의 탄력적 IP 주소를 해제하는 방법**  
이 예제에서는 VPC의 인스턴스에서 사용하도록 탄력적 IP 주소를 해제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 release-address --allocation-id eipalloc-64d5890a
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [ReleaseAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/release-address.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Releases an Elastic IP address asynchronously.
     *
     * @param allocId the allocation ID of the Elastic IP address to be released
     * @return a {@link CompletableFuture} representing the asynchronous operation of releasing the Elastic IP address
     */
    public CompletableFuture<ReleaseAddressResponse> releaseEC2AddressAsync(String allocId) {
        ReleaseAddressRequest request = ReleaseAddressRequest.builder()
            .allocationId(allocId)
            .build();

        CompletableFuture<ReleaseAddressResponse> response = getAsyncClient().releaseAddress(request);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to release Elastic IP address", ex);
            }
        });

        return response;
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [ReleaseAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/ReleaseAddress)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { ReleaseAddressCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Release an Elastic IP address.
 * @param {{ allocationId: string }} options
 */
export const main = async ({ allocationId }) => {
  const client = new EC2Client({});
  const command = new ReleaseAddressCommand({
    // You can also use PublicIp, but that is for EC2 classic which is being retired.
    AllocationId: allocationId,
  });

  try {
    await client.send(command);
    console.log("Successfully released address.");
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidAllocationID.NotFound"
    ) {
      console.warn(`${caught.message}. Please provide a valid AllocationID.`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ReleaseAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/ReleaseAddressCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun releaseEC2AddressSc(allocId: String?) {
    val request =
        ReleaseAddressRequest {
            allocationId = allocId
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.releaseAddress(request)
        println("Successfully released Elastic IP address $allocId")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [ReleaseAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 VPC의 인스턴스에 대해 지정된 탄력적 IP 주소를 릴리스합니다.**  

```
Remove-EC2Address -AllocationId eipalloc-12345678 -Force
```
**예제 2: 이 예제에서는 EC2-Classic의 인스턴스에 대해 지정된 탄력적 IP 주소를 릴리스합니다.**  

```
Remove-EC2Address -PublicIp 198.51.100.2 -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ReleaseAddress](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 VPC의 인스턴스에 대해 지정된 탄력적 IP 주소를 릴리스합니다.**  

```
Remove-EC2Address -AllocationId eipalloc-12345678 -Force
```
**예제 2: 이 예제에서는 EC2-Classic의 인스턴스에 대해 지정된 탄력적 IP 주소를 릴리스합니다.**  

```
Remove-EC2Address -PublicIp 198.51.100.2 -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ReleaseAddress](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class ElasticIpWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface."""

    class ElasticIp:
        """Represents an Elastic IP and its associated instance."""

        def __init__(
            self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None
        ) -> None:
            """
            Initializes the ElasticIp object.

            :param allocation_id: The allocation ID of the Elastic IP.
            :param public_ip: The public IP address of the Elastic IP.
            :param instance_id: The ID of the associated EC2 instance, if any.
            """
            self.allocation_id = allocation_id
            self.public_ip = public_ip
            self.instance_id = instance_id

    def __init__(self, ec2_client: Any) -> None:
        """
        Initializes the ElasticIpWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client
        self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = []

    @classmethod
    def from_client(cls) -> "ElasticIpWrapper":
        """
        Creates an ElasticIpWrapper instance with a default EC2 client.

        :return: An instance of ElasticIpWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def release(self, allocation_id: str) -> None:
        """
        Releases an Elastic IP address. After the Elastic IP address is released,
        it can no longer be used.

        :param allocation_id: The allocation ID of the Elastic IP to release.
        :raises ClientError: If the release fails, such as when the Elastic IP address is not found.
        """
        elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id)
        if elastic_ip is None:
            logger.info(f"No Elastic IP found with allocation ID {allocation_id}.")
            return

        try:
            self.ec2_client.release_address(AllocationId=allocation_id)
            self.elastic_ips.remove(elastic_ip)  # Remove the Elastic IP from the list
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidAddress.NotFound":
                logger.error(
                    f"Failed to release Elastic IP address {allocation_id} "
                    "because it could not be found. Verify the Elastic IP address "
                    "and ensure it is allocated to your account in the correct region "
                    "before attempting to release it."
                )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ReleaseAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/ReleaseAddress)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
# Releases an Elastic IP address from an
# Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Prerequisites:
#
# - An Amazon EC2 instance with an associated Elastic IP address.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param allocation_id [String] The ID of the allocation corresponding to
#   the Elastic IP address.
# @return [Boolean] true if the Elastic IP address was released;
#   otherwise, false.
# @example
#   exit 1 unless elastic_ip_address_released?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'eipalloc-04452e528a66279EX'
#   )
def elastic_ip_address_released?(ec2_client, allocation_id)
  ec2_client.release_address(allocation_id: allocation_id)
  true
rescue StandardError => e
  puts("Error releasing Elastic IP address: #{e.message}")
  false
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ReleaseAddress](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/ReleaseAddress)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn deallocate_ip_address(&self, allocation_id: &str) -> Result<(), EC2Error> {
        self.client
            .release_address()
            .allocation_id(allocation_id)
            .send()
            .await?;
        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [ReleaseAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.release_address)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ec2->releaseaddress( iv_allocationid = iv_allocation_id ).
        MESSAGE 'Elastic IP address released.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [ReleaseAddress](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Release an allocated Elastic IP.
    /// 
    /// - Parameter allocationId: The allocation ID of the Elastic IP to
    ///   release.
    func releaseAddress(allocationId: String?) async {
        do {
            _ = try await ec2Client.releaseAddress(
                input: ReleaseAddressInput(
                    allocationId: allocationId
                )
            )
        } catch {
            print("*** Unable to release the IP address: \(error.localizedDescription)")
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [ReleaseAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/releaseaddress(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ReleaseHosts` 사용
<a name="example_ec2_ReleaseHosts_section"></a>

다음 코드 예시는 `ReleaseHosts`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**계정에서 전용 호스트 해제**  
계정에서 전용 호스트를 해제합니다. 호스트에 있는 인스턴스는 호스트를 해제하기 전에 중지하거나 종료해야 합니다.  
명령:  

```
aws ec2 release-hosts --host-id=h-0029d6e3cacf1b3da
```
출력:  

```
{
    "Successful":  [
        "h-0029d6e3cacf1b3da"
         ],
  "Unsuccessful": []

 }
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ReleaseHosts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/release-hosts.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 호스트 ID h-0badafd1dcb2f3456을 릴리스합니다.**  

```
Remove-EC2Host -HostId h-0badafd1dcb2f3456
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Host (ReleaseHosts)" on target "h-0badafd1dcb2f3456".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Successful            Unsuccessful
----------            ------------
{h-0badafd1dcb2f3456} {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ReleaseHosts](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 호스트 ID h-0badafd1dcb2f3456을 릴리스합니다.**  

```
Remove-EC2Host -HostId h-0badafd1dcb2f3456
```
**출력:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Host (ReleaseHosts)" on target "h-0badafd1dcb2f3456".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Successful            Unsuccessful
----------            ------------
{h-0badafd1dcb2f3456} {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ReleaseHosts](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `ReplaceIamInstanceProfileAssociation` 함께 사용
<a name="example_ec2_ReplaceIamInstanceProfileAssociation_section"></a>

다음 코드 예시는 `ReplaceIamInstanceProfileAssociation`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](example_cross_ResilientService_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Replace the profile associated with a running instance. After the profile is replaced, the instance
    /// is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is
    /// used to restart the Python web server.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to update.</param>
    /// <param name="credsProfileName">The name of the new profile to associate with the specified instance.</param>
    /// <param name="associationId">The Id of the existing profile association for the instance.</param>
    /// <returns>Async task.</returns>
    public async Task ReplaceInstanceProfile(string instanceId, string credsProfileName, string associationId)
    {
        try
        {
            await _amazonEc2.ReplaceIamInstanceProfileAssociationAsync(
                new ReplaceIamInstanceProfileAssociationRequest()
                {
                    AssociationId = associationId,
                    IamInstanceProfile = new IamInstanceProfileSpecification()
                    {
                        Name = credsProfileName
                    }
                });
            // Allow time before resetting.
            Thread.Sleep(25000);

            await _amazonEc2.RebootInstancesAsync(
                new RebootInstancesRequest(new List<string>() { instanceId }));
            Thread.Sleep(25000);
            var instanceReady = false;
            var retries = 5;
            while (retries-- > 0 && !instanceReady)
            {
                var instancesPaginator =
                    _amazonSsm.Paginators.DescribeInstanceInformation(
                        new DescribeInstanceInformationRequest());
                // Get the entire list using the paginator.
                await foreach (var instance in instancesPaginator.InstanceInformationList)
                {
                    instanceReady = instance.InstanceId == instanceId;
                    if (instanceReady)
                    {
                        break;
                    }
                }
            }
            Console.WriteLine("Waiting for instance to be running.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);
            Console.WriteLine("Instance ready.");
            Console.WriteLine($"Sending restart command to instance {instanceId}");
            await _amazonSsm.SendCommandAsync(
                new SendCommandRequest()
                {
                    InstanceIds = new List<string>() { instanceId },
                    DocumentName = "AWS-RunShellScript",
                    Parameters = new Dictionary<string, List<string>>()
                    {
                        {
                            "commands",
                            new List<string>() { "cd / && sudo python3 server.py 80" }
                        }
                    }
                });
            Console.WriteLine($"Restarted the web server on instance {instanceId}");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while replacing the template.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 **AWS SDK for .NET API 참조의 [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)을 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스에 대한 IAM 인스턴스 프로파일을 바꾸는 방법**  
이 예제에서는 `iip-assoc-060bae234aac2e7fa` 연결로 표시되는 IAM 인스턴스 프로파일을 이름이 `AdminRole`인 IAM 인스턴스 프로파일로 바꿉니다.  

```
aws ec2 replace-iam-instance-profile-association \
    --iam-instance-profile Name=AdminRole \
    --association-id iip-assoc-060bae234aac2e7fa
```
출력:  

```
{
    "IamInstanceProfileAssociation": {
        "InstanceId": "i-087711ddaf98f9489",
        "State": "associating",
        "AssociationId": "iip-assoc-0b215292fab192820",
        "IamInstanceProfile": {
            "Id": "AIPAJLNLDX3AMYZNWYYAY",
            "Arn": "arn:aws:iam::123456789012:instance-profile/AdminRole"
        }
    }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [ReplaceIamInstanceProfileAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-iam-instance-profile-association.html)을 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        ec2Client.send(
          new ReplaceIamInstanceProfileAssociationCommand({
            AssociationId: state.instanceProfileAssociationId,
            IamInstanceProfile: { Name: NAMES.ssmOnlyInstanceProfileName },
          }),
        ),
      );
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/ReplaceIamInstanceProfileAssociationCommand)을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예제에서는 실행 중인 인스턴스의 인스턴스 프로파일을 교체하고, 인스턴스를 재부팅하고, 인스턴스가 시작된 후 인스턴스에 명령을 보냅니다.  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def replace_instance_profile(
        self,
        instance_id: str,
        new_instance_profile_name: str,
        profile_association_id: str,
    ) -> None:
        """
        Replaces the profile associated with a running instance. After the profile is
        replaced, the instance is rebooted to ensure that it uses the new profile. When
        the instance is ready, Systems Manager is used to restart the Python web server.

        :param instance_id: The ID of the instance to restart.
        :param new_instance_profile_name: The name of the new profile to associate with
                                          the specified instance.
        :param profile_association_id: The ID of the existing profile association for the
                                       instance.
        """
        try:
            self.ec2_client.replace_iam_instance_profile_association(
                IamInstanceProfile={"Name": new_instance_profile_name},
                AssociationId=profile_association_id,
            )
            log.info(
                "Replaced instance profile for association %s with profile %s.",
                profile_association_id,
                new_instance_profile_name,
            )
            time.sleep(5)

            self.ec2_client.reboot_instances(InstanceIds=[instance_id])
            log.info("Rebooting instance %s.", instance_id)
            waiter = self.ec2_client.get_waiter("instance_running")
            log.info("Waiting for instance %s to be running.", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info("Instance %s is now running.", instance_id)

            self.ssm_client.send_command(
                InstanceIds=[instance_id],
                DocumentName="AWS-RunShellScript",
                Parameters={"commands": ["cd / && sudo python3 server.py 80"]},
            )
            log.info(f"Restarted the Python web server on instance '{instance_id}'.")
        except ClientError as err:
            log.error("Failed to replace instance profile.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAssociationID.NotFound":
                log.error(
                    f"Association ID '{profile_association_id}' does not exist."
                    "Please check the association ID and try again."
                )
            if error_code == "InvalidInstanceId":
                log.error(
                    f"The specified instance ID '{instance_id}' does not exist or is not available for SSM. "
                    f"Please verify the instance ID and try again."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ReplaceNetworkAclAssociation` 사용
<a name="example_ec2_ReplaceNetworkAclAssociation_section"></a>

다음 코드 예시는 `ReplaceNetworkAclAssociation`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**서브넷과 연결된 네트워크 ACL 교체**  
이 예시에서는 지정한 네트워크 ACL을 지정한 네트워크 ACL 연결의 서브넷과 연결합니다.  
명령:  

```
aws ec2 replace-network-acl-association --association-id aclassoc-e5b95c8c --network-acl-id acl-5fb85d36
```
출력:  

```
{
    "NewAssociationId": "aclassoc-3999875b"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ReplaceNetworkAclAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-network-acl-association.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL을 지정된 네트워크 ACL 연결의 서브넷과 연결합니다.**  

```
Set-EC2NetworkAclAssociation -NetworkAclId acl-12345678 -AssociationId aclassoc-1a2b3c4d
```
**출력:**  

```
aclassoc-87654321
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ReplaceNetworkAclAssociation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL을 지정된 네트워크 ACL 연결의 서브넷과 연결합니다.**  

```
Set-EC2NetworkAclAssociation -NetworkAclId acl-12345678 -AssociationId aclassoc-1a2b3c4d
```
**출력:**  

```
aclassoc-87654321
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ReplaceNetworkAclAssociation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ReplaceNetworkAclEntry` 사용
<a name="example_ec2_ReplaceNetworkAclEntry_section"></a>

다음 코드 예시는 `ReplaceNetworkAclEntry`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 ACL 항목 교체**  
이 예시에서는 지정된 네트워크 ACL에 대한 항목을 대체합니다. 새 규칙 100은 UDP 포트 53(DNS)의 203.0.113.12/24에서 연결된 모든 서브넷으로 유입되는 트래픽을 허용합니다.  
명령:  

```
aws ec2 replace-network-acl-entry --network-acl-id acl-5fb85d36 --ingress --rule-number 100 --protocol udp --port-range From=53,To=53 --cidr-block 203.0.113.12/24 --rule-action allow
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ReplaceNetworkAclEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-network-acl-entry.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL에 지정된 항목을 대체합니다. 새 규칙은 지정된 주소에서 연결된 서브넷으로의 인바운드 트래픽을 허용합니다.**  

```
Set-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 203.0.113.12/24 -RuleAction allow
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ReplaceNetworkAclEntry](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 ACL에 지정된 항목을 대체합니다. 새 규칙은 지정된 주소에서 연결된 서브넷으로의 인바운드 트래픽을 허용합니다.**  

```
Set-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 203.0.113.12/24 -RuleAction allow
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ReplaceNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ReplaceRoute` 사용
<a name="example_ec2_ReplaceRoute_section"></a>

다음 코드 예시는 `ReplaceRoute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**경로를 바꾸는 방법**  
이 예시에서는 지정된 라우팅 테이블에서 지정된 경로를 대체합니다. 새 라우팅은 지정된 CIDR과 일치하며 트래픽을 지정된 가상 사설 게이트웨이로 보냅니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 replace-route --route-table-id rtb-22574640 --destination-cidr-block 10.0.0.0/16 --gateway-id vgw-9a4cacf3
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ReplaceRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-route.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블의 지정된 경로를 대체합니다. 새 경로는 지정된 트래픽을 지정된 가상 프라이빗 게이트웨이로 보냅니다.**  

```
Set-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 10.0.0.0/24 -GatewayId vgw-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ReplaceRoute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블의 지정된 경로를 대체합니다. 새 경로는 지정된 트래픽을 지정된 가상 프라이빗 게이트웨이로 보냅니다.**  

```
Set-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 10.0.0.0/24 -GatewayId vgw-1a2b3c4d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ReplaceRoute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ReplaceRouteTableAssociation` 사용
<a name="example_ec2_ReplaceRouteTableAssociation_section"></a>

다음 코드 예시는 `ReplaceRouteTableAssociation`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**서브넷과 연결된 라우팅 테이블 교체**  
이 예시에서는 지정한 라우팅 테이블을 지정한 라우팅 테이블 연결을 위한 서브넷과 연결합니다.  
명령:  

```
aws ec2 replace-route-table-association --association-id rtbassoc-781d0d1a --route-table-id rtb-22574640
```
출력:  

```
{
    "NewAssociationId": "rtbassoc-3a1f0f58"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ReplaceRouteTableAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-route-table-association.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블을 지정된 라우팅 테이블 연결을 위한 서브넷과 연결합니다.**  

```
Set-EC2RouteTableAssociation -RouteTableId rtb-1a2b3c4d -AssociationId rtbassoc-12345678
```
**출력:**  

```
rtbassoc-87654321
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ReplaceRouteTableAssociation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 라우팅 테이블을 지정된 라우팅 테이블 연결을 위한 서브넷과 연결합니다.**  

```
Set-EC2RouteTableAssociation -RouteTableId rtb-1a2b3c4d -AssociationId rtbassoc-12345678
```
**출력:**  

```
rtbassoc-87654321
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ReplaceRouteTableAssociation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ReportInstanceStatus` 사용
<a name="example_ec2_ReportInstanceStatus_section"></a>

다음 코드 예시는 `ReportInstanceStatus`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스에 대한 상태 피드백 보고**  
이 예시 명령은 지정된 인스턴스에 대한 상태 피드백을 보고합니다.  
명령:  

```
aws ec2 report-instance-status --instances i-1234567890abcdef0 --status impaired --reason-codes unresponsive
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ReportInstanceStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/report-instance-status.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스에 대한 상태 피드백을 보고합니다.**  

```
Send-EC2InstanceStatus -Instance i-12345678 -Status impaired -ReasonCode unresponsive
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ReportInstanceStatus](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스에 대한 상태 피드백을 보고합니다.**  

```
Send-EC2InstanceStatus -Instance i-12345678 -Status impaired -ReasonCode unresponsive
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ReportInstanceStatus](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `RequestSpotFleet` 사용
<a name="example_ec2_RequestSpotFleet_section"></a>

다음 코드 예시는 `RequestSpotFleet`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**서브넷에서 가장 저렴한 가격으로 스팟 플릿 요청**  
이 예시 명령은 서브넷만 다른 두 가지 출시 사양을 가진 스팟 플릿 요청을 생성합니다. 스팟 플릿은 지정된 서브넷에서 가장 낮은 가격으로 인스턴스를 시작합니다. 인스턴스가 기본 VPC로 시작되는 경우, 인스턴스는 기본적으로 퍼블릭 IP 주소를 받습니다. 인스턴스가 기본이 아닌 VPC로 시작되는 경우, 인스턴스는 기본적으로 퍼블릭 IP 주소를 받지 않습니다.  
스팟 플릿 요청에서는 동일한 가용 영역에서 다른 서브넷을 지정할 수 없습니다.  
명령:  

```
aws ec2 request-spot-fleet --spot-fleet-request-config file://config.json
```
Config.json:  

```
{
  "SpotPrice": "0.04",
  "TargetCapacity": 2,
  "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role",
  "LaunchSpecifications": [
      {
          "ImageId": "ami-1a2b3c4d",
          "KeyName": "my-key-pair",
          "SecurityGroups": [
              {
                  "GroupId": "sg-1a2b3c4d"
              }
          ],
          "InstanceType": "m3.medium",
          "SubnetId": "subnet-1a2b3c4d, subnet-3c4d5e6f",
          "IamInstanceProfile": {
              "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
          }
      }
  ]
}
```
출력:  

```
{
  "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"
}
```
**가용 영역에서 최저 가격으로 스팟 플릿 요청**  
이 예시 명령은 가용 영역만 다른 두 가지 출시 사양을 가진 스팟 플릿 요청을 생성합니다. 스팟 플릿은 지정된 가용 영역에서 가장 낮은 가격으로 인스턴스를 시작합니다. 계정이 EC2-VPC만 지원하는 경우, Amazon EC2는 가용 영역의 기본 서브넷에서 스팟 인스턴스를 실행합니다. 계정이 EC2-Classic을 지원하는 경우, Amazon EC2는 가용 영역의 EC2-Classic에서 인스턴스를 시작합니다.  
명령:  

```
aws ec2 request-spot-fleet --spot-fleet-request-config file://config.json
```
Config.json:  

```
{
  "SpotPrice": "0.04",
  "TargetCapacity": 2,
  "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role",
  "LaunchSpecifications": [
      {
          "ImageId": "ami-1a2b3c4d",
          "KeyName": "my-key-pair",
          "SecurityGroups": [
              {
                  "GroupId": "sg-1a2b3c4d"
              }
          ],
          "InstanceType": "m3.medium",
          "Placement": {
              "AvailabilityZone": "us-west-2a, us-west-2b"
          },
          "IamInstanceProfile": {
              "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
          }
      }
  ]
}
```
**서브넷에서 스팟 인스턴스를 시작하고 퍼블릭 IP 주소 할당**  
이 예시 명령은 기본값이 아닌 VPC에서 시작된 인스턴스에 퍼블릭 주소를 할당합니다. 네트워크 인터페이스를 지정할 때는 네트워크 인터페이스를 사용하는 서브넷 ID 및 보안 그룹 ID를 포함해야 합니다.  
명령:  

```
aws ec2 request-spot-fleet --spot-fleet-request-config file://config.json
```
Config.json:  

```
{
  "SpotPrice": "0.04",
  "TargetCapacity": 2,
  "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role",
  "LaunchSpecifications": [
      {
          "ImageId": "ami-1a2b3c4d",
          "KeyName": "my-key-pair",
          "InstanceType": "m3.medium",
          "NetworkInterfaces": [
              {
                  "DeviceIndex": 0,
                  "SubnetId": "subnet-1a2b3c4d",
                  "Groups": [ "sg-1a2b3c4d" ],
                  "AssociatePublicIpAddress": true
              }
          ],
          "IamInstanceProfile": {
              "Arn": "arn:aws:iam::880185128111:instance-profile/my-iam-role"
          }
      }
  ]
}
```
**다양한 할당 전략을 사용하여 스팟 플릿 요청**  
이 예시 명령은 다양한 할당 전략을 사용하여 30개의 인스턴스를 실행하는 스팟 플릿 요청을 생성합니다. 시작 사양은 인스턴스 유형에 따라 다릅니다. 스팟 플릿은 각 유형에 10개의 인스턴스가 있도록 출시 사양에 따라 인스턴스를 배포합니다.  
명령:  

```
aws ec2 request-spot-fleet --spot-fleet-request-config file://config.json
```
Config.json:  

```
{
  "SpotPrice": "0.70",
  "TargetCapacity": 30,
  "AllocationStrategy": "diversified",
  "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role",
  "LaunchSpecifications": [
      {
          "ImageId": "ami-1a2b3c4d",
          "InstanceType": "c4.2xlarge",
          "SubnetId": "subnet-1a2b3c4d"
      },
      {
          "ImageId": "ami-1a2b3c4d",
          "InstanceType": "m3.2xlarge",
          "SubnetId": "subnet-1a2b3c4d"
      },
      {
          "ImageId": "ami-1a2b3c4d",
          "InstanceType": "r3.2xlarge",
          "SubnetId": "subnet-1a2b3c4d"
      }
  ]
}
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*의 스팟 플릿 요청을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [RequestSpotFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/request-spot-fleet.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스 유형에 대해 최저 가격으로 가용 영역에 스팟 플릿 요청을 생성합니다. 계정이 EC2-VPC만 지원하는 경우, 스팟 플릿은 기본 서브넷이 있는 최저 가격의 가용 영역에서 인스턴스를 시작합니다. 계정이 EC2-Classic을 지원하는 경우, 스팟 플릿은 최저 가격의 가용 영역에 있는 EC2-Classic에서 인스턴스를 시작합니다. 지불하는 가격은 요청에 지정된 스팟 가격을 초과하지 않습니다.**  

```
$sg = New-Object Amazon.EC2.Model.GroupIdentifier
$sg.GroupId = "sg-12345678"
$lc = New-Object Amazon.EC2.Model.SpotFleetLaunchSpecification
$lc.ImageId = "ami-12345678"
$lc.InstanceType = "m3.medium"
$lc.SecurityGroups.Add($sg) 
Request-EC2SpotFleet -SpotFleetRequestConfig_SpotPrice 0.04 `
-SpotFleetRequestConfig_TargetCapacity 2 `
-SpotFleetRequestConfig_IamFleetRole arn:aws:iam::123456789012:role/my-spot-fleet-role `
-SpotFleetRequestConfig_LaunchSpecification $lc
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RequestSpotFleet](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스 유형에 대해 최저 가격으로 가용 영역에 스팟 플릿 요청을 생성합니다. 계정이 EC2-VPC만 지원하는 경우, 스팟 플릿은 기본 서브넷이 있는 최저 가격의 가용 영역에서 인스턴스를 시작합니다. 계정이 EC2-Classic을 지원하는 경우, 스팟 플릿은 최저 가격의 가용 영역에 있는 EC2-Classic에서 인스턴스를 시작합니다. 지불하는 가격은 요청에 지정된 스팟 가격을 초과하지 않습니다.**  

```
$sg = New-Object Amazon.EC2.Model.GroupIdentifier
$sg.GroupId = "sg-12345678"
$lc = New-Object Amazon.EC2.Model.SpotFleetLaunchSpecification
$lc.ImageId = "ami-12345678"
$lc.InstanceType = "m3.medium"
$lc.SecurityGroups.Add($sg) 
Request-EC2SpotFleet -SpotFleetRequestConfig_SpotPrice 0.04 `
-SpotFleetRequestConfig_TargetCapacity 2 `
-SpotFleetRequestConfig_IamFleetRole arn:aws:iam::123456789012:role/my-spot-fleet-role `
-SpotFleetRequestConfig_LaunchSpecification $lc
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RequestSpotFleet](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `RequestSpotInstances` 사용
<a name="example_ec2_RequestSpotInstances_section"></a>

다음 코드 예시는 `RequestSpotInstances`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스팟 인스턴스 요청**  
이 예시 명령은 지정된 가용 영역에서 5개의 인스턴스에 대한 일회성 스팟 인스턴스 요청을 생성합니다. 계정이 EC2-VPC만 지원하는 경우, Amazon EC2는 지정된 가용 영역의 기본 서브넷에서 인스턴스를 실행합니다. 계정이 EC2-Classic을 지원하는 경우, Amazon EC2는 지정된 가용 영역에서 EC2-Classic의 인스턴스를 시작합니다.  
명령:  

```
aws ec2 request-spot-instances --spot-price "0.03" --instance-count 5 --type "one-time" --launch-specification file://specification.json
```
Specification.json:  

```
{
  "ImageId": "ami-1a2b3c4d",
  "KeyName": "my-key-pair",
  "SecurityGroupIds": [ "sg-1a2b3c4d" ],
  "InstanceType": "m3.medium",
  "Placement": {
    "AvailabilityZone": "us-west-2a"
  },
  "IamInstanceProfile": {
      "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
  }
}
```
출력:  

```
{
  "SpotInstanceRequests": [
      {
          "Status": {
              "UpdateTime": "2014-03-25T20:54:21.000Z",
              "Code": "pending-evaluation",
              "Message": "Your Spot request has been submitted for review, and is pending evaluation."
          },
          "ProductDescription": "Linux/UNIX",
          "SpotInstanceRequestId": "sir-df6f405d",
          "State": "open",
          "LaunchSpecification": {
              "Placement": {
                  "AvailabilityZone": "us-west-2a"
              },
              "ImageId": "ami-1a2b3c4d",
              "KeyName": "my-key-pair",
              "SecurityGroups": [
                  {
                      "GroupName": "my-security-group",
                      "GroupId": "sg-1a2b3c4d"
                  }
              ],
              "Monitoring": {
                  "Enabled": false
              },
              "IamInstanceProfile": {
                  "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
              },
              "InstanceType": "m3.medium"
          },
          "Type": "one-time",
          "CreateTime": "2014-03-25T20:54:20.000Z",
          "SpotPrice": "0.050000"
      },
      ...
  ]
}
```
이 예시 명령은 지정된 서브넷에서 5개의 인스턴스에 대한 일회성 스팟 인스턴스 요청을 생성합니다. Amazon EC2는 지정된 서브넷에서 인스턴스를 시작합니다. VPC가 기본값이 아닌 VPC인 경우 인스턴스는 기본적으로 퍼블릭 IP 주소를 받지 않습니다.  
명령:  

```
aws ec2 request-spot-instances --spot-price "0.050" --instance-count 5 --type "one-time" --launch-specification file://specification.json
```
Specification.json:  

```
{
  "ImageId": "ami-1a2b3c4d",
  "SecurityGroupIds": [ "sg-1a2b3c4d" ],
  "InstanceType": "m3.medium",
  "SubnetId": "subnet-1a2b3c4d",
  "IamInstanceProfile": {
      "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
  }
}
```
출력:  

```
{
  "SpotInstanceRequests": [
      {
          "Status": {
             "UpdateTime": "2014-03-25T22:21:58.000Z",
             "Code": "pending-evaluation",
             "Message": "Your Spot request has been submitted for review, and is pending evaluation."
          },
          "ProductDescription": "Linux/UNIX",
          "SpotInstanceRequestId": "sir-df6f405d",
          "State": "open",
          "LaunchSpecification": {
             "Placement": {
                 "AvailabilityZone": "us-west-2a"
             }
             "ImageId": "ami-1a2b3c4d"
             "SecurityGroups": [
                 {
                     "GroupName": "my-security-group",
                     "GroupID": "sg-1a2b3c4d"
                 }
             ]
             "SubnetId": "subnet-1a2b3c4d",
             "Monitoring": {
                 "Enabled": false
             },
             "IamInstanceProfile": {
                 "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
             },
             "InstanceType": "m3.medium",
         },
         "Type": "one-time",
         "CreateTime": "2014-03-25T22:21:58.000Z",
         "SpotPrice": "0.050000"
      },
      ...
  ]
}
```
이 예시에서는 기본값이 아닌 VPC에서 실행하는 스팟 인스턴스에 퍼블릭 IP 주소를 할당합니다. 네트워크 인터페이스를 지정할 때는 네트워크 인터페이스를 사용하는 서브넷 ID 및 보안 그룹 ID를 포함해야 합니다.  
명령:  

```
aws ec2 request-spot-instances --spot-price "0.050" --instance-count 1 --type "one-time" --launch-specification file://specification.json
```
Specification.json:  

```
{
  "ImageId": "ami-1a2b3c4d",
  "KeyName": "my-key-pair",
  "InstanceType": "m3.medium",
  "NetworkInterfaces": [
    {
      "DeviceIndex": 0,
      "SubnetId": "subnet-1a2b3c4d",
      "Groups": [ "sg-1a2b3c4d" ],
      "AssociatePublicIpAddress": true
    }
  ],
  "IamInstanceProfile": {
      "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
  }
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [RequestSpotInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/request-spot-instances.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 서브넷에서 일회성 스팟 인스턴스를 요청합니다. 보안 그룹은 지정된 서브넷이 포함된 VPC에 대해 생성해야 하며, 네트워크 인터페이스를 사용할 때는 보안 그룹을 ID로 지정해야 합니다. 네트워크 인터페이스를 지정할 때는 해당 네트워크 인터페이스를 사용하는 서브넷 ID를 포함해야 합니다.**  

```
$n = New-Object Amazon.EC2.Model.InstanceNetworkInterfaceSpecification
$n.DeviceIndex = 0
$n.SubnetId = "subnet-12345678"
$n.Groups.Add("sg-12345678")
Request-EC2SpotInstance -InstanceCount 1 -SpotPrice 0.050 -Type one-time `
-IamInstanceProfile_Arn arn:aws:iam::123456789012:instance-profile/my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType m3.medium `
-LaunchSpecification_NetworkInterface $n
```
**출력:**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 12/26/2015 7:44:10 AM
Fault                    :
InstanceId               :
LaunchedAvailabilityZone :
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.050000
State                    : open
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {}
Type                     : one-time
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RequestSpotInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 서브넷에서 일회성 스팟 인스턴스를 요청합니다. 보안 그룹은 지정된 서브넷이 포함된 VPC에 대해 생성해야 하며, 네트워크 인터페이스를 사용할 때는 보안 그룹을 ID로 지정해야 합니다. 네트워크 인터페이스를 지정할 때는 해당 네트워크 인터페이스를 사용하는 서브넷 ID를 포함해야 합니다.**  

```
$n = New-Object Amazon.EC2.Model.InstanceNetworkInterfaceSpecification
$n.DeviceIndex = 0
$n.SubnetId = "subnet-12345678"
$n.Groups.Add("sg-12345678")
Request-EC2SpotInstance -InstanceCount 1 -SpotPrice 0.050 -Type one-time `
-IamInstanceProfile_Arn arn:aws:iam::123456789012:instance-profile/my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType m3.medium `
-LaunchSpecification_NetworkInterface $n
```
**출력:**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 12/26/2015 7:44:10 AM
Fault                    :
InstanceId               :
LaunchedAvailabilityZone :
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.050000
State                    : open
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {}
Type                     : one-time
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RequestSpotInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ResetImageAttribute` 사용
<a name="example_ec2_ResetImageAttribute_section"></a>

다음 코드 예시는 `ResetImageAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**launchPermission 속성 재설정**  
이 예시에서는 지정된 AMI의 `launchPermission` 속성을 기본값으로 재설정합니다. 기본적으로 AMI는 프라이빗으로 설정됩니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 reset-image-attribute --image-id ami-5731123e --attribute launchPermission
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ResetImageAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-image-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 'launchPermission' 속성을 기본값으로 재설정합니다. 기본적으로 AMI는 프라이빗으로 설정됩니다.**  

```
Reset-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ResetImageAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 'launchPermission' 속성을 기본값으로 재설정합니다. 기본적으로 AMI는 프라이빗으로 설정됩니다.**  

```
Reset-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ResetImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ResetInstanceAttribute` 사용
<a name="example_ec2_ResetInstanceAttribute_section"></a>

다음 코드 예시는 `ResetInstanceAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**sourceDestCheck 속성 재설정**  
이 예시에서는 지정된 인스턴스의 `sourceDestCheck` 속성을 재설정합니다. 인스턴스가 VPC에 있어야 합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 reset-instance-attribute --instance-id i-1234567890abcdef0 --attribute sourceDestCheck
```
**커널 속성을 재설정하는 방법**  
이 예시에서는 지정된 인스턴스의 `kernel` 속성을 재설정합니다. 인스턴스는 `stopped` 상태여야 합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 reset-instance-attribute --instance-id i-1234567890abcdef0 --attribute kernel
```
**ramdisk 속성 재설정**  
이 예시에서는 지정된 인스턴스의 `ramdisk` 속성을 재설정합니다. 인스턴스는 `stopped` 상태여야 합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 reset-instance-attribute --instance-id i-1234567890abcdef0 --attribute ramdisk
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ResetInstanceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-instance-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스에 대한 'sriovNetSupport' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**예제 2: 이 예제에서는 지정된 인스턴스에 대한 'ebsOptimized' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**예제 3: 이 예제에서는 지정된 인스턴스에 대한 'sourceDestCheck' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sourceDestCheck
```
**예제 4: 이 예제에서는 지정된 인스턴스에 대한 'disableApiTermination' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**예제 5: 이 예제에서는 지정된 인스턴스의 'instanceInitiatedShutdownBehavior' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ResetInstanceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스에 대한 'sriovNetSupport' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**예제 2: 이 예제에서는 지정된 인스턴스에 대한 'ebsOptimized' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**예제 3: 이 예제에서는 지정된 인스턴스에 대한 'sourceDestCheck' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sourceDestCheck
```
**예제 4: 이 예제에서는 지정된 인스턴스에 대한 'disableApiTermination' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**예제 5: 이 예제에서는 지정된 인스턴스의 'instanceInitiatedShutdownBehavior' 속성을 재설정합니다.**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ResetInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ResetNetworkInterfaceAttribute` 사용
<a name="example_ec2_ResetNetworkInterfaceAttribute_section"></a>

다음 코드 예시는 `ResetNetworkInterfaceAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 인터페이스 속성 재설정**  
다음 `reset-network-interface-attribute` 예시에서는 소스/대상 검사 속성의 값을 `true`로 재설정합니다.  

```
aws ec2 reset-network-interface-attribute \
    --network-interface-id eni-686ea200 \
    --source-dest-check
```
이 명령은 출력을 생성하지 않습니다.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ResetNetworkInterfaceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-network-interface-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스에 대한 소스/대상 확인을 재설정합니다.**  

```
Reset-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ResetNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스에 대한 소스/대상 확인을 재설정합니다.**  

```
Reset-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ResetNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `ResetSnapshotAttribute` 사용
<a name="example_ec2_ResetSnapshotAttribute_section"></a>

다음 코드 예시는 `ResetSnapshotAttribute`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**스냅샷 속성 재설정**  
이 예시에서는 스냅샷 `snap-1234567890abcdef0`에 대한 볼륨 생성 권한을 초기화합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 reset-snapshot-attribute --snapshot-id snap-1234567890abcdef0 --attribute createVolumePermission
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ResetSnapshotAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-snapshot-attribute.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 스냅샷의 지정된 속성을 재설정합니다.**  

```
Reset-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ResetSnapshotAttribute](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 스냅샷의 지정된 속성을 재설정합니다.**  

```
Reset-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ResetSnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `RevokeSecurityGroupEgress` 사용
<a name="example_ec2_RevokeSecurityGroupEgress_section"></a>

다음 코드 예시는 `RevokeSecurityGroupEgress`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 특정 주소 범위로 아웃바운드 트래픽을 허용하는 규칙 제거**  
다음 `revoke-security-group-egress` 예시 명령은 TCP 포트 80에서 지정된 주소 범위에 대한 액세스 권한을 부여하는 규칙을 제거합니다.  

```
aws ec2 revoke-security-group-egress \
    --group-id sg-026c12253ce15eff7 \
    --ip-permissions [{IpProtocol=tcp,FromPort=80,ToPort=80,IpRanges=[{CidrIp=10.0.0.0/16}]
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *Amazon EC2 사용 설명서*의 [보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)을 참조하세요.  
**예시 2: 특정 보안 그룹에 대한 아웃바운드 트래픽을 허용하는 규칙 제거**  
다음 `revoke-security-group-egress` 예시 명령은 TCP 포트 80에서 지정된 보안 그룹에 대한 액세스 권한을 부여하는 규칙을 제거합니다.  

```
aws ec2 revoke-security-group-egress \
    --group-id sg-026c12253ce15eff7 \
    --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443,"UserIdGroupPairs": [{"GroupId": "sg-06df23a01ff2df86d"}]}]'
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *Amazon EC2 사용 설명서*의 [보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [RevokeSecurityGroupEgress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/revoke-security-group-egress.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 EC2-VPC에 지정된 보안 그룹에 대한 규칙을 제거합니다. 이렇게 하면 지정된 IP 주소 범위에 대한 TCP 포트 80 액세스 권한이 취소됩니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**예제 2: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**예제 3: 이 예제에서는 지정된 소스 보안 그룹에 대한 TCP 포트 80 액세스 권한을 취소합니다.**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RevokeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 EC2-VPC에 지정된 보안 그룹에 대한 규칙을 제거합니다. 이렇게 하면 지정된 IP 주소 범위에 대한 TCP 포트 80 액세스 권한이 취소됩니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**예제 2: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**예제 3: 이 예제에서는 지정된 소스 보안 그룹에 대한 TCP 포트 80 액세스 권한을 취소합니다.**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RevokeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `RevokeSecurityGroupIngress` 사용
<a name="example_ec2_RevokeSecurityGroupIngress_section"></a>

다음 코드 예시는 `RevokeSecurityGroupIngress`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 보안 그룹에서 규칙 제거**  
다음 `revoke-security-group-ingress` 예시에서는 기본 VPC의 지정된 보안 그룹에서 `203.0.113.0/24` 주소 범위에 대한 TCP 포트 22 액세스를 제거합니다.  

```
aws ec2 revoke-security-group-ingress \
    --group-name mySecurityGroup
    --protocol tcp \
    --port 22 \
    --cidr 203.0.113.0/24
```
이 명령은 성공 시 출력을 생성하지 않습니다.  
자세한 내용은 *Amazon EC2 사용 설명서*의 [보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)을 참조하세요.  
**예시 2: IP 권한 세트를 사용하여 규칙 제거**  
다음 `revoke-security-group-ingress` 예시에서는 `ip-permissions` 파라미터를 사용하여 ICMP 메시지 `Destination Unreachable: Fragmentation Needed and Don't Fragment was Set`(유형 3, 코드 4)를 허용하는 인바운드 규칙을 제거합니다.  

```
aws ec2 revoke-security-group-ingress \
    --group-id sg-026c12253ce15eff7 \
    --ip-permissions IpProtocol=icmp,FromPort=3,ToPort=4,IpRanges=[{CidrIp=0.0.0.0/0}]
```
이 명령은 성공 시 출력을 생성하지 않습니다.  
자세한 내용은 *Amazon EC2 사용 설명서*의 [보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [RevokeSecurityGroupIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/revoke-security-group-ingress.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 EC2-VPC의 지정된 보안 그룹에 대해 지정된 주소 범위에서 TCP 포트 22에 대한 액세스 권한을 취소합니다. 보안 그룹 이름이 아닌 보안 그룹 ID를 사용하여 EC2-VPC의 보안 그룹을 식별해야 한다는 점에 유의하세요. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**예제 2: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**예제 3: 이 예제에서는 EC2-Classic의 지정된 보안 그룹에 대해 지정된 주소 범위에서 TCP 포트 22에 대한 액세스 권한을 취소합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
**예제 4: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RevokeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 EC2-VPC의 지정된 보안 그룹에 대해 지정된 주소 범위에서 TCP 포트 22에 대한 액세스 권한을 취소합니다. 보안 그룹 이름이 아닌 보안 그룹 ID를 사용하여 EC2-VPC의 보안 그룹을 식별해야 한다는 점에 유의하세요. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**예제 2: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**예제 3: 이 예제에서는 EC2-Classic의 지정된 보안 그룹에 대해 지정된 주소 범위에서 TCP 포트 22에 대한 액세스 권한을 취소합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
**예제 4: PowerShell 버전 2에서 IpPermission 객체를 생성하려면 New-Object를 사용해야 합니다.**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RevokeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `RunInstances` 함께 사용
<a name="example_ec2_RunInstances_section"></a>

다음 코드 예시는 `RunInstances`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Create and run an EC2 instance.
    /// </summary>
    /// <param name="ImageId">The image Id of the image used as a basis for the
    /// EC2 instance.</param>
    /// <param name="instanceType">The instance type of the EC2 instance to create.</param>
    /// <param name="keyName">The name of the key pair to associate with the
    /// instance.</param>
    /// <param name="groupId">The Id of the Amazon EC2 security group that will be
    /// allowed to interact with the new EC2 instance.</param>
    /// <returns>The instance Id of the new EC2 instance.</returns>
    public async Task<string> RunInstances(string imageId, string instanceType, string keyName, string groupId)
    {
        try
        {
            var request = new RunInstancesRequest
            {
                ImageId = imageId,
                InstanceType = instanceType,
                KeyName = keyName,
                MinCount = 1,
                MaxCount = 1,
                SecurityGroupIds = new List<string> { groupId }
            };
            var response = await _amazonEC2.RunInstancesAsync(request);
            var instanceId = response.Reservation.Instances[0].InstanceId;

            Console.Write("Waiting for the instance to start.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);

            return instanceId;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidGroupId.NotFound")
            {
                _logger.LogError(
                    $"GroupId {groupId} was not found. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while running the instance.: {ex.Message}");
            throw;
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [RunInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/RunInstances)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_run_instances
#
# This function launches one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i image_id - The ID of the Amazon Machine Image (AMI) to use.
#       -t instance_type - The instance type to use (e.g., t2.micro).
#       -k key_pair_name - The name of the key pair to use.
#       -s security_group_id - The ID of the security group to use.
#       -c count - The number of instances to launch (default: 1).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_run_instances() {
  local image_id instance_type key_pair_name security_group_id count response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_run_instances"
    echo "Launches one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i image_id - The ID of the Amazon Machine Image (AMI) to use."
    echo "  -t instance_type - The instance type to use (e.g., t2.micro)."
    echo "  -k key_pair_name - The name of the key pair to use."
    echo "  -s security_group_id - The ID of the security group to use."
    echo "  -c count - The number of instances to launch (default: 1)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:t:k:s:c:h" option; do
    case "${option}" in
      i) image_id="${OPTARG}" ;;
      t) instance_type="${OPTARG}" ;;
      k) key_pair_name="${OPTARG}" ;;
      s) security_group_id="${OPTARG}" ;;
      c) count="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$image_id" ]]; then
    errecho "ERROR: You must provide an Amazon Machine Image (AMI) ID with the -i parameter."
    usage
    return 1
  fi

  if [[ -z "$instance_type" ]]; then
    errecho "ERROR: You must provide an instance type with the -t parameter."
    usage
    return 1
  fi

  if [[ -z "$key_pair_name" ]]; then
    errecho "ERROR: You must provide a key pair name with the -k parameter."
    usage
    return 1
  fi

  if [[ -z "$security_group_id" ]]; then
    errecho "ERROR: You must provide a security group ID with the -s parameter."
    usage
    return 1
  fi

  if [[ -z "$count" ]]; then
    count=1
  fi

  response=$(aws ec2 run-instances \
    --image-id "$image_id" \
    --instance-type "$instance_type" \
    --key-name "$key_pair_name" \
    --security-group-ids "$security_group_id" \
    --count "$count" \
    --query 'Instances[*].[InstanceId]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports run-instances operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [RunInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/RunInstances)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Launch an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceName: A name for the EC2 instance.
  \param amiId: An Amazon Machine Image (AMI) identifier.
  \param[out] instanceID: String to return the instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::runInstance(const Aws::String &instanceName,
                              const Aws::String &amiId,
                              Aws::String &instanceID,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    instanceID = instances[0].GetInstanceId();

    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [RunInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/RunInstances)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 기본 서브넷에서 인스턴스를 시작하는 방법**  
다음 `run-instances` 예제에서는 현재 리전의 기본 서브넷에서 `t2.micro` 유형의 단일 인스턴스를 시작하고 이를 해당 리전에서 기본 VPC에 대한 기본 서브넷에 연결합니다. 키 페어는 SSH(Linux) 또는 RDP(Windows)를 사용하여 인스턴스에 연결할 계획이 없는 경우 선택 사항입니다.  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --key-name MyKeyPair
```
출력:  

```
{
    "Instances": [
        {
            "AmiLaunchIndex": 0,
            "ImageId": "ami-0abcdef1234567890",
            "InstanceId": "i-1231231230abcdef0",
            "InstanceType": "t2.micro",
            "KeyName": "MyKeyPair",
            "LaunchTime": "2018-05-10T08:05:20.000Z",
            "Monitoring": {
                "State": "disabled"
            },
            "Placement": {
                "AvailabilityZone": "us-east-2a",
                "GroupName": "",
                "Tenancy": "default"
            },
            "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
            "PrivateIpAddress": "10.0.0.157",
            "ProductCodes": [],
            "PublicDnsName": "",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "StateTransitionReason": "",
            "SubnetId": "subnet-04a636d18e83cfacb",
            "VpcId": "vpc-1234567890abcdef0",
            "Architecture": "x86_64",
            "BlockDeviceMappings": [],
            "ClientToken": "",
            "EbsOptimized": false,
            "Hypervisor": "xen",
            "NetworkInterfaces": [
                {
                    "Attachment": {
                        "AttachTime": "2018-05-10T08:05:20.000Z",
                        "AttachmentId": "eni-attach-0e325c07e928a0405",
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "Status": "attaching"
                    },
                    "Description": "",
                    "Groups": [
                        {
                            "GroupName": "MySecurityGroup",
                            "GroupId": "sg-0598c7d356eba48d7"
                        }
                    ],
                    "Ipv6Addresses": [],
                    "MacAddress": "0a:ab:58:e0:67:e2",
                    "NetworkInterfaceId": "eni-0c0a29997760baee7",
                    "OwnerId": "123456789012",
                    "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                    "PrivateIpAddress": "10.0.0.157",
                    "PrivateIpAddresses": [
                        {
                            "Primary": true,
                            "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                            "PrivateIpAddress": "10.0.0.157"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Status": "in-use",
                    "SubnetId": "subnet-04a636d18e83cfacb",
                    "VpcId": "vpc-1234567890abcdef0",
                    "InterfaceType": "interface"
                }
            ],
            "RootDeviceName": "/dev/xvda",
            "RootDeviceType": "ebs",
            "SecurityGroups": [
                {
                    "GroupName": "MySecurityGroup",
                    "GroupId": "sg-0598c7d356eba48d7"
                }
            ],
            "SourceDestCheck": true,
            "StateReason": {
                "Code": "pending",
                "Message": "pending"
            },
            "Tags": [],
            "VirtualizationType": "hvm",
            "CpuOptions": {
                "CoreCount": 1,
                "ThreadsPerCore": 1
            },
            "CapacityReservationSpecification": {
                "CapacityReservationPreference": "open"
            },
            "MetadataOptions": {
                "State": "pending",
                "HttpTokens": "optional",
                "HttpPutResponseHopLimit": 1,
                "HttpEndpoint": "enabled"
            }
        }
    ],
    "OwnerId": "123456789012",
    "ReservationId": "r-02a3f596d91211712"
}
```
**예제 2: 기본이 아닌 서브넷에서 인스턴스를 시작하고 퍼블릭 IP 주소를 추가하는 방법**  
다음 `run-instances` 예제에서는 기본이 아닌 서브넷에서 시작하는 인스턴스에 대해 퍼블릭 IP 주소를 요청합니다. 인스턴스는 지정된 보안 그룹에 연결됩니다.  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --subnet-id subnet-08fc749671b2d077c \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --associate-public-ip-address \
    --key-name MyKeyPair
```
`run-instances` 출력 예제는 예제 1을 참조하세요.  
**예제 3: 추가 볼륨이 포함된 인스턴스를 시작하는 방법**  
다음 `run-instances` 예제에서는 시작할 때 추가 볼륨을 연결하도록 mapping.json에 지정된 블록 디바이스 매핑을 사용합니다. 블록 디바이스 매핑은 EBS 볼륨, 인스턴스 저장소 볼륨 또는 EBS 볼륨 및 인스턴스 저장소 볼륨 모두를 지정할 수 있습니다.  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --subnet-id subnet-08fc749671b2d077c \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --key-name MyKeyPair \
    --block-device-mappings file://mapping.json
```
`mapping.json`의 콘텐츠: 이 예제에서는 크기가 100GiB인 빈 EBS 볼륨(`/dev/sdh`)을 추가합니다.  

```
[
    {
        "DeviceName": "/dev/sdh",
        "Ebs": {
            "VolumeSize": 100
        }
    }
]
```
`mapping.json`의 콘텐츠: 이 예제에서는 `ephemeral1`을 인스턴스 저장소 볼륨으로 추가합니다.  

```
[
    {
        "DeviceName": "/dev/sdc",
        "VirtualName": "ephemeral1"
    }
]
```
`run-instances` 출력 예제는 예제 1을 참조하세요.  
블록 디바이스 매핑에 대한 자세한 내용은 *Amazon EC2 사용 설명서*에서 [블록 디바이스 매핑](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html)을 참조하세요.  
**예제 4: 인스턴스를 시작하고 생성 시 태그를 추가하는 방법**  
다음 `run-instances` 예제에서는 키가 `production`이고 값이 `webserver`인 태그를 인스턴스에 추가합니다. 이 명령은 또 생성되는 EBS 볼륨(이 경우에는 루트 볼륨)에 키가 `cost-center`이고 값이 `cc123`인 태그를 적용합니다.  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --count 1 \
    --subnet-id subnet-08fc749671b2d077c \
    --key-name MyKeyPair \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --tag-specifications 'ResourceType=instance,Tags=[{Key=webserver,Value=production}]' 'ResourceType=volume,Tags=[{Key=cost-center,Value=cc123}]'
```
`run-instances` 출력 예제는 예제 1을 참조하세요.  
**예제 5: 사용자 데이터를 포함하는 인스턴스를 시작하는 방법**  
다음 `run-instances` 예제에서는 인스턴스의 구성 스크립트가 포함된 `my_script.txt` 파일에 사용자 데이터를 전달합니다. 스크립트는 시작할 때 실행됩니다.  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --count 1 \
    --subnet-id subnet-08fc749671b2d077c \
    --key-name MyKeyPair \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --user-data file://my_script.txt
```
`run-instances` 출력 예제는 예제 1을 참조하세요.  
인스턴스 사용자 데이터에 대한 자세한 내용은 *Amazon EC2 사용 설명서*에서 [인스턴스 사용자 데이터 작업](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-add-user-data.html)을 참조하세요.  
**예제 6: 성능 버스트 가능 인스턴스를 시작하는 방법**  
다음 `run-instances` 예제에서는 `unlimited` 크레딧 옵션을 사용하여 t2.micro 인스턴스를 시작합니다. T2 인스턴스를 시작할 때 `--credit-specification`을 지정하지 않으면 기본값은 `standard` 크레딧 옵션입니다. T3 인스턴스를 시작할 때 기본값은 `unlimited` 크레딧 옵션입니다.  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --count 1 \
    --subnet-id subnet-08fc749671b2d077c \
    --key-name MyKeyPair \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --credit-specification CpuCredits=unlimited
```
`run-instances` 출력 예제는 예제 1을 참조하세요.  
성능 버스트 가능 인스턴스에 대한 자세한 내용은 *Amazon EC2 사용 설명서*에서 [성능 버스트 가능 인스턴스](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html)를 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [RunInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/run-instances.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Runs an EC2 instance asynchronously.
     *
     * @param instanceType The instance type to use for the EC2 instance.
     * @param keyName The name of the key pair to associate with the EC2 instance.
     * @param groupName The name of the security group to associate with the EC2 instance.
     * @param amiId The ID of the Amazon Machine Image (AMI) to use for the EC2 instance.
     * @return A {@link CompletableFuture} that completes with the ID of the started EC2 instance.
     * @throws RuntimeException If there is an error running the EC2 instance.
     */
    public CompletableFuture<String> runInstanceAsync(String instanceType, String keyName, String groupName, String amiId) {
        RunInstancesRequest runRequest = RunInstancesRequest.builder()
            .instanceType(instanceType)
            .keyName(keyName)
            .securityGroups(groupName)
            .maxCount(1)
            .minCount(1)
            .imageId(amiId)
            .build();

        CompletableFuture<RunInstancesResponse> responseFuture = getAsyncClient().runInstances(runRequest);
        return responseFuture.thenCompose(response -> {
            String instanceIdVal = response.instances().get(0).instanceId();
            System.out.println("Going to start an EC2 instance and use a waiter to wait for it to be in running state");
            return getAsyncClient().waiter()
                .waitUntilInstanceExists(r -> r.instanceIds(instanceIdVal))
                .thenCompose(waitResponse -> getAsyncClient().waiter()
                    .waitUntilInstanceRunning(r -> r.instanceIds(instanceIdVal))
                    .thenApply(runningResponse -> instanceIdVal));
        }).exceptionally(throwable -> {
            // Handle any exceptions that occurred during the async call
            throw new RuntimeException("Failed to run EC2 instance: " + throwable.getMessage(), throwable);
        });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x  API 참조의* [RunInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/RunInstances)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, RunInstancesCommand } from "@aws-sdk/client-ec2";

/**
 * Create new EC2 instances.
 * @param {{
 *  keyName: string,
 *  securityGroupIds: string[],
 *  imageId: string,
 *  instanceType: import('@aws-sdk/client-ec2')._InstanceType,
 *  minCount?: number,
 *  maxCount?: number }} options
 */
export const main = async ({
  keyName,
  securityGroupIds,
  imageId,
  instanceType,
  minCount = "1",
  maxCount = "1",
}) => {
  const client = new EC2Client({});
  minCount = Number.parseInt(minCount);
  maxCount = Number.parseInt(maxCount);
  const command = new RunInstancesCommand({
    // Your key pair name.
    KeyName: keyName,
    // Your security group.
    SecurityGroupIds: securityGroupIds,
    // An Amazon Machine Image (AMI). There are multiple ways to search for AMIs. For more information, see:
    // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html
    ImageId: imageId,
    // An instance type describing the resources provided to your instance. There are multiple
    // ways to search for instance types. For more information see:
    // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-discovery.html
    InstanceType: instanceType,
    // Availability Zones have capacity limitations that may impact your ability to launch instances.
    // The `RunInstances` operation will only succeed if it can allocate at least the `MinCount` of instances.
    // However, EC2 will attempt to launch up to the `MaxCount` of instances, even if the full request cannot be satisfied.
    // If you need a specific number of instances, use `MinCount` and `MaxCount` set to the same value.
    // If you want to launch up to a certain number of instances, use `MaxCount` and let EC2 provision as many as possible.
    // If you require a minimum number of instances, but do not want to exceed a maximum, use both `MinCount` and `MaxCount`.
    MinCount: minCount,
    MaxCount: maxCount,
  });

  try {
    const { Instances } = await client.send(command);
    const instanceList = Instances.map(
      (instance) => `• ${instance.InstanceId}`,
    ).join("\n");
    console.log(`Launched instances:\n${instanceList}`);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceCountExceeded") {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript  API 참조의* [RunInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/RunInstancesCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun createEC2Instance(
    name: String,
    amiId: String,
): String? {
    val request =
        RunInstancesRequest {
            imageId = amiId
            instanceType = InstanceType.T1Micro
            maxCount = 1
            minCount = 1
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.runInstances(request)
        val instanceId = response.instances?.get(0)?.instanceId
        val tag =
            Tag {
                key = "Name"
                value = name
            }

        val requestTags =
            CreateTagsRequest {
                resources = listOf(instanceId.toString())
                tags = listOf(tag)
            }
        ec2.createTags(requestTags)
        println("Successfully started EC2 Instance $instanceId based on AMI $amiId")
        return instanceId
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [RunInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 EC2-Classic 또는 기본 VPC에서 지정된 AMI의 단일 인스턴스를 시작합니다.**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -InstanceType m3.medium -KeyName my-key-pair -SecurityGroup my-security-group
```
**예제 2: 이 예제에서는 VPC에서 지정된 AMI의 단일 인스턴스를 시작합니다.**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -SubnetId subnet-12345678 -InstanceType t2.micro -KeyName my-key-pair -SecurityGroupId sg-12345678
```
**예제 3: EBS 볼륨 또는 인스턴스 저장소 볼륨을 추가하려면 블록 디바이스 매핑을 정의하고 명령에 추가합니다. 이 예제에서는 인스턴스 저장소 볼륨을 추가합니다.**  

```
$bdm = New-Object Amazon.EC2.Model.BlockDeviceMapping
$bdm.VirtualName = "ephemeral0"
$bdm.DeviceName = "/dev/sdf"

New-EC2Instance -ImageId ami-12345678 -BlockDeviceMapping $bdm ...
```
**예제 4: 현재 Windows AMI 중 하나를 지정하려면 Get-EC2ImageByName을 사용하여 AMI ID를 가져옵니다. 이 예제에서는 Windows Server 2016용 최신 기본 AMI를 기반으로 인스턴스를 시작합니다.**  

```
$ami = Get-EC2ImageByName WINDOWS_2016_BASE

New-EC2Instance -ImageId $ami.ImageId ...
```
**예제 5: 지정된 전용 호스트 환경에서 인스턴스를 시작합니다.**  

```
New-EC2Instance -ImageId ami-1a2b3c4d -InstanceType m4.large -KeyName my-key-pair -SecurityGroupId sg-1a2b3c4d  -AvailabilityZone us-west-1a -Tenancy host -HostID h-1a2b3c4d5e6f1a2b3
```
**예제 6: 이 요청에서는 두 개의 인스턴스를 시작하고 키가 webserver이고 값이 production인 태그를 인스턴스에 적용합니다. 또한 이 요청은 생성된 볼륨(이 경우 각 인스턴스의 루트 볼륨)에 키가 cost-center이고 값이 cc123인 태그를 적용합니다.**  

```
$tag1 = @{ Key="webserver"; Value="production" }
$tag2 = @{ Key="cost-center"; Value="cc123" }

$tagspec1 = new-object Amazon.EC2.Model.TagSpecification
$tagspec1.ResourceType = "instance"
$tagspec1.Tags.Add($tag1)

$tagspec2 = new-object Amazon.EC2.Model.TagSpecification
$tagspec2.ResourceType = "volume"
$tagspec2.Tags.Add($tag2)

New-EC2Instance -ImageId "ami-1a2b3c4d" -KeyName "my-key-pair" -MaxCount 2 -InstanceType "t2.large" -SubnetId "subnet-1a2b3c4d" -TagSpecification $tagspec1,$tagspec2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RunInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 EC2-Classic 또는 기본 VPC에서 지정된 AMI의 단일 인스턴스를 시작합니다.**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -InstanceType m3.medium -KeyName my-key-pair -SecurityGroup my-security-group
```
**예제 2: 이 예제에서는 VPC에서 지정된 AMI의 단일 인스턴스를 시작합니다.**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -SubnetId subnet-12345678 -InstanceType t2.micro -KeyName my-key-pair -SecurityGroupId sg-12345678
```
**예제 3: EBS 볼륨 또는 인스턴스 저장소 볼륨을 추가하려면 블록 디바이스 매핑을 정의하고 명령에 추가합니다. 이 예제에서는 인스턴스 저장소 볼륨을 추가합니다.**  

```
$bdm = New-Object Amazon.EC2.Model.BlockDeviceMapping
$bdm.VirtualName = "ephemeral0"
$bdm.DeviceName = "/dev/sdf"

New-EC2Instance -ImageId ami-12345678 -BlockDeviceMapping $bdm ...
```
**예제 4: 현재 Windows AMI 중 하나를 지정하려면 Get-SSMLatestEC2Image를 사용하여 AMI ID를 가져옵니다. 이 예제에서는 Windows Server 2016용 최신 기본 AMI를 기반으로 인스턴스를 시작합니다.**  

```
$ami = (Get-SSMLatestEC2Image -Path 'ami-windows-latest' -ImageName 'WINDOWS*2016*English*Core*BASE').Value

New-EC2Instance -ImageId $ami ...
```
**예제 5: 지정된 전용 호스트 환경에서 인스턴스를 시작합니다.**  

```
New-EC2Instance -ImageId ami-1a2b3c4d -InstanceType m4.large -KeyName my-key-pair -SecurityGroupId sg-1a2b3c4d  -AvailabilityZone us-west-1a -Tenancy host -HostID h-1a2b3c4d5e6f1a2b3
```
**예제 6: 이 요청에서는 두 개의 인스턴스를 시작하고 키가 webserver이고 값이 production인 태그를 인스턴스에 적용합니다. 또한 이 요청은 생성된 볼륨(이 경우 각 인스턴스의 루트 볼륨)에 키가 cost-center이고 값이 cc123인 태그를 적용합니다.**  

```
$tag1 = @{ Key="webserver"; Value="production" }
$tag2 = @{ Key="cost-center"; Value="cc123" }

$tagspec1 = new-object Amazon.EC2.Model.TagSpecification
$tagspec1.ResourceType = "instance"
$tagspec1.Tags.Add($tag1)

$tagspec2 = new-object Amazon.EC2.Model.TagSpecification
$tagspec2.ResourceType = "volume"
$tagspec2.Tags.Add($tag2)

New-EC2Instance -ImageId "ami-1a2b3c4d" -KeyName "my-key-pair" -MaxCount 2 -InstanceType "t2.large" -SubnetId "subnet-1a2b3c4d" -TagSpecification $tagspec1,$tagspec2
```
**예제 7: 이 예제에서는 인스턴스를 실제로 생성하지 않고 DryRun 파라미터를 사용하여 EC2 인스턴스를 시작할 수 있는 권한을 검증합니다. 참고: 작업이 성공하면 예외가 발생하며 이는 정상적인 동작입니다.**  

```
New-EC2Instance -ImageId 'ami-12345678' -InstanceType 't2.micro' -KeyName 'my-key-pair' -Region 'us-west-2' -DryRun $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RunInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create(
        self,
        image_id: str,
        instance_type: str,
        key_pair_name: str,
        security_group_ids: Optional[List[str]] = None,
    ) -> List[Dict[str, Any]]:
        """
        Creates a new EC2 instance in the default VPC of the current account.

        The instance starts immediately after it is created.

        :param image_id: The ID of the Amazon Machine Image (AMI) to use for the instance.
        :param instance_type: The type of instance to create, such as 't2.micro'.
        :param key_pair_name: The name of the key pair to use for SSH access.
        :param security_group_ids: A list of security group IDs to associate with the instance.
                                   If not specified, the default security group of the VPC is used.
        :return: A list of dictionaries representing Boto3 Instance objects representing the newly created instances.
        """
        try:
            instance_params = {
                "ImageId": image_id,
                "InstanceType": instance_type,
                "KeyName": key_pair_name,
            }
            if security_group_ids is not None:
                instance_params["SecurityGroupIds"] = security_group_ids

            response = self.ec2_client.run_instances(
                **instance_params, MinCount=1, MaxCount=1
            )
            instance = response["Instances"][0]
            self.instances.append(instance)
            waiter = self.ec2_client.get_waiter("instance_running")
            waiter.wait(InstanceIds=[instance["InstanceId"]])
        except ClientError as err:
            params_str = "\n\t".join(
                f"{key}: {value}" for key, value in instance_params.items()
            )
            logger.error(
                f"Failed to complete instance creation request.\nRequest details:{params_str}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InstanceLimitExceeded":
                logger.error(
                    (
                        f"Insufficient capacity for instance type '{instance_type}'. "
                        "Terminate unused instances or contact AWS Support for a limit increase."
                    )
                )
            if error_code == "InsufficientInstanceCapacity":
                logger.error(
                    (
                        f"Insufficient capacity for instance type '{instance_type}'. "
                        "Select a different instance type or launch in a different availability zone."
                    )
                )
            raise
        return self.instances
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [RunInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/RunInstances)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn create_instance<'a>(
        &self,
        image_id: &'a str,
        instance_type: InstanceType,
        key_pair: &'a KeyPairInfo,
        security_groups: Vec<&'a SecurityGroup>,
    ) -> Result<String, EC2Error> {
        let run_instances = self
            .client
            .run_instances()
            .image_id(image_id)
            .instance_type(instance_type)
            .key_name(
                key_pair
                    .key_name()
                    .ok_or_else(|| EC2Error::new("Missing key name when launching instance"))?,
            )
            .set_security_group_ids(Some(
                security_groups
                    .iter()
                    .filter_map(|sg| sg.group_id.clone())
                    .collect(),
            ))
            .min_count(1)
            .max_count(1)
            .send()
            .await?;

        if run_instances.instances().is_empty() {
            return Err(EC2Error::new("Failed to create instance"));
        }

        let instance_id = run_instances.instances()[0].instance_id().unwrap();
        let response = self
            .client
            .create_tags()
            .resources(instance_id)
            .tags(
                Tag::builder()
                    .key("Name")
                    .value("From SDK Examples")
                    .build(),
            )
            .send()
            .await;

        match response {
            Ok(_) => tracing::info!("Created {instance_id} and applied tags."),
            Err(err) => {
                tracing::info!("Error applying tags to {instance_id}: {err:?}");
                return Err(err.into());
            }
        }

        tracing::info!("Instance is created.");

        Ok(instance_id.to_string())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [RunInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.run_instances)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    " Create tags for resource created during instance launch. "
    DATA lt_tagspecifications TYPE /aws1/cl_ec2tagspecification=>tt_tagspecificationlist.
    DATA ls_tagspecifications LIKE LINE OF lt_tagspecifications.
    ls_tagspecifications = NEW /aws1/cl_ec2tagspecification(
      iv_resourcetype = 'instance'
      it_tags = VALUE /aws1/cl_ec2tag=>tt_taglist(
        ( NEW /aws1/cl_ec2tag( iv_key = 'Name' iv_value = iv_tag_value ) )
      ) ).
    APPEND ls_tagspecifications TO lt_tagspecifications.

    TRY.
        " Create/launch Amazon Elastic Compute Cloud (Amazon EC2) instance. "
        oo_result = lo_ec2->runinstances(                           " oo_result is returned for testing purposes. "
          iv_imageid = iv_ami_id
          iv_instancetype = 't3.micro'
          iv_maxcount = 1
          iv_mincount = 1
          it_tagspecifications = lt_tagspecifications
          iv_subnetid = iv_subnet_id ).
        MESSAGE 'EC2 instance created.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [RunInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Create and return a new EC2 instance.
    /// 
    /// - Parameters:
    ///   - imageId: The image ID of the AMI to use when creating the instance.
    ///   - instanceType: The type of instance to create.
    ///   - keyPairName: The RSA key pair's name to use to secure the instance.
    ///   - securityGroups: The security group or groups to add the instance
    ///     to.
    ///
    /// - Returns: The EC2 instance as an `EC2ClientTypes.Instance` object.
    func runInstance(imageId: String, instanceType: EC2ClientTypes.InstanceType,
                        keyPairName: String, securityGroups: [String]?) async -> EC2ClientTypes.Instance? {
        do {
            let output = try await ec2Client.runInstances(
                input: RunInstancesInput(
                    imageId: imageId,
                    instanceType: instanceType,
                    keyName: keyPairName,
                    maxCount: 1,
                    minCount: 1,
                    securityGroupIds: securityGroups
                )
            )

            guard let instances = output.instances else {
                print("*** Unable to create the instance.")
                return nil
            }

            return instances[0]
        } catch {
            print("*** Error creating the instance: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [RunInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/runinstances(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `RunScheduledInstances` 사용
<a name="example_ec2_RunScheduledInstances_section"></a>

다음 코드 예시는 `RunScheduledInstances`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**정기 인스턴스 시작**  
이 예시에서는 VPC에서 지정된 정기 인스턴스를 시작합니다.  
명령:  

```
aws ec2 run-scheduled-instances --scheduled-instance-id sci-1234-1234-1234-1234-123456789012 --instance-count 1 --launch-specification file://launch-specification.json
```
Launch-specification.json:  

```
{
  "ImageId": "ami-12345678",
  "KeyName": "my-key-pair",
  "InstanceType": "c4.large",
  "NetworkInterfaces": [
    {
        "DeviceIndex": 0,
        "SubnetId": "subnet-12345678",
        "AssociatePublicIpAddress": true,
        "Groups": ["sg-12345678"]
    }
  ],
  "IamInstanceProfile": {
      "Name": "my-iam-role"
  }
}
```
출력:  

```
{
  "InstanceIdSet": [
      "i-1234567890abcdef0"
  ]
}
```
이 예시에서는 EC2-Classic에서 지정된 정기 인스턴스를 시작합니다.  
명령:  

```
aws ec2 run-scheduled-instances --scheduled-instance-id sci-1234-1234-1234-1234-123456789012 --instance-count 1 --launch-specification file://launch-specification.json
```
Launch-specification.json:  

```
{
  "ImageId": "ami-12345678",
  "KeyName": "my-key-pair",
  "SecurityGroupIds": ["sg-12345678"],
  "InstanceType": "c4.large",
  "Placement": {
    "AvailabilityZone": "us-west-2b"
  }
  "IamInstanceProfile": {
      "Name": "my-iam-role"
  }
}
```
출력:  

```
{
  "InstanceIdSet": [
      "i-1234567890abcdef0"
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [RunScheduledInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/run-scheduled-instances.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 일정이 예약된 지정된 인스턴스를 시작합니다.**  

```
New-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012 -InstanceCount 1 `
-IamInstanceProfile_Name my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType c4.large `
-LaunchSpecification_SubnetId subnet-12345678`
-LaunchSpecification_SecurityGroupId sg-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RunScheduledInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 일정이 예약된 지정된 인스턴스를 시작합니다.**  

```
New-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012 -InstanceCount 1 `
-IamInstanceProfile_Name my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType c4.large `
-LaunchSpecification_SubnetId subnet-12345678`
-LaunchSpecification_SecurityGroupId sg-12345678
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RunScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `StartInstances` 함께 사용
<a name="example_ec2_StartInstances_section"></a>

다음 코드 예시는 `StartInstances`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Start an EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the Amazon EC2 instance
    /// to start.</param>
    /// <returns>Async task.</returns>
    public async Task StartInstances(string ec2InstanceId)
    {
        try
        {
            var request = new StartInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId },
            };

            await _amazonEC2.StartInstancesAsync(request);

            Console.Write("Waiting for instance to start. ");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Running);
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to start. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while starting the instance.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEC2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [StartInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/StartInstances)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_start_instances
#
# This function starts one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i instance_id - The ID(s) of the instance(s) to start (comma-separated).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_start_instances() {
  local instance_ids
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_start_instances"
    echo "Starts one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_id - The ID(s) of the instance(s) to start (comma-separated)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) instance_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$instance_ids" ]]; then
    errecho "ERROR: You must provide one or more instance IDs with the -i parameter."
    usage
    return 1
  fi

  response=$(aws ec2 start-instances \
    --instance-ids "${instance_ids}") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports start-instances operation failed with $response."
    return 1
  }

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [StartInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/StartInstances)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Start an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::startInstance(const Aws::String &instanceId,
                                const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return startInstancesOutcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [StartInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/StartInstances)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**Amazon EC2 인스턴스를 시작하는 방법**  
다음 예제에서는 지정된 Amazon EBS 지원 인스턴스를 시작합니다.  
명령:  

```
aws ec2 start-instances --instance-ids i-1234567890abcdef0
```
출력:  

```
{
    "StartingInstances": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "CurrentState": {
                "Code": 0,
                "Name": "pending"
            },
            "PreviousState": {
                "Code": 80,
                "Name": "stopped"
            }
        }
    ]
}
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*에서 인스턴스 중지 및 시작을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [StartInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/start-instances.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Starts an Amazon EC2 instance asynchronously and waits until it is in the "running" state.
     *
     * @param instanceId the ID of the instance to start
     * @return a {@link CompletableFuture} that completes when the instance has been started and is in the "running" state, or exceptionally if an error occurs
     */
    public CompletableFuture<Void> startInstanceAsync(String instanceId) {
        StartInstancesRequest startRequest = StartInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        Ec2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()
            .client(getAsyncClient())
            .build();

        DescribeInstancesRequest describeRequest = DescribeInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        logger.info("Starting instance " + instanceId + " and waiting for it to run.");
        CompletableFuture<Void> resultFuture = new CompletableFuture<>();
        return getAsyncClient().startInstances(startRequest)
            .thenCompose(response ->
                ec2Waiter.waitUntilInstanceRunning(describeRequest)
            )
            .thenAccept(waiterResponse -> {
                logger.info("Successfully started instance " + instanceId);
                resultFuture.complete(null);
            })
            .exceptionally(throwable -> {
                resultFuture.completeExceptionally(new RuntimeException("Failed to start instance: " + throwable.getMessage(), throwable));
                return null;
            });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [StartInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/StartInstances)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, StartInstancesCommand } from "@aws-sdk/client-ec2";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

/**
 * Starts an Amazon EBS-backed instance that you've previously stopped.
 * @param {{ instanceIds }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new StartInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { StartingInstances } = await client.send(command);
    const instanceIdList = StartingInstances.map(
      (instance) => ` • ${instance.InstanceId}`,
    );
    console.log("Starting instances:");
    console.log(instanceIdList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [StartInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/StartInstancesCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun startInstanceSc(instanceId: String) {
    val request =
        StartInstancesRequest {
            instanceIds = listOf(instanceId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.startInstances(request)
        println("Waiting until instance $instanceId starts. This will take a few minutes.")
        ec2.waitUntilInstanceRunning {
            // suspend call
            instanceIds = listOf(instanceId)
        }
        println("Successfully started instance $instanceId")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [StartInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스를 시작합니다.**  

```
Start-EC2Instance -InstanceId i-12345678
```
**출력:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
**예제 2: 이 예제에서는 지정된 인스턴스를 시작합니다.**  

```
@("i-12345678", "i-76543210") | Start-EC2Instance
```
**예제 3: 이 예제에서는 현재 중지된 인스턴스 세트를 시작합니다. Get-EC2Instance에서 반환하는 인스턴스 객체는 Start-EC2Instance로 파이프됩니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
(Get-EC2Instance -Filter @{ Name="instance-state-name"; Values="stopped"}).Instances | Start-EC2Instance
```
**예제 4: PowerShell 버전 2에서 Filter 파라미터에 대해 필터를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "instance-state-name"
$filter.Values = "stopped"

(Get-EC2Instance -Filter $filter).Instances | Start-EC2Instance
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [StartInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스를 시작합니다.**  

```
Start-EC2Instance -InstanceId i-12345678
```
**출력:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
**예제 2: 이 예제에서는 지정된 인스턴스를 시작합니다.**  

```
@("i-12345678", "i-76543210") | Start-EC2Instance
```
**예제 3: 이 예제에서는 현재 중지된 인스턴스 세트를 시작합니다. Get-EC2Instance에서 반환하는 인스턴스 객체는 Start-EC2Instance로 파이프됩니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
(Get-EC2Instance -Filter @{ Name="instance-state-name"; Values="stopped"}).Instances | Start-EC2Instance
```
**예제 4: PowerShell 버전 2에서 Filter 파라미터에 대해 필터를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "instance-state-name"
$filter.Values = "stopped"

(Get-EC2Instance -Filter $filter).Instances | Start-EC2Instance
```
**예제 5: 이 예제에서는 인스턴스를 실제로 시작하지 않고 DryRun 파라미터를 사용하여 EC2 인스턴스를 시작할 수 있는 권한을 검증합니다. 참고: 작업이 성공하면 예외가 발생하며 이는 정상적인 동작입니다.**  

```
Start-EC2Instance -InstanceId 'i-0abcdef123456' -Region 'us-west-1' -DryRun $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [StartInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def start(self) -> Optional[Dict[str, Any]]:
        """
        Starts instances and waits for them to be in a running state.

        :return: The response to the start request.
        """
        if not self.instances:
            logger.info("No instances to start.")
            return None

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        try:
            start_response = self.ec2_client.start_instances(InstanceIds=instance_ids)
            waiter = self.ec2_client.get_waiter("instance_running")
            waiter.wait(InstanceIds=instance_ids)
            return start_response
        except ClientError as err:
            logger.error(
                f"Failed to start instance(s): {','.join(map(str, instance_ids))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "IncorrectInstanceState":
                logger.error(
                    "Couldn't start instance(s) because they are in an incorrect state. "
                    "Ensure the instances are in a stopped state before starting them."
                )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [StartInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/StartInstances)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'aws-sdk-ec2'

# Attempts to start an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Prerequisites:
#
# - The Amazon EC2 instance.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param instance_id [String] The ID of the instance.
# @return [Boolean] true if the instance was started; otherwise, false.
# @example
#   exit 1 unless instance_started?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'i-123abc'
#   )
def instance_started?(ec2_client, instance_id)
  response = ec2_client.describe_instance_status(instance_ids: [instance_id])

  if response.instance_statuses.count.positive?
    state = response.instance_statuses[0].instance_state.name
    case state
    when 'pending'
      puts 'Error starting instance: the instance is pending. Try again later.'
      return false
    when 'running'
      puts 'The instance is already running.'
      return true
    when 'terminated'
      puts 'Error starting instance: ' \
        'the instance is terminated, so you cannot start it.'
      return false
    end
  end

  ec2_client.start_instances(instance_ids: [instance_id])
  ec2_client.wait_until(:instance_running, instance_ids: [instance_id])
  puts 'Instance started.'
  true
rescue StandardError => e
  puts "Error starting instance: #{e.message}"
  false
end

# Example usage:
def run_me
  instance_id = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-start-instance-i-123abc.rb ' \
      'INSTANCE_ID REGION '
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-start-instance-i-123abc.rb ' \
      'i-123abc us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    instance_id = 'i-123abc'
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    instance_id = ARGV[0]
    region = ARGV[1]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts "Attempting to start instance '#{instance_id}' " \
    '(this might take a few minutes)...'
  return if instance_started?(ec2_client, instance_id)

  puts 'Could not start instance.'
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [StartInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/StartInstances)를 참조하십시오.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
인스턴스 ID로 EC2 인스턴스를 시작합니다.  

```
    pub async fn start_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Starting instance {instance_id}");

        self.client
            .start_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        tracing::info!("Started instance.");

        Ok(())
    }
```
Waiters API를 사용하여 인스턴스가 준비 및 정상 상태가 될 때까지 기다립니다. Waiters API를 사용하려면 rust 파일에 'use aws\$1sdk\$1ec2::client::Waiters'가 필요합니다.  

```
    /// Wait for an instance to be ready and status ok (default wait 60 seconds)
    pub async fn wait_for_instance_ready(
        &self,
        instance_id: &str,
        duration: Option<Duration>,
    ) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_status_ok()
            .instance_ids(instance_id)
            .wait(duration.unwrap_or(Duration::from_secs(60)))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to start.",
                    exceeded.max_wait().as_secs()
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [StartInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.start_instances)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist.
    APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids.

    "Perform dry run"
    TRY.
        " DryRun is set to true. This checks for the required permissions to start the instance without actually making the request. "
        lo_ec2->startinstances(
          it_instanceids = lt_instance_ids
          iv_dryrun = abap_true ).
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        " If the error code returned is `DryRunOperation`, then you have the required permissions to start this instance. "
        IF lo_exception->av_err_code = 'DryRunOperation'.
          MESSAGE 'Dry run to start instance completed.' TYPE 'I'.
          " DryRun is set to false to start instance. "
          oo_result = lo_ec2->startinstances(           " oo_result is returned for testing purposes. "
            it_instanceids = lt_instance_ids
            iv_dryrun = abap_false ).
          MESSAGE 'Successfully started the EC2 instance.' TYPE 'I'.
          " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to start this instance. "
        ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'.
          MESSAGE 'Dry run to start instance failed. User does not have permissions to start the instance.' TYPE 'E'.
        ELSE.
          DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
          MESSAGE lv_error TYPE 'E'.
        ENDIF.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [StartInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Start the specified instance.
    /// 
    /// - Parameters:
    ///   - instanceId: The ID of the instance to start.
    ///   - waitUntilStarted: If `true`, execution waits until the instance
    ///     has started. Otherwise, execution continues and the instance starts
    ///     asynchronously.
    ///
    /// - Returns: `true` if the image is successfully started (or is left to
    ///   start asynchronously). `false` if the instance doesn't start.
    func startInstance(instanceId: String, waitUntilStarted: Bool = false) async -> Bool {
        let instanceList = [instanceId]

        do {
            _ = try await ec2Client.startInstances(
                input: StartInstancesInput(
                    instanceIds: instanceList
                )
            )

            if waitUntilStarted {
                print("Waiting for the instance to start...")

                let waitOptions = WaiterOptions(maxWaitTime: 60.0)
                let output = try await ec2Client.waitUntilInstanceRunning(
                    options: waitOptions,
                    input: DescribeInstancesInput(
                        instanceIds: instanceList
                    )
                )
                switch output.result {
                case .success:
                    return true
                case .failure:
                    return false
                }
            } else {
                return true
            }
        } catch {
            print("*** Unable to start the instance: \(error.localizedDescription)")
            return false
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [StartInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/startinstances(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `StopInstances` 함께 사용
<a name="example_ec2_StopInstances_section"></a>

다음 코드 예시는 `StopInstances`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Stop an EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the EC2 instance to
    /// stop.</param>
    /// <returns>Async task.</returns>
    public async Task StopInstances(string ec2InstanceId)
    {
        try
        {
            var request = new StopInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId },
            };

            await _amazonEC2.StopInstancesAsync(request);
            Console.Write("Waiting for the instance to stop.");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Stopped);

            Console.WriteLine("\nThe instance has stopped.");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to stop. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while stopping the instance.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEC2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [StopInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/StopInstances)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_stop_instances
#
# This function stops one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i instance_id - The ID(s) of the instance(s) to stop (comma-separated).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_stop_instances() {
  local instance_ids
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_stop_instances"
    echo "Stops one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_id - The ID(s) of the instance(s) to stop (comma-separated)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) instance_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$instance_ids" ]]; then
    errecho "ERROR: You must provide one or more instance IDs with the -i parameter."
    usage
    return 1
  fi

  response=$(aws ec2 stop-instances \
    --instance-ids "${instance_ids}") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports stop-instances operation failed with $response."
    return 1
  }

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [StopInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/StopInstances)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Stop an EC2 instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::stopInstance(const Aws::String &instanceId,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return outcome.IsSuccess();
}

void PrintUsage() {
    std::cout << "Usage: run_start_stop_instance <instance_id> <start|stop>" <<
              std::endl;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [StopInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/StopInstances)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: Amazon EC2 인스턴스를 중지하는 방법**  
다음 `stop-instances` 예제에서는 Amazon EBS 지원 인스턴스를 중지합니다.  

```
aws ec2 stop-instances \
    --instance-ids i-1234567890abcdef0
```
출력:  

```
{
    "StoppingInstances": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "CurrentState": {
                "Code": 64,
                "Name": "stopping"
            },
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*에서 [인스턴스 중지 및 시작](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html)을 참조하세요.  
**예제 2: Amazon EC2 인스턴스에서 최대 절전 모드를 적용하는 방법**  
다음 `stop-instances` 예제에서는 인스턴스에서 최대 절전 모드가 활성화되고 인스턴스가 최대 절전 모드 사전 조건을 충족하는 경우 Amazon EBS 지원 인스턴스를 최대 절전 모드로 전환합니다. 인스턴스가 최대 절전 모드로 전환된 후에 인스턴스가 중지됩니다.  

```
aws ec2 stop-instances \
    --instance-ids i-1234567890abcdef0 \
    --hibernate
```
출력:  

```
{
    "StoppingInstances": [
        {
            "CurrentState": {
                "Code": 64,
                "Name": "stopping"
            },
            "InstanceId": "i-1234567890abcdef0",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```
자세한 내용은 *Amazon Elastic Compute Cloud 사용 설명서*에서 [온디맨드 Linux 인스턴스를 최대 절전 모드로 전환](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [StopInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/stop-instances.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Stops the EC2 instance with the specified ID asynchronously and waits for the instance to stop.
     *
     * @param instanceId the ID of the EC2 instance to stop
     * @return a {@link CompletableFuture} that completes when the instance has been stopped, or exceptionally if an error occurs
     */
    public CompletableFuture<Void> stopInstanceAsync(String instanceId) {
        StopInstancesRequest stopRequest = StopInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        DescribeInstancesRequest describeRequest = DescribeInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        Ec2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()
            .client(getAsyncClient())
            .build();

        CompletableFuture<Void> resultFuture = new CompletableFuture<>();
        logger.info("Stopping instance " + instanceId + " and waiting for it to stop.");
        getAsyncClient().stopInstances(stopRequest)
            .thenCompose(response -> {
                if (response.stoppingInstances().isEmpty()) {
                    return CompletableFuture.failedFuture(new RuntimeException("No instances were stopped. Please check the instance ID: " + instanceId));
                }
                return ec2Waiter.waitUntilInstanceStopped(describeRequest);
            })
            .thenAccept(waiterResponse -> {
                logger.info("Successfully stopped instance " + instanceId);
                resultFuture.complete(null);
            })
            .exceptionally(throwable -> {
                logger.error("Failed to stop instance " + instanceId + ": " + throwable.getMessage(), throwable);
                resultFuture.completeExceptionally(new RuntimeException("Failed to stop instance: " + throwable.getMessage(), throwable));
                return null;
            });

        return resultFuture;
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [StopInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/StopInstances)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, StopInstancesCommand } from "@aws-sdk/client-ec2";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

/**
 * Stop one or more EC2 instances.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new StopInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { StoppingInstances } = await client.send(command);
    const instanceIdList = StoppingInstances.map(
      (instance) => ` • ${instance.InstanceId}`,
    );
    console.log("Stopping instances:");
    console.log(instanceIdList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [StopInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/StopInstancesCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun stopInstanceSc(instanceId: String) {
    val request =
        StopInstancesRequest {
            instanceIds = listOf(instanceId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.stopInstances(request)
        println("Waiting until instance $instanceId stops. This will take a few minutes.")
        ec2.waitUntilInstanceStopped {
            // suspend call
            instanceIds = listOf(instanceId)
        }
        println("Successfully stopped instance $instanceId")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [StopInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스를 중지합니다.**  

```
Stop-EC2Instance -InstanceId i-12345678
```
**출력:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [StopInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스를 중지합니다.**  

```
Stop-EC2Instance -InstanceId i-12345678
```
**출력:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [StopInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def stop(self) -> Optional[Dict[str, Any]]:
        """
        Stops instances and waits for them to be in a stopped state.

        :return: The response to the stop request, or None if there are no instances to stop.
        """
        if not self.instances:
            logger.info("No instances to stop.")
            return None

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        try:
            # Attempt to stop the instances
            stop_response = self.ec2_client.stop_instances(InstanceIds=instance_ids)
            waiter = self.ec2_client.get_waiter("instance_stopped")
            waiter.wait(InstanceIds=instance_ids)
        except ClientError as err:
            logger.error(
                f"Failed to stop instance(s): {','.join(map(str, instance_ids))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "IncorrectInstanceState":
                logger.error(
                    "Couldn't stop instance(s) because they are in an incorrect state. "
                    "Ensure the instances are in a running state before stopping them."
                )
            raise
        return stop_response
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [StopInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/StopInstances)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'aws-sdk-ec2'

# Prerequisites:
#
# - The Amazon EC2 instance.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param instance_id [String] The ID of the instance.
# @return [Boolean] true if the instance was stopped; otherwise, false.
# @example
#   exit 1 unless instance_stopped?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'i-123abc'
#   )
def instance_stopped?(ec2_client, instance_id)
  response = ec2_client.describe_instance_status(instance_ids: [instance_id])

  if response.instance_statuses.count.positive?
    state = response.instance_statuses[0].instance_state.name
    case state
    when 'stopping'
      puts 'The instance is already stopping.'
      return true
    when 'stopped'
      puts 'The instance is already stopped.'
      return true
    when 'terminated'
      puts 'Error stopping instance: ' \
        'the instance is terminated, so you cannot stop it.'
      return false
    end
  end

  ec2_client.stop_instances(instance_ids: [instance_id])
  ec2_client.wait_until(:instance_stopped, instance_ids: [instance_id])
  puts 'Instance stopped.'
  true
rescue StandardError => e
  puts "Error stopping instance: #{e.message}"
  false
end

# Example usage:
def run_me
  instance_id = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-stop-instance-i-123abc.rb ' \
      'INSTANCE_ID REGION '
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-start-instance-i-123abc.rb ' \
      'i-123abc us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    instance_id = 'i-123abc'
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    instance_id = ARGV[0]
    region = ARGV[1]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts "Attempting to stop instance '#{instance_id}' " \
    '(this might take a few minutes)...'
  return if instance_stopped?(ec2_client, instance_id)

  puts 'Could not stop instance.'
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [StopInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/StopInstances)를 참조하십시오.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn stop_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Stopping instance {instance_id}");

        self.client
            .stop_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        self.wait_for_instance_stopped(instance_id, None).await?;

        tracing::info!("Stopped instance.");

        Ok(())
    }
```
Waiters API를 사용하여 인스턴스가 중지 상태가 될 때까지 기다립니다. Waiters API를 사용하려면 rust 파일에 'use aws\$1sdk\$1ec2::client::Waiters'가 필요합니다.  

```
    pub async fn stop_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Stopping instance {instance_id}");

        self.client
            .stop_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        self.wait_for_instance_stopped(instance_id, None).await?;

        tracing::info!("Stopped instance.");

        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [StopInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.stop_instances)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist.
    APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids.

    "Perform dry run"
    TRY.
        " DryRun is set to true. This checks for the required permissions to stop the instance without actually making the request. "
        lo_ec2->stopinstances(
          it_instanceids = lt_instance_ids
          iv_dryrun = abap_true ).
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        " If the error code returned is `DryRunOperation`, then you have the required permissions to stop this instance. "
        IF lo_exception->av_err_code = 'DryRunOperation'.
          MESSAGE 'Dry run to stop instance completed.' TYPE 'I'.
          " DryRun is set to false to stop instance. "
          oo_result = lo_ec2->stopinstances(           " oo_result is returned for testing purposes. "
            it_instanceids = lt_instance_ids
            iv_dryrun = abap_false ).
          MESSAGE 'Successfully stopped the EC2 instance.' TYPE 'I'.
          " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to stop this instance. "
        ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'.
          MESSAGE 'Dry run to stop instance failed. User does not have permissions to stop the instance.' TYPE 'E'.
        ELSE.
          DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
          MESSAGE lv_error TYPE 'E'.
        ENDIF.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [StopInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Stop the specified instance.
    /// 
    /// - Parameters:
    ///   - instanceId: The ID of the instance to stop.
    ///   - waitUntilStopped: If `true`, execution waits until the instance
    ///     has stopped. Otherwise, execution continues and the instance stops
    ///     asynchronously.
    ///
    /// - Returns: `true` if the image is successfully stopped (or is left to
    ///   stop asynchronously). `false` if the instance doesn't stop.
    func stopInstance(instanceId: String, waitUntilStopped: Bool = false) async -> Bool {
        let instanceList = [instanceId]

        do {
            _ = try await ec2Client.stopInstances(
                input: StopInstancesInput(
                    instanceIds: instanceList
                )
            )

            if waitUntilStopped {
                print("Waiting for the instance to stop. Please be patient!")

                let waitOptions = WaiterOptions(maxWaitTime: 600)
                let output = try await ec2Client.waitUntilInstanceStopped(
                    options: waitOptions,
                    input: DescribeInstancesInput(
                        instanceIds: instanceList
                    )
                )

                switch output.result {
                case .success:
                    return true
                case .failure:
                    return false
                }
            } else {
                return true
            }
        } catch {
            print("*** Unable to stop the instance: \(error.localizedDescription)")
            return false
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [StopInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/stopinstances(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `TerminateInstances` 함께 사용
<a name="example_ec2_TerminateInstances_section"></a>

다음 코드 예시는 `TerminateInstances`의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 
+  [Amazon VPC 시작하기](example_vpc_GettingStartedCLI_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /// <summary>
    /// Terminate an EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the EC2 instance
    /// to terminate.</param>
    /// <returns>Async task.</returns>
    public async Task<List<InstanceStateChange>> TerminateInstances(string ec2InstanceId)
    {
        try
        {
            var request = new TerminateInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId }
            };

            var response = await _amazonEC2.TerminateInstancesAsync(request);
            Console.Write("Waiting for the instance to terminate.");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Terminated);

            Console.WriteLine($"\nThe instance {ec2InstanceId} has been terminated.");
            return response.TerminatingInstances;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to terminate. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while terminating the instance.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEC2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [TerminateInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/TerminateInstances)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function ec2_terminate_instances
#
# This function terminates one or more Amazon Elastic Compute Cloud (Amazon EC2)
# instances using the AWS CLI.
#
# Parameters:
#       -i instance_ids - A space-separated list of instance IDs.
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_terminate_instances() {
  local instance_ids response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_terminate_instances"
    echo "Terminates one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_ids - A space-separated list of instance IDs."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) instance_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Check if instance ID is provided
  if [[ -z "${instance_ids}" ]]; then
    echo "Error: Missing required instance IDs parameter."
    usage
    return 1
  fi

  # shellcheck disable=SC2086
  response=$(aws ec2 terminate-instances \
    "--instance-ids" $instance_ids \
    --query 'TerminatingInstances[*].[InstanceId,CurrentState.Name]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports terminate-instances operation failed.$response"
    return 1
  }

  return 0
}
```
이 예제에 사용된 유틸리티 함수  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [TerminateInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/TerminateInstances)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Terminate an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::terminateInstances(const Aws::String &instanceID,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::TerminateInstancesRequest request;
    request.SetInstanceIds({instanceID});

    Aws::EC2::Model::TerminateInstancesOutcome outcome =
            ec2Client.TerminateInstances(request);
    if (outcome.IsSuccess()) {
        std::cout << "Ec2 instance '" << instanceID <<
                  "' was terminated." << std::endl;
    } else {
        std::cerr << "Failed to terminate ec2 instance " << instanceID <<
                  ", " <<
                  outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [TerminateInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/TerminateInstances)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**Amazon EC2 인스턴스를 종료하는 방법**  
이 예제에서는 지정된 인스턴스를 종료합니다.  
명령:  

```
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0
```
출력:  

```
{
    "TerminatingInstances": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```
자세한 내용은 *AWS Command Line Interface 사용 설명서*에서 Amazon EC2 인스턴스 사용을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [TerminateInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/terminate-instances.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Terminates an EC2 instance asynchronously and waits for it to reach the terminated state.
     *
     * @param instanceId the ID of the EC2 instance to terminate
     * @return a {@link CompletableFuture} that completes when the instance has been terminated
     * @throws RuntimeException if there is no response from the AWS SDK or if there is a failure during the termination process
     */
    public CompletableFuture<Object> terminateEC2Async(String instanceId) {
        TerminateInstancesRequest terminateRequest = TerminateInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        CompletableFuture<TerminateInstancesResponse> responseFuture = getAsyncClient().terminateInstances(terminateRequest);
        return responseFuture.thenCompose(terminateResponse -> {
            if (terminateResponse == null) {
                throw new RuntimeException("No response received for terminating instance " + instanceId);
            }
            System.out.println("Going to terminate an EC2 instance and use a waiter to wait for it to be in terminated state");
            return getAsyncClient().waiter()
                .waitUntilInstanceTerminated(r -> r.instanceIds(instanceId))
                .thenApply(waiterResponse -> null);
        }).exceptionally(throwable -> {
            // Handle any exceptions that occurred during the async call
            throw new RuntimeException("Failed to terminate EC2 instance: " + throwable.getMessage(), throwable);
        });
    }
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [TerminateInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/TerminateInstances)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, TerminateInstancesCommand } from "@aws-sdk/client-ec2";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

/**
 * Terminate one or more EC2 instances.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new TerminateInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { TerminatingInstances } = await client.send(command);
    const instanceList = TerminatingInstances.map(
      (instance) => ` • ${instance.InstanceId}`,
    );
    console.log("Terminating instances:");
    console.log(instanceList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [TerminateInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/TerminateInstancesCommand)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun terminateEC2(instanceID: String) {
    val request =
        TerminateInstancesRequest {
            instanceIds = listOf(instanceID)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.terminateInstances(request)
        response.terminatingInstances?.forEach { instance ->
            println("The ID of the terminated instance is ${instance.instanceId}")
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [TerminateInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스를 종료합니다(인스턴스가 실행 중이거나 'stopped' 상태일 수 있음). 계속하기 전에 cmdlet에 확인 프롬프트가 표시됩니다. 프롬프트를 차단하려면 -Force 스위치를 사용하세요.**  

```
Remove-EC2Instance -InstanceId i-12345678
```
**출력:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [TerminateInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스를 종료합니다(인스턴스가 실행 중이거나 'stopped' 상태일 수 있음). 계속하기 전에 cmdlet에 확인 프롬프트가 표시됩니다. 프롬프트를 차단하려면 -Force 스위치를 사용하세요.**  

```
Remove-EC2Instance -InstanceId i-12345678
```
**출력:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [TerminateInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def terminate(self) -> None:
        """
        Terminates instances and waits for them to reach the terminated state.
        """
        if not self.instances:
            logger.info("No instances to terminate.")
            return

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        try:
            self.ec2_client.terminate_instances(InstanceIds=instance_ids)
            waiter = self.ec2_client.get_waiter("instance_terminated")
            waiter.wait(InstanceIds=instance_ids)
            self.instances.clear()
            for instance_id in instance_ids:
                print(f"• Instance ID: {instance_id}\n" f"• Action: Terminated")

        except ClientError as err:
            logger.error(
                f"Failed instance termination details:\n\t{str(self.instances)}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                logger.error(
                    "One or more instance IDs do not exist. "
                    "Please verify the instance IDs and try again."
                )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [TerminateInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/TerminateInstances)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'aws-sdk-ec2'

# Prerequisites:
#
# - The Amazon EC2 instance.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param instance_id [String] The ID of the instance.
# @return [Boolean] true if the instance was terminated; otherwise, false.
# @example
#   exit 1 unless instance_terminated?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'i-123abc'
#   )
def instance_terminated?(ec2_client, instance_id)
  response = ec2_client.describe_instance_status(instance_ids: [instance_id])

  if response.instance_statuses.count.positive? &&
     response.instance_statuses[0].instance_state.name == 'terminated'

    puts 'The instance is already terminated.'
    return true
  end

  ec2_client.terminate_instances(instance_ids: [instance_id])
  ec2_client.wait_until(:instance_terminated, instance_ids: [instance_id])
  puts 'Instance terminated.'
  true
rescue StandardError => e
  puts "Error terminating instance: #{e.message}"
  false
end

# Example usage:
def run_me
  instance_id = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-terminate-instance-i-123abc.rb ' \
      'INSTANCE_ID REGION '
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-terminate-instance-i-123abc.rb ' \
      'i-123abc us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    instance_id = 'i-123abc'
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    instance_id = ARGV[0]
    region = ARGV[1]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts "Attempting to terminate instance '#{instance_id}' " \
    '(this might take a few minutes)...'
  return if instance_terminated?(ec2_client, instance_id)

  puts 'Could not terminate instance.'
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [TerminateInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/TerminateInstances)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn delete_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Deleting instance with id {instance_id}");
        self.stop_instance(instance_id).await?;
        self.client
            .terminate_instances()
            .instance_ids(instance_id)
            .send()
            .await?;
        self.wait_for_instance_terminated(instance_id).await?;
        tracing::info!("Terminated instance with id {instance_id}");
        Ok(())
    }
```
Waiters API를 사용하여 인스턴스가 종료 상태가 될 때까지 기다립니다. Waiters API를 사용하려면 rust 파일에 'use aws\$1sdk\$1ec2::client::Waiters'가 필요합니다.  

```
    async fn wait_for_instance_terminated(&self, instance_id: &str) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_terminated()
            .instance_ids(instance_id)
            .wait(Duration::from_secs(60))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to terminate.",
                    exceeded.max_wait().as_secs(),
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [TerminateInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.terminate_instances)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSEC2

    /// Terminate the specified instance.
    ///
    /// - Parameters:
    ///   - instanceId: The instance to terminate.
    ///   - waitUntilTerminated: Whether or not to wait until the instance is
    ///     terminated before returning.
    /// 
    /// - Returns: `true` if terminated successfully. `false` if not or if an
    ///   error occurs.
    func terminateInstance(instanceId: String, waitUntilTerminated: Bool = false) async -> Bool {
        let instanceList = [instanceId]

        do {
            _ = try await ec2Client.terminateInstances(
                input: TerminateInstancesInput(
                    instanceIds: instanceList
                )
            )

            if waitUntilTerminated {
                print("Waiting for the instance to terminate...")

                let waitOptions = WaiterOptions(maxWaitTime: 600.0)
                let output = try await ec2Client.waitUntilInstanceTerminated(
                    options: waitOptions,
                    input: DescribeInstancesInput(
                        instanceIds: instanceList
                    )
                )

                switch output.result {
                case .success:
                    return true
                case .failure:
                    return false
                }
            } else {
                return true
            }
        } catch {
            print("*** Unable to terminate the instance: \(error.localizedDescription)")
            return false
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [TerminateInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/terminateinstances(input:))를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `UnassignPrivateIpAddresses` 사용
<a name="example_ec2_UnassignPrivateIpAddresses_section"></a>

다음 코드 예시는 `UnassignPrivateIpAddresses`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**네트워크 인터페이스에서 보조 프라이빗 IP 주소 할당 해제**  
이 예시에서는 지정된 네트워크 인터페이스에서 지정된 프라이빗 IP 주소의 할당을 해제합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.  
명령:  

```
aws ec2 unassign-private-ip-addresses --network-interface-id eni-e5aa89a3 --private-ip-addresses 10.0.0.82
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [UnassignPrivateIpAddresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/unassign-private-ip-addresses.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스에서 지정된 프라이빗 IP 주소의 할당을 해제합니다.**  

```
Unregister-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UnassignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 네트워크 인터페이스에서 지정된 프라이빗 IP 주소의 할당을 해제합니다.**  

```
Unregister-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UnassignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# AWS SDK 또는 CLI와 `UnmonitorInstances` 함께 사용
<a name="example_ec2_UnmonitorInstances_section"></a>

다음 코드 예시는 `UnmonitorInstances`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](example_ec2_Scenario_GetStartedInstances_section.md) 

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Disable monitoring for an EC2 instance.
/*!
  \param instanceId: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::disableMonitoring(const Aws::String &instanceId,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    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;
    }

    return unmonitorInstancesOutcome.IsSuccess();
}
```
+  API 세부 정보는  *AWS SDK for C\$1\$1  API 참조*의 [UnmonitorInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/UnmonitorInstances)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**인스턴스에 대한 세부 모니터링을 비활성화하는 방법**  
이 예제 명령은 지정된 인스턴스에 대한 세부 모니터링을 비활성화합니다.  
명령:  

```
aws ec2 unmonitor-instances --instance-ids i-1234567890abcdef0
```
출력:  

```
{
  "InstanceMonitorings": [
      {
          "InstanceId": "i-1234567890abcdef0",
          "Monitoring": {
              "State": "disabling"
          }
      }
  ]
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*에서 [UnmonitorInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/unmonitor-instances.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { EC2Client, UnmonitorInstancesCommand } from "@aws-sdk/client-ec2";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

/**
 * Turn off detailed monitoring for the selected instance.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new UnmonitorInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { InstanceMonitorings } = await client.send(command);
    const instanceMonitoringsList = InstanceMonitorings.map(
      (im) =>
        ` • Detailed monitoring state for ${im.InstanceId} is ${im.Monitoring.State}.`,
    );
    console.log("Monitoring status:");
    console.log(instanceMonitoringsList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는  *AWS SDK for JavaScript  API 참조*의 [UnmonitorInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/UnmonitorInstancesCommand)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 인스턴스에 대한 세부 모니터링을 비활성화합니다.**  

```
Stop-EC2InstanceMonitoring -InstanceId i-12345678
```
**출력:**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UnmonitorInstances](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 인스턴스에 대한 세부 모니터링을 비활성화합니다.**  

```
Stop-EC2InstanceMonitoring -InstanceId i-12345678
```
**출력:**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UnmonitorInstances](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

# CLI로 `UpdateSecurityGroupRuleDescriptionsIngress` 사용
<a name="example_ec2_UpdateSecurityGroupRuleDescriptionsIngress_section"></a>

다음 코드 예시는 `UpdateSecurityGroupRuleDescriptionsIngress`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**예시 1: 인바운드 보안 그룹 규칙에 대한 설명을 CIDR 소스로 업데이트**  
다음 `update-security-group-rule-descriptions-ingress` 예시에서는 지정된 포트 및 IPv4 주소 범위에 대한 보안 그룹 규칙에 대한 설명을 업데이트합니다. '`SSH access from ABC office`' 설명은 규칙에 대한 기존 설명을 대체합니다.  

```
aws ec2 update-security-group-rule-descriptions-ingress \
    --group-id sg-02f0d35a850ba727f \
    --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges='[{CidrIp=203.0.113.0/16,Description="SSH access from corpnet"}]'
```
출력:  

```
{
    "Return": true
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [보안 그룹 규칙](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html#security-group-rules)을 참조하세요.  
**예시 2: 인바운드 보안 그룹 규칙에 대한 설명을 접두사 목록 소스로 업데이트**  
다음 `update-security-group-rule-descriptions-ingress` 예시에서는 지정된 포트 및 접두사 목록에 대한 보안 그룹 규칙의 설명을 업데이트합니다. '`SSH access from ABC office`' 설명은 규칙에 대한 기존 설명을 대체합니다.  

```
aws ec2 update-security-group-rule-descriptions-ingress \
    --group-id sg-02f0d35a850ba727f \
    --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,PrefixListIds='[{PrefixListId=pl-12345678,Description="SSH access from corpnet"}]'
```
출력:  

```
{
    "Return": true
}
```
자세한 내용은 *Amazon EC2 사용 설명서*의 [보안 그룹 규칙](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html#security-group-rules)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [UpdateSecurityGroupRuleDescriptionsIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/update-security-group-rule-descriptions-ingress.html) 섹션을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 기존 수신(인바운드) 보안 그룹 규칙에 대한 설명을 업데이트합니다.**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithUpdatedDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
  "Description" = "Updated rule description"
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithUpdatedDescription
```
**예제 2: 요청에서 파라미터를 생략하여 기존 수신(인바운드) 보안 그룹 규칙에 대한 설명을 제거합니다.**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithoutDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithoutDescription
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UpdateSecurityGroupRuleDescriptionsIngress](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 기존 수신(인바운드) 보안 그룹 규칙에 대한 설명을 업데이트합니다.**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithUpdatedDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
  "Description" = "Updated rule description"
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithUpdatedDescription
```
**예제 2: 요청에서 파라미터를 생략하여 기존 수신(인바운드) 보안 그룹 규칙에 대한 설명을 제거합니다.**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithoutDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithoutDescription
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateSecurityGroupRuleDescriptionsIngress](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

 AWS SDK 개발자 안내서 및 코드 예제의 전체 목록은 섹션을 참조하세요[AWS SDK를 사용하여 Amazon EC2 리소스 생성](sdk-general-information-section.md). 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.