【问题标题】:How to get free-tier AMI in AWS using python with boto3如何使用 python 和 boto3 在 AWS 中获取免费层级 AMI
【发布时间】:2020-07-29 23:33:11
【问题描述】:

我正在尝试在 python 中构建一个函数,以在特定区域创建一个新的 ec2 实例。 为了使该功能正常工作,我需要指定这个新实例的 AMI。 问题是同一个 AMI(例如 Amazon Linux)在不同区域有不同的 id,我不能在另一个区域实例中使用一个区域的图像。

我不明白如何在这个特定区域获得这个 AMI id

def create_instance(region):
        ec2 = boto3.resource('ec2', region)
        instances = ec2.create_instances(InstanceType='t2.micro',
                                         MinCount=1, MaxCount=1,
                                         ImageId='AMI-id') # What do I put here?

目前,除了它是 Linux 和免费层这一事实之外,AMI 是什么并不重要,因此搜索特定的已知免费层 Linux AMI 可能会起作用。

我知道您可以使用 describe_images() 函数获取所有 AMI,但我如何仅过滤那些 Linux(可能是特定版本)和 免费层

boto3.client('ec2').describe_images(Filters["""What do I write here to get only linux free-tier AMI"""])

【问题讨论】:

  • TBH,我会避免这种情况。这里最常见的模式是只有一个静态字典映射区域:AMI
  • 这是迄今为止我能找到的唯一解决方案,只是看起来有点“硬编码”,我认为必须有一个更优雅和通用的解决方案。
  • 甚至 AWS 的官方 cloudformation 示例都使用静态硬编码映射
  • 其实现在推荐使用Systems Manager Parameter Store来获取映射。见:Query for the latest Amazon Linux AMI IDs using AWS Systems Manager Parameter Store | AWS Compute Blog

标签: python amazon-web-services amazon-ec2 boto3 amazon-ami


【解决方案1】:

AWS System Manager 在/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 维护 AWS Linux 2 AMI 的精选列表

这是 CLI 调用:

$ aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 --region us-east-1

{
    "Parameters": [
        {
            "Name": "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
            "Type": "String",
            "Value": "ami-0323c3dd2da7fb37d",
            "Version": 27,
            "LastModifiedDate": 1586395100.713,
            "ARN": "arn:aws:ssm:us-east-1::parameter/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"
        }
    ],
    "InvalidParameters": []
}

您应该可以在 Python 中使用SSM BOTO3 API 执行相同的操作。

【讨论】:

    【解决方案2】:

    肖恩,试试这个……

    ec2_client= session.client('ec2', region_name=region_name)
    print(f'***region_name: {region_name}')
    response= ec2_client.describe_instance_types(  
    #InstanceTypes=['t2.micro']
    Filters=[
        {
            'Name': 'free-tier-eligible',
            'Values': ['true']
            }
        ]
    ) 
    #pprint(response['InstanceTypes'][0]['InstanceType'])
    
    instance_type= response['InstanceTypes'][0]['InstanceType']
    response= ec2_client.describe_images(
       Filters=[{'Name': 'name', 'Values': [instance_type]},]   
    )
    #pprint(response)
    
    for image in response['Images']:
         print(image['ImageId'])
    
     Result:**************************************
     ***region_name: ap-south-1
     ami-0e84c461
     ami-1154187e
     ami-2f0e7540
     ami-4d8aca22
     ami-50aeed3f
     ami-77a4e718
     ami-cce794a3
    

    希望对您有所帮助...
    r0ck

    【讨论】:

      【解决方案3】:

      这是我想出的脚本:

      import boto3
      from typing import Optional, List
      
      
      def get_ami_ids(names: Optional[List[str]]=None) -> List[str]:
          if names is None:
              names = [
                  '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'
              ]
          ssm = boto3.client('ssm')
          response = ssm.get_parameters(Names=names)
          metadata: dict = response['ResponseMetadata']
          if metadata['HTTPStatusCode'] == 200:
              params: List[dict] = response['Parameters']
              amis: List[str] = [p.get('Value') for p in params]
      
          return amis
      
      print(get_ami_ids())
      

      如果响应中有任何 AMI ID,这应该会为您提供一个列表。但是,我看不到在 anton 提供的答案中指定 AWS 区域的位置,如 AWS CLI 等效项。

      【讨论】:

        猜你喜欢
        • 2017-08-04
        • 2019-03-10
        • 1970-01-01
        • 1970-01-01
        • 2015-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-15
        相关资源
        最近更新 更多