boto3 aws api - 列出可用的实例类型

Oli*_*ver 9 python amazon-web-services instancetype boto3

实例类型:(t2.micro,t2.small,c4.large ...)这里列出的那些:http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html

我想通过boto3访问这些列表.就像是:

conn.get_all_instance_types()
Run Code Online (Sandbox Code Playgroud)

甚至

conn.describe_instance_types()['InstanceTypes'][0]['Name']
Run Code Online (Sandbox Code Playgroud)

在这个奇怪的api中,一切看起来都像.

我查看了客户端和ServiceResource的文档,但我找不到任何似乎接近的东西.我甚至没有找到一个hacky解决方案,列出了碰巧代表所有实例类型的其他内容.

谁有更多的boto3经验?

Tom*_*zky 7

现在有boto3.client('ec2').describe_instance_types()相应的 aws-cli 命令aws ec2 describe-instance-types

'''EC2 describe_instance_types usage example'''

import boto3

def ec2_instance_types(region_name):
    '''Yield all available EC2 instance types in region <region_name>'''
    ec2 = boto3.client('ec2', region_name=region_name)
    describe_args = {}
    while True:
        describe_result = ec2.describe_instance_types(**describe_args)
        yield from [i['InstanceType'] for i in describe_result['InstanceTypes']]
        if 'NextToken' not in describe_result:
            break
        describe_args['NextToken'] = describe_result['NextToken']

for ec2_type in ec2_instance_types('us-east-1'):
    print(ec2_type)
Run Code Online (Sandbox Code Playgroud)

预计大约 3 秒的运行时间。


gar*_*aat 6

EC2 API不提供获取所有EC2实例类型列表的方法.我希望它能做到.有些人通过刮样的网站拼凑自己的有效类型列表这个,但现在这是唯一的办法.

  • 从2015年12月开始,有一种方法可以从AWS Pricing API获取此信息。请参阅下面的答案:/sf/answers/3332743291/ (2认同)

Jas*_*man 6

可以在最近宣布的AWS Price List API提供的JSON中检索此信息。作为使用Python requests模块的简单示例:

#!/usr/bin/env python
# List EC2 Instance Types
# see: https://aws.amazon.com/blogs/aws/new-aws-price-list-api/

import requests

offers = requests.get(
    'https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.json'
)
ec2_offer_path = offers.json()['offers']['AmazonEC2']['currentVersionUrl']
ec2offer = requests.get(
    'https://pricing.us-east-1.amazonaws.com%s' % ec2_offer_path
).json()

uniq = set()
for sku, data in ec2offer['products'].items():
    if data['productFamily'] != 'Compute Instance':
        # skip anything that's not an EC2 Instance
        continue
    uniq.add(data['attributes']['instanceType'])
for itype in sorted(uniq):
    print(itype)
Run Code Online (Sandbox Code Playgroud)

请注意,这可能要花一些时间...直到今天,当前的EC2优惠JSON文件(https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index以.json)是173MB,所以需要一段时间都以检索和分析。当前结果是99个不同的实例类型。