You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用boto3通过AMI名称获取AMI ID以用于CloudFormation模板

基于EC2实例自动化创建Auto Scaling Group的CloudFormation模板实现

1. 获取指定名称的AMI ID

要通过boto3根据AMI名称获取对应的ID,可使用describe_images接口,并添加必要过滤条件确保拿到自己创建的可用AMI:

import boto3

def get_target_ami_id(ami_name):
    ec2_client = boto3.client('ec2')
    # 调用接口筛选符合条件的AMI
    response = ec2_client.describe_images(
        Filters=[
            {'Name': 'name', 'Values': [ami_name]},
            {'Name': 'state', 'Values': ['available']},
            {'Name': 'owner-id', 'Values': ['你的AWS账号ID']}  # 限定账号避免匹配到其他用户的AMI
        ]
    )
    
    # 返回第一个匹配的AMI ID,无匹配则抛出异常
    if response['Images']:
        return response['Images'][0]['ImageId']
    raise RuntimeError(f"未找到名称为{ami_name}的可用AMI")

# 调用函数获取目标AMI ID
target_ami_id = get_target_ami_id("abc")

2. 将AMI ID传入CloudFormation模板生成流程

可以通过字符串替换或模板引擎动态填充CloudFormation模板中的AMI ID字段,以下是基础实现示例:

示例CloudFormation模板片段(带占位符)

Resources:
  TargetASG:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      MinSize: 1
      MaxSize: 3
      LaunchTemplate:
        LaunchTemplateId: !Ref TargetLaunchTemplate
        Version: !GetAtt TargetLaunchTemplate.LatestVersionNumber
  TargetLaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateData:
        ImageId: __TARGET_AMI_ID__  # 占位符
        InstanceType: t2.micro
        # 其他实例配置参数(如安全组、密钥对等)

Python填充模板代码

def generate_final_cfn_template(ami_id, template_path, output_path):
    # 读取原始模板内容
    with open(template_path, 'r', encoding='utf-8') as f:
        template_content = f.read()
    
    # 替换占位符为实际AMI ID
    updated_template = template_content.replace("__TARGET_AMI_ID__", ami_id)
    
    # 写入最终模板文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(updated_template)

# 调用生成最终模板
generate_final_cfn_template(target_ami_id, "base_cfn_template.yaml", "final_cfn_template.yaml")

注意:如果需要更复杂的模板生成逻辑,建议使用Jinja2等模板引擎来管理模板变量,提升可维护性。

内容的提问来源于stack exchange,提问作者Juanpa1103

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:31:02