Amazon EC2 On-Demand实例是一种灵活的付费方式,用户只支付所使用的容量。On-Demand Capacity Reservation实例则是Amazon EC2 On Demand实例的一种变体,它允许用户在需要时预留一定的容量以保证可用性。以下是一个使用On-Demand Capacity Reservation实例创建EC2实例的示例代码:
import boto3
# 创建EC2客户端
ec2 = boto3.client('ec2')
# 获取capacity reservation标识符
reservation_id = 'cr-xxxxxx'
# 创建EC2实例
response = ec2.run_instances(
ImageId='ami-0c55b159cbfafe1f0',
InstanceType='t2.micro',
MinCount=1,
MaxCount=1,
CapacityReservationSpecification={
'CapacityReservationPreference': 'open',
'CapacityReservationTarget': {
'CapacityReservationId': reservation_id
}
}
)
在上述代码中,通过为CapacityReservationPreference参数设置“open”选项,可以扩展到使用其他可提供的空间,而非Capacity Reservation时仍可以使用该选项。