

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 购买预留实例 (Amazon 软件开发工具包)
<a name="ri-sdk"></a>

 Amazon 软件开发工具包（Android 和 iOS 软件开发工具包除外）支持《[亚马逊 OpenSearch 服务 API 参考](https://docs.amazonaws.cn/opensearch-service/latest/APIReference/Welcome.html)》中定义的所有操作，包括以下操作：
+ `DescribeReservedInstanceOfferings`
+ `PurchaseReservedInstanceOffering`
+ `DescribeReservedInstances`

此示例脚本使用中的[OpenSearchService](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/opensearch.html)低级 Python 客户端购买预留实例。 适用于 Python (Boto3) 的 Amazon SDK 您必须为 `instance_type` 提供一个值。

```
import boto3
from botocore.config import Config

# Build the client using the default credential configuration.
# You can use the CLI and run 'aws configure' to set access key, secret
# key, and default region.

my_config = Config(
    # Optionally lets you specify a region other than your default.
    region_name='us-east-1'
)

client = boto3.client('opensearch', config=my_config)

instance_type = '' # e.g. m4.2xlarge.search


def describe_RI_offerings(client):
    """Gets the Reserved Instance offerings for this account"""

    response = client.describe_reserved_instance_offerings()
    offerings = (response['ReservedInstanceOfferings'])
    return offerings


def check_instance(offering):
    """Returns True if instance type is the one you specified above"""

    if offering['InstanceType'] == instance_type:
        return True

    return False


def get_instance_id():
    """Iterates through the available offerings to find the ID of the one you specified"""

    instance_type_iterator = filter(
        check_instance, describe_RI_offerings(client))
    offering = list(instance_type_iterator)
    id = offering[0]['ReservedInstanceOfferingId']
    return id


def purchase_RI_offering(client):
    """Purchase Reserved Instances"""

    response = client.purchase_reserved_instance_offering(
        ReservedInstanceOfferingId = get_instance_id(),
        ReservationName = 'my-reservation',
        InstanceCount = 1
    )
    print('Purchased reserved instance offering of type ' + instance_type)
    print(response)


def main():
    """Purchase Reserved Instances"""
    purchase_RI_offering(client)
```

有关安装和使用软件开发 Amazon 工具包的更多信息，请参阅[Amazon 软件开发套件](https://www.amazonaws.cn/code)。