求Python脚本:获取AWS Lightsail所有实例详情(已能获取EC2)
获取AWS EC2与Lightsail实例详情的Python脚本
你可以通过boto3的lightsail客户端来获取Lightsail实例的详情,以下是整合了EC2和Lightsail实例查询的完整脚本,输出字段与你提供的CLI命令完全对应:
import boto3 region = 'ap-south-1' # 获取EC2实例详情 ec2 = boto3.resource('ec2', region_name=region) print("=== EC2实例详情 ===") for instance in ec2.instances.all(): print( "Id: {0}\nPlatform: {1}\nType: {2}\nPublic IPv4: {3}\nAMI: {4}\nState: {5}\nTags: {6}\n".format( instance.id, instance.platform, instance.instance_type, instance.public_ip_address, instance.image.id, instance.state, instance.tags ) ) # 获取Lightsail实例详情 lightsail = boto3.client('lightsail', region_name=region) print("\n=== Lightsail实例详情 ===") response = lightsail.get_instances() for instance in response['instances']: blueprint_id = instance.get('blueprintId') public_ip = instance.get('publicIpAddress') tags = instance.get('tags') name = instance.get('name') print( "名称: {0}\n蓝图ID: {1}\n公网IP: {2}\n标签: {3}\n".format( name, blueprint_id, public_ip, tags ) )
说明
- Lightsail暂不支持boto3的resource模式,因此使用client方式调用API,对应CLI的
get-instances命令 - 提取的字段与你指定的CLI查询参数完全一致:
blueprintId、publicIpAddress、Tags、name - 运行前需确保已通过环境变量、
~/.aws/credentials文件等方式配置好AWS访问凭证
内容的提问来源于stack exchange,提问作者Tejashree Ekhande
相关产品推荐
相关产品推荐

